diff --git a/.github/scripts/gen-build-failure-report.sh b/.github/scripts/gen-build-failure-report.sh index fd3215fc7fe..2dda69a3f33 100644 --- a/.github/scripts/gen-build-failure-report.sh +++ b/.github/scripts/gen-build-failure-report.sh @@ -24,12 +24,19 @@ # questions. # +# Import common utils +. .github/scripts/report-utils.sh + GITHUB_STEP_SUMMARY="$1" BUILD_DIR="$(ls -d build/*)" # Send signal to the do-build action that we failed touch "$BUILD_DIR/build-failure" +# Collect hs_errs for build-time crashes, e.g. javac, jmod, jlink, CDS. +# These usually land in make/ +hs_err_files=$(ls make/hs_err*.log 2> /dev/null || true) + ( echo '### :boom: Build failure summary' echo '' @@ -46,6 +53,20 @@ touch "$BUILD_DIR/build-failure" echo '' echo '' + for hs_err in $hs_err_files; do + echo "
View HotSpot error log: "$hs_err"" + echo '' + echo '```' + echo "$hs_err:" + echo '' + cat "$hs_err" + echo '```' + echo '
' + echo '' + done + echo '' echo ':arrow_right: To see the entire test log, click the job in the list to the left. To download logs, see the `failure-logs` [artifact above](#artifacts).' ) >> $GITHUB_STEP_SUMMARY + +truncate_summary diff --git a/.github/scripts/gen-test-results.sh b/.github/scripts/gen-test-results.sh index 9e85eef4dc0..bdf3eb3b9cb 100644 --- a/.github/scripts/gen-test-results.sh +++ b/.github/scripts/gen-test-results.sh @@ -24,6 +24,9 @@ # questions. # +# Import common utils +. .github/scripts/report-utils.sh + GITHUB_STEP_SUMMARY="$1" test_suite_name=$(cat build/run-test-prebuilt/test-support/test-last-ids.txt) @@ -89,18 +92,6 @@ for test in $failures $errors; do fi done >> $GITHUB_STEP_SUMMARY -# With many failures, the summary can easily exceed 1024 kB, the limit set by Github -# Trim it down if so. -summary_size=$(wc -c < $GITHUB_STEP_SUMMARY) -if [[ $summary_size -gt 1000000 ]]; then - # Trim to below 1024 kB, and cut off after the last detail group - head -c 1000000 $GITHUB_STEP_SUMMARY | tac | sed -n -e '/<\/details>/,$ p' | tac > $GITHUB_STEP_SUMMARY.tmp - mv $GITHUB_STEP_SUMMARY.tmp $GITHUB_STEP_SUMMARY - ( - echo '' - echo ':x: **WARNING: Summary is too large and has been truncated.**' - echo '' - ) >> $GITHUB_STEP_SUMMARY -fi - echo ':arrow_right: To see the entire test log, click the job in the list to the left.' >> $GITHUB_STEP_SUMMARY + +truncate_summary diff --git a/.github/scripts/report-utils.sh b/.github/scripts/report-utils.sh new file mode 100644 index 00000000000..da5b6c04b3c --- /dev/null +++ b/.github/scripts/report-utils.sh @@ -0,0 +1,41 @@ +#!/bin/bash +# +# 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. Oracle designates this +# particular file as subject to the "Classpath" exception as provided +# by Oracle in the LICENSE file that accompanied this code. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +function truncate_summary() { + # With large hs_errs, the summary can easily exceed 1024 kB, the limit set by Github + # Trim it down if so. + summary_size=$(wc -c < $GITHUB_STEP_SUMMARY) + if [[ $summary_size -gt 1000000 ]]; then + # Trim to below 1024 kB, and cut off after the last detail group + head -c 1000000 $GITHUB_STEP_SUMMARY | tac | sed -n -e '/<\/details>/,$ p' | tac > $GITHUB_STEP_SUMMARY.tmp + mv $GITHUB_STEP_SUMMARY.tmp $GITHUB_STEP_SUMMARY + ( + echo '' + echo ':x: **WARNING: Summary is too large and has been truncated.**' + echo '' + ) >> $GITHUB_STEP_SUMMARY + fi +} diff --git a/.jcheck/conf b/.jcheck/conf index 616d6926da1..70d14481809 100644 --- a/.jcheck/conf +++ b/.jcheck/conf @@ -1,7 +1,7 @@ [general] project=jdk-updates jbs=JDK -version=17.0.14 +version=17.0.15 [checks] error=author,committer,reviewers,merge,issues,executable,symlink,message,hg-tag,whitespace,problemlists diff --git a/closed/DDR.gmk b/closed/DDR.gmk index 327cfbd4890..c3d3e8f3c2f 100644 --- a/closed/DDR.gmk +++ b/closed/DDR.gmk @@ -1,5 +1,5 @@ # =========================================================================== -# (c) Copyright IBM Corp. 2018, 2022 All Rights Reserved +# (c) Copyright IBM Corp. 2018, 2025 All Rights Reserved # =========================================================================== # This code is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 only, as @@ -42,7 +42,7 @@ include $(TOPDIR)/make/common/MakeBase.gmk include $(TOPDIR)/make/common/JavaCompilation.gmk # The main source directory. -DDR_VM_SRC_ROOT := $(OPENJ9_TOPDIR)/debugtools/DDR_VM/src +DDR_VM_SRC_ROOT := $(J9JCL_SOURCES_DIR)/openj9.dtfj/share/classes # The top-level directory for intermediate artifacts. DDR_SUPPORT_DIR := $(SUPPORT_OUTPUTDIR)/ddr @@ -171,7 +171,7 @@ $(eval $(call SetupJavaCompilation,BUILD_J9DDR_TEST_CLASSES, \ --system none, \ BIN := $(DDR_TEST_BIN), \ CLASSPATH := $(DDR_CLASSES_BIN), \ - SRC := $(J9JCL_SOURCES_DIR)/openj9.dtfj/share/classes \ + SRC := $(DDR_VM_SRC_ROOT) \ )) .PHONY : compile_check diff --git a/closed/OpenJ9.gmk b/closed/OpenJ9.gmk index d62a8527ec5..dfd98e39ab2 100644 --- a/closed/OpenJ9.gmk +++ b/closed/OpenJ9.gmk @@ -1,5 +1,5 @@ # =========================================================================== -# (c) Copyright IBM Corp. 2017, 2024 All Rights Reserved +# (c) Copyright IBM Corp. 2017, 2025 All Rights Reserved # =========================================================================== # This code is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 only, as @@ -78,21 +78,10 @@ else OPENJ9_VERSION_STRING := $(OPENJ9_BRANCH)-$(OPENJ9_SHA) endif -ifeq (true,$(OPENJ9_ENABLE_CMAKE)) - # If a logging level was specified that shows commands, tell cmake to do likewise. - ifneq (,$(or $(filter true,$(LOG_CMDLINES)),$(filter debug trace,$(LOG_LEVEL)))) - MAKE_ARGS += VERBOSE=ON - endif -else - # MAKEFLAGS, as inherited from openjdk, includes options (e.g. '-r' and '-R') - # that don't work well with OpenJ9 and OMR when not using cmake. - unexport MAKEFLAGS - # Filter out unwanted make flags. - MAKE_ARGS := $(filter-out -R -r -s,$(MAKE_ARGS)) - ifneq (,$(JOBS)) - MAKE_ARGS += -j $(JOBS) - endif -endif # OPENJ9_ENABLE_CMAKE +# If a logging level was specified that shows commands, tell cmake to do likewise. +ifneq (,$(or $(filter true,$(LOG_CMDLINES)),$(filter debug trace,$(LOG_LEVEL)))) + MAKE_ARGS += VERBOSE=ON +endif # Propagate configure option '--disable-warnings-as-errors-omr' to OMR. ifeq (false,$(WARNINGS_AS_ERRORS_OMR)) @@ -124,31 +113,8 @@ endif clean-openj9-thirdparty-binaries \ openj9-config-headers \ run-preprocessors-j9 \ - stage-j9 \ # -# openj9_copy_tree -# ---------------- -# $1 = The target directory to create or update. -# $2 = The source directory to copy. -openj9_copy_tree = $(call openj9_copy_tree_impl,$(strip $1),$(strip $2)) - -OPENJ9_MARKER_FILE := .up-to-date - -# Use '-m' to update file modification times ('-m' is equivalent to '--touch' in some implementations of tar). -define openj9_copy_tree_impl - @$(MKDIR) -p $1 - @$(TAR) --create --directory=$2 $(if $(wildcard $1/$(OPENJ9_MARKER_FILE)),--newer=$1/$(OPENJ9_MARKER_FILE)) --exclude=.git . \ - | $(TAR) --extract --directory=$1 -m - @$(TOUCH) $1/$(OPENJ9_MARKER_FILE) -endef - -ifeq (true,$(OPENJ9_ENABLE_CMAKE)) - CONFIG_HEADERS := j9cfg.h omr/omrcfg.h -else - CONFIG_HEADERS := include/j9cfg.h omr/include_core/omrcfg.h -endif - define openj9_config_header_rules openj9-config-headers : $(SUPPORT_OUTPUTDIR)/openj9_include/$(notdir $1) @@ -157,7 +123,7 @@ define openj9_config_header_rules endef $(foreach file, \ - $(CONFIG_HEADERS), \ + j9cfg.h omr/omrcfg.h, \ $(eval $(call openj9_config_header_rules, $(OPENJ9_VM_BUILD_DIR)/$(file)))) # openj9_test_image_rules @@ -229,123 +195,6 @@ $(foreach file, \ $(if $(wildcard $(file)), \ $(eval $(call openj9_test_image_rules, $(file))))) -# Comments for stage-j9 -# Currently there is a staged location where j9 is built. This is due to a number of reasons: -# 1. make currently leaves output files in current directory -# 2. generated source and header files -# 3. repo layout compared to source.zip layout -# See issue 49 for more information and actions to correct this action. - -# Functions to generate sed program fragments. -# $1 - name of flag to be enabled or disabled. -SedDisable = -e '/"$(strip $1)"/s/"true"/"false"/g' -SedEnable = -e '/"$(strip $1)"/s/"false"/"true"/g' - -# Adjust features based on our configuration. -ifeq (true,$(OPENJ9_ENABLE_CUDA)) - FEATURE_SED_SCRIPT := $(call SedEnable,opt_cuda) -else - FEATURE_SED_SCRIPT := $(call SedDisable,opt_cuda) -endif - -# Function to generate sed program fragment. -# $1 - name of make macro to use instead of a hard-coded tool reference. -# $2 - suffix of uma_make_cmd property name to be adjusted. -SedUmaCommand = -e '/ $$@ - else ifeq (.spec,$(suffix $1)) - @$(SED) $(SPEC_SED_SCRIPT) < $$< > $$@ - else - @$(CP) $$< $$@ - endif -endef - -$(foreach file, \ - $(notdir $(wildcard $(OPENJ9_TOPDIR)/buildspecs/*)), \ - $(eval $(call openj9_stage_buildspec_file,$(file)))) - -stage-j9 : - @$(ECHO) Staging OpenJ9 runtime in $(OUTPUTDIR)/vm - $(call openj9_copy_tree,$(OUTPUTDIR)/vm,$(OPENJ9_TOPDIR)/runtime) - - @$(ECHO) Staging OpenJ9 OMR in $(OUTPUTDIR)/vm - $(call openj9_copy_tree,$(OUTPUTDIR)/vm/omr,$(OPENJ9OMR_TOPDIR)) - OPENJ9_VERSION_VARS := \ COMPANY_NAME \ COMPILER_VERSION_STRING \ @@ -395,9 +244,7 @@ run-preprocessors-j9 : \ $(OPENJ9_VM_BUILD_DIR)/compiler/jit.version \ $(OPENJ9_VM_BUILD_DIR)/include/openj9_version_info.h -ifeq (true,$(OPENJ9_ENABLE_CMAKE)) - - CMAKE_ARGS := \ +CMAKE_ARGS := \ -C $(OPENJ9_TOPDIR)/runtime/cmake/caches/$(patsubst %_cross,%,$(OPENJ9_BUILDSPEC)).cmake \ -DBOOT_JDK="$(BOOT_JDK)" \ -DBUILD_ID=$(BUILD_ID) \ @@ -411,102 +258,102 @@ ifeq (true,$(OPENJ9_ENABLE_CMAKE)) -DOPENJDK_VERSION_NUMBER_FOUR_POSITIONS=$(VERSION_NUMBER_FOUR_POSITIONS) \ # - # Windows can't specify compiler overrides since we already generated wrapper scripts. - ifneq (windows,$(OPENJDK_TARGET_OS)) - # Override the compilers if an OPENJ9_* value is specified. - # Otherwise, toolchain.cmake has the default values. - ifneq (,$(OPENJ9_CC)) - CMAKE_ARGS += -DCMAKE_C_COMPILER="$(OPENJ9_CC)" - endif - ifneq (,$(OPENJ9_CXX)) - CMAKE_ARGS += -DCMAKE_CXX_COMPILER="$(OPENJ9_CXX)" - endif - endif # windows - - ifneq (,$(CCACHE)) - # openjdk makefiles add a bunch of environemnt variables to the ccache command. - # CMake will not parse this properly, so we wrap the whole thing in the env command. - # We also need to add semicolons between arguments or else cmake will treat the whole - # thing as one long command name. - - # Note: We remove the CCACHE_COMPRESS option that openjdk adds, because it significantly - # slows down the build (to the point of erasing any gains from using ccache). - CCACHE_NOCOMPRESS := $(filter-out CCACHE_COMPRESS=1,$(CCACHE)) - ESCAPED_CCACHE := env$(subst $(SPACE),,$(addprefix ;,$(CCACHE_NOCOMPRESS))) - - CMAKE_ARGS += -DCMAKE_C_COMPILER_LAUNCHER="$(ESCAPED_CCACHE)" - CMAKE_ARGS += -DCMAKE_CXX_COMPILER_LAUNCHER="$(ESCAPED_CCACHE)" - endif # CCACHE - - ifeq (true,$(OPENJ9_ENABLE_JFR)) - CMAKE_ARGS += -DJ9VM_OPT_JFR=ON - else # OPENJ9_ENABLE_JFR - CMAKE_ARGS += -DJ9VM_OPT_JFR=OFF - endif # OPENJ9_ENABLE_JFR - - ifeq (true,$(OPENJ9_ENABLE_JITSERVER)) - CMAKE_ARGS += -DJ9VM_OPT_JITSERVER=ON - - ifneq (,$(OPENSSL_CFLAGS)) - CMAKE_ARGS += -DOPENSSL_CFLAGS="$(OPENSSL_CFLAGS)" - endif - - ifneq (,$(OPENSSL_DIR)) - CMAKE_ARGS += -DOPENSSL_DIR="$(OPENSSL_DIR)" - endif - - ifneq (,$(OPENSSL_BUNDLE_LIB_PATH)) - CMAKE_ARGS += -DOPENSSL_BUNDLE_LIB_PATH="$(OPENSSL_BUNDLE_LIB_PATH)" - endif - else - CMAKE_ARGS += -DJ9VM_OPT_JITSERVER=OFF - endif # OPENJ9_ENABLE_JITSERVER - - ifeq (true,$(OPENJ9_ENABLE_SNAPSHOTS)) - CMAKE_ARGS += -DJ9VM_OPT_SNAPSHOTS=ON - else # OPENJ9_ENABLE_SNAPSHOTS - CMAKE_ARGS += -DJ9VM_OPT_SNAPSHOTS=OFF - endif # OPENJ9_ENABLE_SNAPSHOTS - - ifeq (true,$(OPENJ9_ENABLE_CUDA)) - CMAKE_ARGS += -DJ9VM_OPT_CUDA=ON -DOMR_CUDA_HOME="$(call UnixPath,$(CUDA_HOME))" - else # OPENJ9_ENABLE_CUDA - CMAKE_ARGS += -DJ9VM_OPT_CUDA=OFF - endif # OPENJ9_ENABLE_CUDA - - ifeq (true,$(OPENJ9_ENABLE_INLINE_TYPES)) - CMAKE_ARGS += -DJ9VM_OPT_VALHALLA_VALUE_TYPES=ON - else # OPENJ9_ENABLE_INLINE_TYPES - CMAKE_ARGS += -DJ9VM_OPT_VALHALLA_VALUE_TYPES=OFF - endif # OPENJ9_ENABLE_INLINE_TYPES - - ifeq (true,$(OPENJ9_ENABLE_CRAC_SUPPORT)) - CMAKE_ARGS += -DJ9VM_OPT_CRAC_SUPPORT=ON - else # OPENJ9_ENABLE_CRAC_SUPPORT - CMAKE_ARGS += -DJ9VM_OPT_CRAC_SUPPORT=OFF - endif # OPENJ9_ENABLE_CRAC_SUPPORT - - ifeq (true,$(OPENJ9_ENABLE_CRIU_SUPPORT)) - CMAKE_ARGS += -DJ9VM_OPT_CRIU_SUPPORT=ON - else # OPENJ9_ENABLE_CRIU_SUPPORT - CMAKE_ARGS += -DJ9VM_OPT_CRIU_SUPPORT=OFF - endif # OPENJ9_ENABLE_CRIU_SUPPORT - - CMAKE_ARGS += -DJ9VM_OPT_METHOD_HANDLE=OFF - CMAKE_ARGS += -DJ9VM_OPT_OPENJDK_METHODHANDLE=ON - - # Propagate configure option '--disable-warnings-as-errors-omr' to OMR. - ifeq (false,$(WARNINGS_AS_ERRORS_OMR)) - CMAKE_ARGS += -DOMR_WARNINGS_AS_ERRORS=OFF +# Windows can't specify compiler overrides since we already generated wrapper scripts. +ifneq (windows,$(OPENJDK_TARGET_OS)) + # Override the compilers if an OPENJ9_* value is specified. + # Otherwise, toolchain.cmake has the default values. + ifneq (,$(OPENJ9_CC)) + CMAKE_ARGS += -DCMAKE_C_COMPILER="$(OPENJ9_CC)" + endif + ifneq (,$(OPENJ9_CXX)) + CMAKE_ARGS += -DCMAKE_CXX_COMPILER="$(OPENJ9_CXX)" + endif +endif # windows + +ifneq (,$(CCACHE)) + # openjdk makefiles add a bunch of environemnt variables to the ccache command. + # CMake will not parse this properly, so we wrap the whole thing in the env command. + # We also need to add semicolons between arguments or else cmake will treat the whole + # thing as one long command name. + + # Note: We remove the CCACHE_COMPRESS option that openjdk adds, because it significantly + # slows down the build (to the point of erasing any gains from using ccache). + CCACHE_NOCOMPRESS := $(filter-out CCACHE_COMPRESS=1,$(CCACHE)) + ESCAPED_CCACHE := env$(subst $(SPACE),,$(addprefix ;,$(CCACHE_NOCOMPRESS))) + + CMAKE_ARGS += -DCMAKE_C_COMPILER_LAUNCHER="$(ESCAPED_CCACHE)" + CMAKE_ARGS += -DCMAKE_CXX_COMPILER_LAUNCHER="$(ESCAPED_CCACHE)" +endif # CCACHE + +ifeq (true,$(OPENJ9_ENABLE_JFR)) + CMAKE_ARGS += -DJ9VM_OPT_JFR=ON +else # OPENJ9_ENABLE_JFR + CMAKE_ARGS += -DJ9VM_OPT_JFR=OFF +endif # OPENJ9_ENABLE_JFR + +ifeq (true,$(OPENJ9_ENABLE_JITSERVER)) + CMAKE_ARGS += -DJ9VM_OPT_JITSERVER=ON + + ifneq (,$(OPENSSL_CFLAGS)) + CMAKE_ARGS += -DOPENSSL_CFLAGS="$(OPENSSL_CFLAGS)" endif - # Propagate configure option '--disable-warnings-as-errors-openj9' to OpenJ9. - ifeq (false,$(WARNINGS_AS_ERRORS_OPENJ9)) - CMAKE_ARGS += -DJ9VM_WARNINGS_AS_ERRORS=OFF - endif + ifneq (,$(OPENSSL_DIR)) + CMAKE_ARGS += -DOPENSSL_DIR="$(OPENSSL_DIR)" + endif - # Do this last so extra args take precedence. - CMAKE_ARGS += $(EXTRA_CMAKE_ARGS) + ifneq (,$(OPENSSL_BUNDLE_LIB_PATH)) + CMAKE_ARGS += -DOPENSSL_BUNDLE_LIB_PATH="$(OPENSSL_BUNDLE_LIB_PATH)" + endif +else + CMAKE_ARGS += -DJ9VM_OPT_JITSERVER=OFF +endif # OPENJ9_ENABLE_JITSERVER + +ifeq (true,$(OPENJ9_ENABLE_SNAPSHOTS)) + CMAKE_ARGS += -DJ9VM_OPT_SNAPSHOTS=ON +else # OPENJ9_ENABLE_SNAPSHOTS + CMAKE_ARGS += -DJ9VM_OPT_SNAPSHOTS=OFF +endif # OPENJ9_ENABLE_SNAPSHOTS + +ifeq (true,$(OPENJ9_ENABLE_CUDA)) + CMAKE_ARGS += -DJ9VM_OPT_CUDA=ON -DOMR_CUDA_HOME="$(call UnixPath,$(CUDA_HOME))" +else # OPENJ9_ENABLE_CUDA + CMAKE_ARGS += -DJ9VM_OPT_CUDA=OFF +endif # OPENJ9_ENABLE_CUDA + +ifeq (true,$(OPENJ9_ENABLE_INLINE_TYPES)) + CMAKE_ARGS += -DJ9VM_OPT_VALHALLA_VALUE_TYPES=ON +else # OPENJ9_ENABLE_INLINE_TYPES + CMAKE_ARGS += -DJ9VM_OPT_VALHALLA_VALUE_TYPES=OFF +endif # OPENJ9_ENABLE_INLINE_TYPES + +ifeq (true,$(OPENJ9_ENABLE_CRAC_SUPPORT)) + CMAKE_ARGS += -DJ9VM_OPT_CRAC_SUPPORT=ON +else # OPENJ9_ENABLE_CRAC_SUPPORT + CMAKE_ARGS += -DJ9VM_OPT_CRAC_SUPPORT=OFF +endif # OPENJ9_ENABLE_CRAC_SUPPORT + +ifeq (true,$(OPENJ9_ENABLE_CRIU_SUPPORT)) + CMAKE_ARGS += -DJ9VM_OPT_CRIU_SUPPORT=ON +else # OPENJ9_ENABLE_CRIU_SUPPORT + CMAKE_ARGS += -DJ9VM_OPT_CRIU_SUPPORT=OFF +endif # OPENJ9_ENABLE_CRIU_SUPPORT + +CMAKE_ARGS += -DJ9VM_OPT_METHOD_HANDLE=OFF +CMAKE_ARGS += -DJ9VM_OPT_OPENJDK_METHODHANDLE=ON + +# Propagate configure option '--disable-warnings-as-errors-omr' to OMR. +ifeq (false,$(WARNINGS_AS_ERRORS_OMR)) + CMAKE_ARGS += -DOMR_WARNINGS_AS_ERRORS=OFF +endif + +# Propagate configure option '--disable-warnings-as-errors-openj9' to OpenJ9. +ifeq (false,$(WARNINGS_AS_ERRORS_OPENJ9)) + CMAKE_ARGS += -DJ9VM_WARNINGS_AS_ERRORS=OFF +endif + +# Do this last so extra args take precedence. +CMAKE_ARGS += $(EXTRA_CMAKE_ARGS) $(OUTPUTDIR)/vm/cmake.stamp : @$(MKDIR) -p $(@D) @@ -515,27 +362,6 @@ $(OUTPUTDIR)/vm/cmake.stamp : run-preprocessors-j9 : $(OUTPUTDIR)/vm/cmake.stamp -else # OPENJ9_ENABLE_CMAKE - -run-preprocessors-j9 : stage-j9 - @$(ECHO) Running OpenJ9 preprocessors with OPENJ9_BUILDSPEC: $(OPENJ9_BUILDSPEC) - +BOOT_JDK=$(BOOT_JDK) $(EXPORT_COMPILER_ENV_VARS) OPENJDK_VERSION_NUMBER_FOUR_POSITIONS=$(VERSION_NUMBER_FOUR_POSITIONS) \ - $(MAKE) $(MAKE_ARGS) -C $(OUTPUTDIR)/vm -f $(OPENJ9_TOPDIR)/runtime/buildtools.mk \ - BUILD_ID=$(BUILD_ID) \ - DEST_DIR=$(call MixedPath,$(J9TOOLS_DIR)) \ - EXTRA_CONFIGURE_ARGS=$(OMR_EXTRA_CONFIGURE_ARGS) \ - FREEMARKER_JAR="$(FREEMARKER_JAR)" \ - J9VM_SHA=$(OPENJ9_SHA) \ - JAVA_HOME=$(BOOT_JDK) \ - OMR_DIR=$(OUTPUTDIR)/vm/omr \ - SOURCETOOLS_DIR=$(call MixedPath,$(OPENJ9_TOPDIR))/sourcetools \ - SPEC=$(OPENJ9_BUILDSPEC) \ - UMA_OPTIONS_EXTRA="-buildDate $(shell date +'%Y%m%d')" \ - VERSION_MAJOR=$(VERSION_FEATURE) \ - tools - -endif # OPENJ9_ENABLE_CMAKE - CUSTOM_COMPILER_ENV_VARS := ifneq (,$(OPENJ9_CC)) @@ -547,31 +373,11 @@ endif ifneq (,$(OPENJ9_DEVELOPER_DIR)) CUSTOM_COMPILER_ENV_VARS += DEVELOPER_DIR="$(OPENJ9_DEVELOPER_DIR)" endif -ifeq (true,$(OPENJ9_ENABLE_JITSERVER)) - ifneq (true,$(OPENJ9_ENABLE_CMAKE)) - CUSTOM_COMPILER_ENV_VARS += J9VM_OPT_JITSERVER=1 - - ifneq (,$(OPENSSL_CFLAGS)) - CUSTOM_COMPILER_ENV_VARS += OPENSSL_CFLAGS="$(OPENSSL_CFLAGS)" - endif - - ifneq (,$(OPENSSL_DIR)) - CUSTOM_COMPILER_ENV_VARS += OPENSSL_DIR="$(OPENSSL_DIR)" - endif - - ifneq (,$(OPENSSL_BUNDLE_LIB_PATH)) - CUSTOM_COMPILER_ENV_VARS += OPENSSL_BUNDLE_LIB_PATH="$(OPENSSL_BUNDLE_LIB_PATH)" - endif - endif # OPENJ9_ENABLE_CMAKE -endif # OPENJ9_ENABLE_JITSERVER ifneq (true,$(OPENJ9_ENABLE_DDR)) DDR_COMMAND := -else ifeq (true,$(OPENJ9_ENABLE_CMAKE)) - DDR_COMMAND := $(EXPORT_COMPILER_ENV_VARS) $(MAKE) $(MAKE_ARGS) -C $(OPENJ9_VM_BUILD_DIR) j9ddr else - DDR_COMMAND := CC="$(CC)" CXX="$(CXX)" $(EXPORT_COMPILER_ENV_VARS) \ - $(MAKE) $(MAKE_ARGS) -C $(OUTPUTDIR)/vm/ddr -f run_omrddrgen.mk + DDR_COMMAND := $(EXPORT_COMPILER_ENV_VARS) $(MAKE) $(MAKE_ARGS) -C $(OPENJ9_VM_BUILD_DIR) j9ddr endif # OPENJ9_ENABLE_DDR build-j9 : run-preprocessors-j9 diff --git a/closed/autoconf/custom-hook.m4 b/closed/autoconf/custom-hook.m4 index 930e5126e4e..d1d142a6101 100644 --- a/closed/autoconf/custom-hook.m4 +++ b/closed/autoconf/custom-hook.m4 @@ -1,5 +1,5 @@ # =========================================================================== -# (c) Copyright IBM Corp. 2017, 2024 All Rights Reserved +# (c) Copyright IBM Corp. 2017, 2025 All Rights Reserved # =========================================================================== # This code is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 only, as @@ -38,7 +38,6 @@ AC_DEFUN_ONCE([CUSTOM_EARLY_HOOK], OPENJ9_BASIC_SETUP_FUNDAMENTAL_TOOLS OPENJ9_PLATFORM_SETUP - OPENJ9_CONFIGURE_CMAKE OPENJ9_CONFIGURE_COMPILERS OPENJ9_CONFIGURE_CRAC_AND_CRIU_SUPPORT OPENJ9_CONFIGURE_CUDA @@ -51,55 +50,13 @@ AC_DEFUN_ONCE([CUSTOM_EARLY_HOOK], OPENJ9_CONFIGURE_NUMA OPENJ9_CONFIGURE_SNAPSHOTS OPENJ9_CONFIGURE_WARNINGS - OPENJ9_THIRD_PARTY_REQUIREMENTS OPENJ9_CHECK_NASM_VERSION OPENJCEPLUS_SETUP ]) -AC_DEFUN([OPENJ9_CONFIGURE_CMAKE], -[ - AC_ARG_WITH(cmake, [AS_HELP_STRING([--with-cmake], [enable building openJ9 with CMake])], - [ - if test "x$with_cmake" = xyes -o "x$with_cmake" = x ; then - with_cmake=cmake - fi - ], - [ - case "$OPENJ9_PLATFORM_CODE" in - ap64|oa64|or64|wa64|xa64|xl64|xr64|xz64) - if test "x$COMPILE_TYPE" != xcross ; then - with_cmake=cmake - else - with_cmake=no - fi - ;; - *) - with_cmake=no - ;; - esac - ]) - # at this point with_cmake should either be no, or the name of the cmake command - if test "x$with_cmake" = xno ; then - OPENJ9_ENABLE_CMAKE=false - - # Currently, mixedrefs mode is only available with CMake enabled - if test "x$OMR_MIXED_REFERENCES_MODE" != xoff ; then - AC_MSG_ERROR([[--with-mixedrefs=[static|dynamic] requires --with-cmake]]) - fi - else - OPENJ9_ENABLE_CMAKE=true - if AS_EXECUTABLE_P(["$with_cmake"]) ; then - CMAKE="$with_cmake" - else - UTIL_REQUIRE_PROGS([CMAKE], [$with_cmake]) - fi - fi - - AC_SUBST(OPENJ9_ENABLE_CMAKE) -]) - AC_DEFUN([OPENJ9_BASIC_SETUP_FUNDAMENTAL_TOOLS], [ + UTIL_REQUIRE_PROGS(CMAKE, cmake) UTIL_REQUIRE_PROGS(M4, m4) ]) @@ -621,52 +578,6 @@ AC_DEFUN([OPENJ9_PLATFORM_SETUP], AC_SUBST(OMR_MIXED_REFERENCES_MODE) ]) -AC_DEFUN([OPENJ9_THIRD_PARTY_REQUIREMENTS], -[ - # check 3rd party library requirement for UMA - AC_ARG_WITH(freemarker-jar, [AS_HELP_STRING([--with-freemarker-jar], - [path to freemarker.jar (used to build OpenJ9 build tools)])]) - - FREEMARKER_JAR= - if test "x$OPENJ9_ENABLE_CMAKE" != xtrue ; then - AC_MSG_CHECKING([that freemarker location is set]) - if test "x$with_freemarker_jar" = x -o "x$with_freemarker_jar" = xno ; then - AC_MSG_RESULT([no]) - printf "\n" - printf "The FreeMarker library is required to build the OpenJ9 build tools\n" - printf "and has to be provided during configure process.\n" - printf "\n" - printf "Download the FreeMarker library and unpack it into an arbitrary directory:\n" - printf "\n" - printf "wget https://sourceforge.net/projects/freemarker/files/freemarker/2.3.8/freemarker-2.3.8.tar.gz/download -O freemarker-2.3.8.tar.gz\n" - printf "\n" - printf "tar -xzf freemarker-2.3.8.tar.gz\n" - printf "\n" - printf "Then run configure with '--with-freemarker-jar='\n" - printf "\n" - - AC_MSG_ERROR([Cannot continue]) - else - AC_MSG_RESULT([yes]) - AC_MSG_CHECKING([checking that '$with_freemarker_jar' exists]) - if test -f "$with_freemarker_jar" ; then - AC_MSG_RESULT([yes]) - else - AC_MSG_RESULT([no]) - AC_MSG_ERROR([freemarker.jar not found at '$with_freemarker_jar']) - fi - fi - - if test "x$OPENJDK_BUILD_OS_ENV" = xwindows.cygwin ; then - FREEMARKER_JAR=`$PATHTOOL -m "$with_freemarker_jar"` - else - FREEMARKER_JAR=$with_freemarker_jar - fi - fi - - AC_SUBST(FREEMARKER_JAR) -]) - AC_DEFUN([OPENJ9_CHECK_NASM_VERSION], [ OPENJ9_PLATFORM_EXTRACT_VARS_FROM_CPU($host_cpu) diff --git a/closed/autoconf/custom-spec.gmk.in b/closed/autoconf/custom-spec.gmk.in index b1c9f1f5194..25c840c5f6a 100644 --- a/closed/autoconf/custom-spec.gmk.in +++ b/closed/autoconf/custom-spec.gmk.in @@ -1,5 +1,5 @@ # =========================================================================== -# (c) Copyright IBM Corp. 2017, 2024 All Rights Reserved +# (c) Copyright IBM Corp. 2017, 2025 All Rights Reserved # =========================================================================== # This code is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License version 2 only, as @@ -88,10 +88,7 @@ J9JDK_EXT_NAME := Extensions for OpenJDK for Eclipse OpenJ9 # required by CMake CMAKE := @CMAKE@ -OPENJ9_ENABLE_CMAKE := @OPENJ9_ENABLE_CMAKE@ -# required by UMA -FREEMARKER_JAR := @FREEMARKER_JAR@ OPENJ9_BUILDSPEC := @OPENJ9_BUILDSPEC@ # required by JPP @@ -169,11 +166,7 @@ PERL := @PERL@ WITH_OPENSSL := @WITH_OPENSSL@ # Use '=' instead of ':=' because bootcycle-spec.gmk overrides OUTPUTDIR. -ifeq (true,$(OPENJ9_ENABLE_CMAKE)) - OPENJ9_VM_BUILD_DIR = $(OUTPUTDIR)/vm/runtime -else - OPENJ9_VM_BUILD_DIR = $(OUTPUTDIR)/vm -endif +OPENJ9_VM_BUILD_DIR = $(OUTPUTDIR)/vm/runtime # Enable use of j9cfg.h in openjdk native code. $(foreach var, \ diff --git a/closed/openjdk-tag.gmk b/closed/openjdk-tag.gmk index 548b2c08d15..f361d3da234 100644 --- a/closed/openjdk-tag.gmk +++ b/closed/openjdk-tag.gmk @@ -1 +1 @@ -OPENJDK_TAG := jdk-17.0.14+7 +OPENJDK_TAG := jdk-17.0.15+1 diff --git a/closed/src/java.base/aix/native/libjncrypto/NativeCrypto_md.c b/closed/src/java.base/aix/native/libjncrypto/NativeCrypto_md.c deleted file mode 100644 index 440fea8e0f5..00000000000 --- a/closed/src/java.base/aix/native/libjncrypto/NativeCrypto_md.c +++ /dev/null @@ -1,84 +0,0 @@ -/* - * =========================================================================== - * (c) Copyright IBM Corp. 2019, 2023 All Rights Reserved - * =========================================================================== - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * IBM designates this particular file as subject to the "Classpath" exception - * as provided by IBM in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, see . - * - * =========================================================================== - */ - -#include -#include -#include -#include -#include -#include "NativeCrypto_md.h" - -/* Load the crypto library (return NULL on error) */ -void * load_crypto_library(jboolean traceEnabled) { - void * result = NULL; - const char *libname3_a_64 = "libcrypto.a(libcrypto64.so.3)"; - const char *libname3_64 = "libcrypto64.so.3"; - const char *libname3_a = "libcrypto.a(libcrypto.so.3)"; - const char *libname3 = "libcrypto.so.3"; - const char *libname111 = "libcrypto.a(libcrypto64.so.1.1)"; - const char *libname110 = "libcrypto.so.1.1"; - const char *libname102 = "libcrypto.so.1.0.0"; - const char *symlink = "libcrypto.a(libcrypto64.so)"; - - result = dlopen (libname3_a_64, RTLD_NOW | RTLD_MEMBER); - if (result == NULL) { - result = dlopen (libname3_64, RTLD_NOW); - if (result == NULL) { - result = dlopen (libname3_a, RTLD_NOW | RTLD_MEMBER); - if (result == NULL) { - result = dlopen (libname3, RTLD_NOW); - if (result == NULL) { - result = dlopen (libname111, RTLD_NOW | RTLD_MEMBER); - if (result == NULL) { - result = dlopen (libname110, RTLD_NOW); - if (result == NULL) { - result = dlopen (libname102, RTLD_NOW); - if (result == NULL) { - result = dlopen (symlink, RTLD_NOW | RTLD_MEMBER); - } - } - } - } - } - } - } - return result; -} - -/* Unload the crypto library */ -void unload_crypto_library(void *handle) { - (void)dlclose(handle); -} - -/* Find the symbol in the crypto library (return NULL if not found) */ -void * find_crypto_symbol(void *handle, const char *symname) { - return dlsym(handle, symname); -} - -/* Find the path that the library was loaded from */ -void get_library_path(void * handle, char * library_path) { - /* There doesnt seem to be an easy way to find */ - /* the library path, so return "Unknown path" */ - strcpy(library_path, "Unknown path"); -} diff --git a/closed/src/java.base/macosx/native/libjncrypto/NativeCrypto_md.c b/closed/src/java.base/macosx/native/libjncrypto/NativeCrypto_md.c deleted file mode 100644 index d0e361760ec..00000000000 --- a/closed/src/java.base/macosx/native/libjncrypto/NativeCrypto_md.c +++ /dev/null @@ -1,75 +0,0 @@ -/* - * =========================================================================== - * (c) Copyright IBM Corp. 2019, 2023 All Rights Reserved - * =========================================================================== - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * IBM designates this particular file as subject to the "Classpath" exception - * as provided by IBM in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, see . - * - * =========================================================================== - */ - -#include -#include -#include -#include -#include -#include "NativeCrypto_md.h" - -/* Load the crypto library (return NULL on error) */ -void * load_crypto_library(jboolean traceEnabled) { - void * result = NULL; - - const char *libname3 = "libcrypto.3.dylib"; - const char *libname = "libcrypto.1.1.dylib"; - const char *oldname = "libcrypto.1.0.0.dylib"; - const char *symlink = "libcrypto.dylib"; - - result = dlopen (libname3, RTLD_NOW); - if (result == NULL) { - result = dlopen (libname, RTLD_NOW); - if (result == NULL) { - result = dlopen (oldname, RTLD_NOW); - if (result == NULL) { - result = dlopen (symlink, RTLD_NOW); - } - } - } - - return result; -} - -/* Unload the crypto library */ -void unload_crypto_library(void *handle) { - (void)dlclose(handle); -} - -/* Find the symbol in the crypto library (return NULL if not found) */ -void * find_crypto_symbol(void *handle, const char *symname) { - return dlsym(handle, symname); -} - -/* Find the path that the library was loaded from */ -void get_library_path(void * handle, char * library_path) { - Dl_info info; - // Load binary path information from dlinfo() API if available, - // else return "Unknown path" - if (dladdr(handle, &info)) { - strcpy(library_path, info.dli_fname); - } else { - strcpy(library_path, "Unknown path"); - } -} diff --git a/closed/src/java.base/share/classes/jdk/crypto/jniprovider/NativeCrypto.java b/closed/src/java.base/share/classes/jdk/crypto/jniprovider/NativeCrypto.java index d2132df6398..423a97d6a6c 100644 --- a/closed/src/java.base/share/classes/jdk/crypto/jniprovider/NativeCrypto.java +++ b/closed/src/java.base/share/classes/jdk/crypto/jniprovider/NativeCrypto.java @@ -1,6 +1,6 @@ /* * =========================================================================== - * (c) Copyright IBM Corp. 2018, 2024 All Rights Reserved + * (c) Copyright IBM Corp. 2018, 2025 All Rights Reserved * =========================================================================== * * This code is free software; you can redistribute it and/or modify it @@ -32,6 +32,7 @@ import jdk.internal.ref.CleanerFactory; import jdk.internal.reflect.Reflection; import jdk.internal.reflect.CallerSensitive; +import jdk.internal.util.StaticProperty; import sun.security.action.GetPropertyAction; @@ -81,16 +82,31 @@ private static final class InstanceHolder { private final boolean isOpenSSLFIPS; + @SuppressWarnings("restricted") private static long loadCryptoLibraries() { long osslVersion; try { - // load jncrypto JNI library + // Load jncrypto JNI library. System.loadLibrary("jncrypto"); - // load OpenSSL crypto library dynamically - osslVersion = loadCrypto(traceEnabled); - if (traceEnabled && (osslVersion != -1)) { - System.err.println("Native crypto library load succeeded - using native crypto library."); + + // Get user-specified OpenSSL library to use, if available. + String nativeLibName = + GetPropertyAction.privilegedGetProperty("jdk.native.openssl.lib", ""); + + // Get the JDK location. + String javaHome = StaticProperty.javaHome(); + + // Load OpenSSL crypto library dynamically. + osslVersion = loadCrypto(traceEnabled, nativeLibName, javaHome); + if (osslVersion != -1) { + if (traceEnabled) { + System.err.println("Native crypto library load succeeded - using native crypto library."); + } + } else { + if (!nativeLibName.isEmpty()) { + throw new RuntimeException(nativeLibName + " is not available, crypto libraries are not loaded"); + } } } catch (UnsatisfiedLinkError usle) { if (traceEnabled) { @@ -98,7 +114,7 @@ private static long loadCryptoLibraries() { System.err.println("Warning: Native crypto library load failed." + " Using Java crypto implementation."); } - // signal load failure + // Signal load failure. osslVersion = -1; } return osslVersion; @@ -253,14 +269,18 @@ public void run() { }); } - /* Native digest interfaces */ + /* OpenSSL utility interfaces */ - private static final native long loadCrypto(boolean trace); + private static final native long loadCrypto(boolean trace, + String libName, + String javaHome); public static final native boolean isMD5Available(); private static final native boolean isOpenSSLFIPS(); + /* Native digest interfaces */ + public final native long DigestCreateContext(long nativeBuffer, int algoIndex); diff --git a/closed/src/java.base/share/native/libjncrypto/NativeCrypto.c b/closed/src/java.base/share/native/libjncrypto/NativeCrypto.c index 2e53d0a8e1e..c28822a0a68 100644 --- a/closed/src/java.base/share/native/libjncrypto/NativeCrypto.c +++ b/closed/src/java.base/share/native/libjncrypto/NativeCrypto.c @@ -1,6 +1,6 @@ /* * =========================================================================== - * (c) Copyright IBM Corp. 2018, 2024 All Rights Reserved + * (c) Copyright IBM Corp. 2018, 2025 All Rights Reserved * =========================================================================== * * This code is free software; you can redistribute it and/or modify it @@ -22,6 +22,20 @@ * =========================================================================== */ +#if defined(_AIX) +#include +#include +#define DLFCN_LDINFO_SIZE (sizeof(struct ld_info) + _XOPEN_PATH_MAX + _XOPEN_NAME_MAX) +#elif defined(__APPLE__) /* defined(_AIX) */ +#include +#include +#elif defined(__linux__) /* defined(__APPLE__) */ +#include +#include +#elif defined(_WIN32) /* defined(__linux__) */ +#include +#endif /* defined(_AIX) */ + #include #include #include @@ -37,7 +51,6 @@ #include #include "jdk_crypto_jniprovider_NativeCrypto.h" -#include "NativeCrypto_md.h" #define OPENSSL_VERSION_CODE(major, minor, fix, patch) \ ((((jlong)(major)) << 28) | ((minor) << 20) | ((fix) << 12) | (patch)) @@ -64,6 +77,11 @@ # include #endif /* defined(WINDOWS) */ +/* Header for NativeCrypto loading methods. */ +static void * find_crypto_symbol(void *handle, const char *symname); +static void * find_crypto_library(jboolean traceEnabled, const char *chomepath); +static void unload_crypto_library(void *handle); + /* Header for RSA algorithm using 1.0.2 OpenSSL. */ int OSSL102_RSA_set0_key(RSA *, BIGNUM *, BIGNUM *, BIGNUM *); int OSSL102_RSA_set0_factors(RSA *, BIGNUM *, BIGNUM *); @@ -380,30 +398,114 @@ JNIEXPORT jboolean JNICALL Java_jdk_crypto_jniprovider_NativeCrypto_isOpenSSLFIP return OSSL_IS_FIPS; } -/* - * Class: jdk_crypto_jniprovider_NativeCrypto - * Method: loadCrypto - * Signature: (Z)J - */ -JNIEXPORT jlong JNICALL Java_jdk_crypto_jniprovider_NativeCrypto_loadCrypto - (JNIEnv *env, jclass thisObj, jboolean trace) +/* Unload the crypto library. */ +static void +unload_crypto_library(void *crypto_library) { - typedef const char* OSSL_version_t(int); +#if defined(_WIN32) + FreeLibrary(crypto_library); +#else /* defined(_WIN32) */ + (void)dlclose(crypto_library); +#endif /* defined(_WIN32) */ +} - /* Determine the version of OpenSSL. */ - OSSL_version_t* OSSL_version; - const char * openssl_version; - jlong ossl_ver = 0; +/* Find the symbol in the crypto library (return NULL if not found). */ +static void * +find_crypto_symbol(void *crypto_library, const char *symname) +{ +#if defined(_WIN32) + return GetProcAddress(crypto_library, symname); +#else /* defined(_WIN32) */ + return dlsym(crypto_library, symname); +#endif /* defined(_WIN32) */ +} - /* Load OpenSSL Crypto library */ - crypto_library = load_crypto_library(trace); - if (NULL == crypto_library) { - if (trace) { - fprintf(stderr, "Error loading OpenSSL: FAILED TO LOAD OPENSSL CRYPTO LIBRARY\n"); - fflush(stderr); +static void +log_crypto_library_path(jboolean traceEnabled, void *crypto_library, const char *message) +{ + if (traceEnabled && (NULL != crypto_library)) { +#if defined(_AIX) + int rc = 0; + /* Initialize the buffer with maximum size for L_GETINFO. */ + char *buffer = (char *)malloc(DLFCN_LDINFO_SIZE); + if (NULL == buffer) { + return; } - return -1; + /* Get the list of all object files loaded by this process. */ + rc = loadquery(L_GETINFO, buffer, DLFCN_LDINFO_SIZE); + + /* Parse the list of all object files and print the OPENSSL library path. */ + if (0 == rc) { + char *buf = buffer; + for (;;) { + struct ld_info *cur_info = (struct ld_info *)buf; + const char *path = cur_info->ldinfo_filename; + const char *member_name = path + strlen(cur_info->ldinfo_filename) + 1; + if (('\0' != *member_name) && (NULL != strstr(path, "/libcrypto"))) { + fprintf(stdout, "%s: %s(%s)\n", message, path, member_name); + fflush(stdout); + break; + } + if (0 == cur_info->ldinfo_next) { + break; + } + buf += cur_info->ldinfo_next; + } + } + free(buffer); +#elif defined(__APPLE__) /* defined(_AIX) */ + /* Since we know the image we want will always be near the end of the list, start there and go backwards. */ + uint32_t i = _dyld_image_count() - 1; + for (; i >= 0; i--) { + const char *image_name = _dyld_get_image_name(i); + void *probe_handle = NULL; + jboolean same_handle = JNI_FALSE; + if (NULL == image_name) { + continue; + } + + /* Why dlopen doesn't affect _dyld stuff: if an image is already loaded, it returns the existing handle. */ + probe_handle = dlopen(image_name, RTLD_LAZY); + if (NULL == probe_handle) { + continue; + } + if (crypto_library == probe_handle) { + same_handle = JNI_TRUE; + } + dlclose(probe_handle); + + if (same_handle) { + fprintf(stdout, "OpenSSL was loaded from - %s\n", image_name); + fflush(stdout); + break; + } + } +#elif defined(_WIN32) /* defined(__APPLE__) */ + char path[MAX_PATH]; + DWORD written = GetModuleFileName(crypto_library, path, MAX_PATH); + if (0 != written) { + fprintf(stdout, "OpenSSL was loaded from - %s\n", path); + fflush(stdout); + } +#else /* defined(_WIN32) */ + struct link_map *map = NULL; + int ret = dlinfo(crypto_library, RTLD_DI_LINKMAP, &map); + if ((0 == ret) && (NULL != map)) { + fprintf(stdout, "OpenSSL was loaded from - %s\n", map->l_name); + fflush(stdout); + } +#endif /* defined(_AIX) */ } +} + +/* Get the version for the crypto library. */ +static jlong +get_crypto_library_version(jboolean traceEnabled, void *crypto_library, const char *message) +{ + typedef const char *OSSL_version_t(int); + OSSL_version_t *OSSL_version = NULL; + const char *openssl_version = NULL; + jlong ossl_ver = 0; /* * Different symbols are used by OpenSSL with 1.0 and 1.1 and later. @@ -417,7 +519,7 @@ JNIEXPORT jlong JNICALL Java_jdk_crypto_jniprovider_NativeCrypto_loadCrypto OSSL_version = (OSSL_version_t*)find_crypto_symbol(crypto_library, "SSLeay_version"); if (NULL == OSSL_version) { - if (trace) { + if (traceEnabled) { fprintf(stderr, "Error loading OpenSSL: Error finding the OpenSSL version symbol in the crypto library\n"); fflush(stderr); } @@ -429,7 +531,7 @@ JNIEXPORT jlong JNICALL Java_jdk_crypto_jniprovider_NativeCrypto_loadCrypto /* Ensure the OpenSSL version is "OpenSSL 1.0.x" */ ossl_ver = extractVersionToJlong(openssl_version); if (!((OPENSSL_VERSION_1_0_0 <= ossl_ver) && (ossl_ver < OPENSSL_VERSION_1_1_0))) { - if (trace) { + if (traceEnabled) { fprintf(stderr, "Error loading OpenSSL: Incompatible OpenSSL version found: %s\n", openssl_version); fflush(stderr); } @@ -442,10 +544,10 @@ JNIEXPORT jlong JNICALL Java_jdk_crypto_jniprovider_NativeCrypto_loadCrypto openssl_version = (*OSSL_version)(0); /* get OPENSSL_VERSION */ /* Ensure the OpenSSL version is "OpenSSL 1.1.x" or "OpenSSL 3.x.x". */ ossl_ver = extractVersionToJlong(openssl_version); - if (!((OPENSSL_VERSION_1_1_0 <= ossl_ver) && (ossl_ver < OPENSSL_VERSION_2_0_0)) - && !((OPENSSL_VERSION_3_0_0 <= ossl_ver) && (ossl_ver < OPENSSL_VERSION_4_0_0)) + if (!(((OPENSSL_VERSION_1_1_0 <= ossl_ver) && (ossl_ver < OPENSSL_VERSION_2_0_0)) + || ((OPENSSL_VERSION_3_0_0 <= ossl_ver) && (ossl_ver < OPENSSL_VERSION_4_0_0))) ) { - if (trace) { + if (traceEnabled) { fprintf(stderr, "Error loading OpenSSL: Incompatible OpenSSL version found: %s\n", openssl_version); fflush(stderr); } @@ -474,12 +576,301 @@ JNIEXPORT jlong JNICALL Java_jdk_crypto_jniprovider_NativeCrypto_loadCrypto } } + if (traceEnabled) { + fprintf(stdout, "%s: %s\n", message, openssl_version); + fflush(stdout); + } + + return ossl_ver; +} + +static void * +load_crypto_library(jboolean traceEnabled, const char *libName) +{ + void *result = NULL; + if ((NULL != libName) && ('\0' != *libName)) { +#if defined(_AIX) + int flags = RTLD_NOW; + if (NULL != strrchr(libName, '(')) { + flags |= RTLD_MEMBER; + } + result = dlopen(libName, flags); +#elif defined(_WIN32) /* defined(_AIX) */ + result = LoadLibrary(libName); +#else /* defined(_WIN32) */ + result = dlopen(libName, RTLD_NOW); +#endif /* defined(_AIX) */ + } + return result; +} + +/* Look for a crypto library in java.home or the system. + * NULL is returned when an appropriate crypto library + * cannot be found. + */ +static void * +find_crypto_library(jboolean traceEnabled, const char *chomepath) +{ + /* Library names for OpenSSL 1.1.1, 1.1.0 and symbolic links: + * It is important to preserve the order!!! + * + * Since there is no indication of the version of a symlink, + * they have to be loaded first, so as to compare with other + * available options. + * Note: On macOS 11 or later, loading the general symlink causes + * a fatal warning and associated abort by default, so it is + * omitted. + * + * The rest of the libraries are listed in descending order, + * which allows us to do two things: + * - Stop if a general symlink is loaded and we then find a + * specific version that is higher. + * - Stop immediately if a specific version is loaded, as + * anything after that will be a lower version. + */ + static const char * const libNames[] = { +#if defined(_AIX) + "libcrypto.a(libcrypto64.so)", /* general symlink library name from archive file */ + "libcrypto64.so", /* general symlink library name */ + "libcrypto.a(libcrypto.so)", /* general symlink library name from archive file */ + "libcrypto.so", /* general symlink library name */ + "libcrypto.a(libcrypto64.so.3)", /* 3.x library name from archive file */ + "libcrypto64.so.3", /* 3.x library name */ + "libcrypto.a(libcrypto.so.3)", /* 3.x library name from archive file */ + "libcrypto.so.3", /* 3.x library name */ + "libcrypto.a(libcrypto64.so.1.1)", /* 1.1.x library name from archive file */ + "libcrypto.so.1.1", /* 1.1.x library name */ + "libcrypto.a(libcrypto.so.1.0.0)", /* 1.0.x library name from archive file */ + "libcrypto.so.1.0.0", /* 1.0.x library name */ +#elif defined(__APPLE__) /* defined(_AIX) */ + "libcrypto.3.dylib", /* 3.x library name */ + "libcrypto.1.1.dylib", /* 1.1.x library name */ + "libcrypto.1.0.0.dylib", /* 1.0.x library name */ +#elif defined(_WIN32) /* defined(__APPLE__) */ + "libcrypto-3-x64.dll", /* 3.x library name */ + "libcrypto-1_1-x64.dll", /* 1.1.x library name */ + "libeay32.dll", /* old library name */ +#else /* defined(_WIN32) */ + "libcrypto.so", /* general symlink library name */ + "libcrypto.so.3", /* 3.x library name */ + "libcrypto.so.1.1", /* 1.1.x library name */ + "libcrypto.so.1.0.0", /* 1.0.x library name */ + "libcrypto.so.10", /* old library name */ +#endif /* defined(_AIX) */ + }; + + const size_t numOfLibs = sizeof(libNames) / sizeof(libNames[0]); +#if defined(_AIX) + const size_t num_of_generic = 4; +#elif defined(__linux__) /* defined(_AIX) */ + const size_t num_of_generic = 1; +#else /* defined(__linux__) */ + const size_t num_of_generic = 0; +#endif /* defined(_AIX) */ + + void *result = NULL; + void *prevResult = NULL; + size_t i = 0; + long tempVersion = 0; + long previousVersion = 0; + + /* If JAVA_HOME is not null or empty and no library has been loaded yet, try there. */ + if ((NULL != chomepath) && ('\0' != *chomepath) && (NULL == crypto_library)) { +#if defined(_WIN32) + static const char pathSuffix[] = "\\bin\\"; +#else /* defined(_WIN32) */ + static const char pathSuffix[] = "/lib/"; +#endif /* defined(_WIN32) */ + + size_t path_len = strlen(chomepath) + sizeof(pathSuffix) - 1; + char *libPath = malloc(path_len + 1); + + if (NULL == libPath) { + if (traceEnabled) { + fprintf(stderr, "\tFailed to allocate memory for path.\n"); + } + return NULL; + } + strcpy(libPath, chomepath); + + /* Append the proper directory using a slash or backslash, depending on the operating system. */ + strcat(libPath, pathSuffix); + + if (traceEnabled) { + fprintf(stdout, "Attempting to load library bundled with JDK from: %s\n", libPath); + } + + for (i = 0; i < numOfLibs; i++) { + size_t file_len = strlen(libNames[i]); + /* Allocate memory for the new file name with the path. */ + char *libNameWithPath = (char *)malloc(path_len + file_len + 1); + + if (NULL == libNameWithPath) { + if (traceEnabled) { + fprintf(stderr, "\tFailed to allocate memory for file name with path.\n"); + } + continue; + } + + strcpy(libNameWithPath, libPath); + strcat(libNameWithPath, libNames[i]); + + /* Load OpenSSL Crypto library bundled with JDK. */ + if (traceEnabled) { + fprintf(stdout, "\tAttempting to load: %s\n", libNames[i]); + } + result = load_crypto_library(traceEnabled, libNameWithPath); + + free(libNameWithPath); + + if (NULL == result) { + continue; + } + + /* Identify and load the latest version from the potential libraries. + * This logic depends upon the order in which libnames are defined. + * Libraries are listed in descending order w.r.t version. + * Since only one library is bundled with the JDK, once any library is + * loaded, this is the only available and we can stop. + */ + tempVersion = get_crypto_library_version(traceEnabled, result, "\t\tLoaded OpenSSL version"); + if (tempVersion > 0) { + free(libPath); + return result; + } + } + free(libPath); + } + + /* The attempt to load from property and OpenSSL bundled with JDK failed. + * Try loading the libraries in the order set out above, and retain the latest library. + */ + for (i = 0; i < numOfLibs; i++) { + if (traceEnabled) { + fprintf(stdout, "Attempting to load libname from OS: %s\n", libNames[i]); + } + result = load_crypto_library(traceEnabled, libNames[i]); + + if (NULL == result) { + continue; + } + + /* Identify and load the latest version from the available libraries. + * This logic depends upon the order in which libnames are defined. + * It only loads the libraries which can possibly be the latest versions. + */ + log_crypto_library_path(traceEnabled, result, "\tLibrary to be potentially used was loaded from"); + tempVersion = get_crypto_library_version(traceEnabled, result, "\tLoaded OpenSSL version"); + + if (tempVersion <= 0) { + continue; + } + + if (tempVersion > previousVersion) { + if (0 != previousVersion) { + unload_crypto_library(prevResult); + } + previousVersion = tempVersion; + prevResult = result; + } else { + unload_crypto_library(result); + } + + /* If library checked is not a generic one, there is no need to check further. */ + if (i >= num_of_generic) { + break; + } + } + + /* If we reach here, it means that none of the non-generic libraries + * where found. However, a generic one might have been found in the + * process and, if so, it will be in the prevResult variable. + */ + return prevResult; +} + +/* + * Class: jdk_crypto_jniprovider_NativeCrypto + * Method: loadCrypto + * Signature: (ZLjava/lang/String;Ljava/lang/String;)J + */ +JNIEXPORT jlong JNICALL +Java_jdk_crypto_jniprovider_NativeCrypto_loadCrypto + (JNIEnv * env, jobject jobj, jboolean traceEnabled, jstring jlibname, jstring jhomepath) +{ + const char *chomepath = ""; + jlong ossl_ver = 0; + + if (NULL != jlibname) { + const char *clibname = (*env)->GetStringUTFChars(env, jlibname, NULL); + if (NULL == clibname) { + if (traceEnabled) { + fprintf(stderr, "Failed to get jdk.native.openssl.lib value.\n"); + fflush(stderr); + } + return -1; + } + if ('\0' == clibname[0]) { + if (traceEnabled) { + fprintf(stderr, "The jdk.native.openssl.lib property is not set.\n"); + fflush(stderr); + } + } else { + crypto_library = load_crypto_library(traceEnabled, clibname); + if (NULL == crypto_library) { + if (traceEnabled) { + fprintf(stderr, "OpenSSL library specified in jdk.openssl.lib couldn't be loaded.\n"); + fflush(stderr); + } + (*env)->ReleaseStringUTFChars(env, jlibname, clibname); + return -1; + } + } + (*env)->ReleaseStringUTFChars(env, jlibname, clibname); + } + + if (NULL != jhomepath) { + chomepath = (*env)->GetStringUTFChars(env, jhomepath, NULL); + if (NULL == chomepath) { + if (traceEnabled) { + fprintf(stderr, "Failed to get java.home value.\n"); + fflush(stderr); + } + return -1; + } + } + + /* If the jdk.native.openssl.lib property was not set, attempt + * to find an OpenSSL library from java.home or OS Library path. + */ + if (NULL == crypto_library) { + crypto_library = find_crypto_library(traceEnabled, chomepath); + } + + if (NULL != jhomepath) { + (*env)->ReleaseStringUTFChars(env, jhomepath, chomepath); + } + + /* If an OpenSSL library was not loaded from any of the potential + * sources, fail loading native crypto. + */ + if (NULL == crypto_library) { + if (traceEnabled) { + fprintf(stderr, "FAILED TO LOAD OPENSSL CRYPTO LIBRARY\n"); + fflush(stderr); + } + return -1; + } + + log_crypto_library_path(traceEnabled, crypto_library, "OpenSSL to be used was loaded from"); + ossl_ver = get_crypto_library_version(traceEnabled, crypto_library, "Version of OpenSSL library that is used"); + /* Load the function symbols for OpenSSL errors. */ OSSL_error_string_n = (OSSL_error_string_n_t*)find_crypto_symbol(crypto_library, "ERR_error_string_n"); OSSL_error_string = (OSSL_error_string_t*)find_crypto_symbol(crypto_library, "ERR_error_string"); OSSL_get_error = (OSSL_get_error_t*)find_crypto_symbol(crypto_library, "ERR_get_error"); - /* Load Threading routines for OpenSSL 1.0.2 */ + /* Load Threading routines for OpenSSL 1.0.2. */ if (ossl_ver < OPENSSL_VERSION_1_1_0) { OSSL_CRYPTO_num_locks = (OSSL_CRYPTO_num_locks_t*)find_crypto_symbol(crypto_library, "CRYPTO_num_locks"); OSSL_CRYPTO_THREADID_set_numeric = (OSSL_CRYPTO_THREADID_set_numeric_t*)find_crypto_symbol(crypto_library, "CRYPTO_THREADID_set_numeric"); @@ -763,30 +1154,26 @@ JNIEXPORT jlong JNICALL Java_jdk_crypto_jniprovider_NativeCrypto_loadCrypto ((NULL == OSSL_CRYPTO_THREADID_set_callback) && (ossl_ver < OPENSSL_VERSION_1_1_0)) || ((NULL == OSSL_CRYPTO_set_locking_callback) && (ossl_ver < OPENSSL_VERSION_1_1_0)) ) { - if (trace) { - fprintf(stderr, "Error loading OpenSSL: One or more of the required symbols are missing in the crypto library: %s\n", openssl_version); + if (traceEnabled) { + fprintf(stderr, "Error loading OpenSSL: One or more of the required symbols are missing."); } unload_crypto_library(crypto_library); crypto_library = NULL; return -1; } else { - if (trace) { - char *library_path = malloc(4096); - if (NULL == library_path) { - fprintf(stderr, "Using OpenSSL version: %s\n", openssl_version); - } else { - get_library_path(crypto_library, library_path); - fprintf(stderr, "Using OpenSSL version: %s (%s)\n", openssl_version, library_path); - free(library_path); - } - } if (ossl_ver < OPENSSL_VERSION_1_1_0) { if (0 != thread_setup()) { + if (traceEnabled) { + fprintf(stderr, "Error loading OpenSSL: Thread setup was unsuccessful."); + } unload_crypto_library(crypto_library); crypto_library = NULL; return -1; } } + if (traceEnabled) { + fprintf(stderr, "OpenSSL library loaded successfully.\n"); + } return ossl_ver; } } @@ -2015,7 +2402,7 @@ JNIEXPORT jint JNICALL Java_jdk_crypto_jniprovider_NativeCrypto_RSADP } } } - } else { // if verify == kLen + } else { /* if verify == kLen */ for (i = 0; i < verify; i++) { if (kNative[i] != k2[i]) { msg_len = -2; @@ -2531,7 +2918,7 @@ Java_jdk_crypto_jniprovider_NativeCrypto_ECGenerateKeyPair goto cleanup; } - // to translate the public key to java format, we need to extract the public key coordinates: xBN, yBN + /* to translate the public key to java format, we need to extract the public key coordinates: xBN, yBN */ ctx = (*OSSL_BN_CTX_new)(); if (NULL == ctx) { goto cleanup; @@ -2563,7 +2950,7 @@ Java_jdk_crypto_jniprovider_NativeCrypto_ECGenerateKeyPair goto cleanup; } - // to translate the private key to java format, we need the private key BIGNUM + /* to translate the private key to java format, we need the private key BIGNUM */ sBN = (*OSSL_EC_KEY_get0_private_key)(nativeKey); ret = getArrayFromBN(sBN, nativeS, sLen); @@ -3278,13 +3665,13 @@ Java_jdk_crypto_jniprovider_NativeCrypto_ECDSAVerify } if (NULL != signature) { - // The BIGNUM structs will be freed by the signature. + /* The BIGNUM structs will be freed by the signature. */ sBN = NULL; rBN = NULL; (*OSSL_ECDSA_SIG_free)(signature); } - // In case the BIGNUM structs weren't freed by the signature. + /* In case the BIGNUM structs weren't freed by the signature. */ if (NULL != sBN) { (*OSSL_BN_free)(sBN); } @@ -3320,7 +3707,7 @@ Java_jdk_crypto_jniprovider_NativeCrypto_XDHCreateKeys unsigned char *privateKeyArray = NULL; unsigned char *publicKeyArray = NULL; - // Create PKEY (public/private pair) based on curve type (X25519 or X448) + /* Create PKEY (public/private pair) based on curve type (X25519 or X448). */ pctx = (*OSSL_EVP_PKEY_CTX_new_id)(curveType, NULL); if (NULL == pctx) { @@ -3334,7 +3721,7 @@ Java_jdk_crypto_jniprovider_NativeCrypto_XDHCreateKeys goto cleanup; } - // Separate private and public and store into arrays + /* Separate private and public and store into arrays. */ privateKeyArray = (unsigned char *)((*env)->GetPrimitiveArrayCritical(env, privateKey, 0)); if (NULL == privateKeyArray) { goto cleanup; @@ -3403,7 +3790,7 @@ Java_jdk_crypto_jniprovider_NativeCrypto_XDHGenerateSecret goto cleanup; } - // Setup EVP_PKEY instances for user private and peer public keys + /* Setup EVP_PKEY instances for user private and peer public keys. */ pkey = (*OSSL_EVP_PKEY_new_raw_private_key)(curveType, NULL, privateKeyArray, privateKey_len); peerkey = (*OSSL_EVP_PKEY_new_raw_public_key)(curveType, NULL, publicKeyArray, publicKey_len); @@ -3411,23 +3798,23 @@ Java_jdk_crypto_jniprovider_NativeCrypto_XDHGenerateSecret goto cleanup; } - // Create key agreement context + /* Create key agreement context. */ pctx = (*OSSL_EVP_PKEY_CTX_new)(pkey, NULL); if (NULL == pctx) { goto cleanup; } - // Initialize with user private key + /* Initialize with user private key. */ if (0 >= (*OSSL_EVP_PKEY_derive_init)(pctx)) { goto cleanup; } - // Set peer's public key + /* Set peer's public key. */ if (0 >= (*OSSL_EVP_PKEY_derive_set_peer)(pctx, peerkey)) { goto cleanup; } - // Derive shared secret and save in sharedKeyArray + /* Derive shared secret and save in sharedKeyArray. */ sharedKeyArray = (unsigned char *)((*env)->GetPrimitiveArrayCritical(env, sharedKey, 0)); if (NULL == sharedKeyArray) { goto cleanup; diff --git a/closed/src/java.base/share/native/libjncrypto/NativeCrypto_md.h b/closed/src/java.base/share/native/libjncrypto/NativeCrypto_md.h deleted file mode 100644 index b01402ba4dd..00000000000 --- a/closed/src/java.base/share/native/libjncrypto/NativeCrypto_md.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * =========================================================================== - * (c) Copyright IBM Corp. 2019, 2022 All Rights Reserved - * =========================================================================== - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * IBM designates this particular file as subject to the "Classpath" exception - * as provided by IBM in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, see . - * - * =========================================================================== - */ - -#ifndef NATIVECRYPTO_MD_H -#define NATIVECRYPTO_MD_H - -#include - -void * load_crypto_library(jboolean traceEnabled); -void unload_crypto_library(void *handle); -void * find_crypto_symbol(void *handle, const char *symname); -void get_library_path(void * handle, char * library_path); - -#endif /* NATIVECRYPTO_MD_H */ diff --git a/closed/src/java.base/unix/native/libjncrypto/NativeCrypto_md.c b/closed/src/java.base/unix/native/libjncrypto/NativeCrypto_md.c deleted file mode 100644 index 72e14e979cc..00000000000 --- a/closed/src/java.base/unix/native/libjncrypto/NativeCrypto_md.c +++ /dev/null @@ -1,81 +0,0 @@ -/* - * =========================================================================== - * (c) Copyright IBM Corp. 2019, 2022 All Rights Reserved - * =========================================================================== - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * IBM designates this particular file as subject to the "Classpath" exception - * as provided by IBM in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, see . - * - * =========================================================================== - */ - -#include -#include -#include -#include -#include -#include -#include "NativeCrypto_md.h" - -/* Load the crypto library (return NULL on error) */ -void * load_crypto_library(jboolean traceEnabled) -{ - void * result = NULL; - size_t i = 0; - - // Library names for OpenSSL 3.x, 1.1.1, 1.1.0, 1.0.2 and symbolic links - static const char * const libNames[] = { - "libcrypto.so.3", // 3.x library name - "libcrypto.so.1.1", // 1.1.x library name - "libcrypto.so.1.0.0", // 1.0.x library name - "libcrypto.so.10", // 1.0.x library name on RHEL - "libcrypto.so" // general symlink library name - }; - - // Check to see if we can load the libraries in the order set out above - for (i = 0; (NULL == result) && (i < sizeof(libNames) / sizeof(libNames[0])); i++) { - const char * libName = libNames[i]; - - // Check to see if we can load the library - result = dlopen (libName, RTLD_NOW); - } - - if (traceEnabled && (NULL != result)) { - struct link_map *map = NULL; - dlinfo(result, RTLD_DI_LINKMAP, &map); - fprintf(stderr, "Attempt to load OpenSSL %s\n", map->l_name); - fflush(stderr); - } - return result; -} - -/* Unload the crypto library */ -void unload_crypto_library(void *handle) { - (void)dlclose(handle); -} - -/* Find the symbol in the crypto library (return NULL if not found) */ -void * find_crypto_symbol(void *handle, const char *symname) { - return dlsym(handle, symname); -} - -/* Find the path that the library was loaded from */ -void get_library_path(void * handle, char * library_path) { - if (0 != dlinfo(handle, RTLD_DI_ORIGIN, library_path)) { - strcpy(library_path, "Unknown path"); - } - -} diff --git a/closed/src/java.base/windows/native/libjncrypto/NativeCrypto_md.c b/closed/src/java.base/windows/native/libjncrypto/NativeCrypto_md.c deleted file mode 100644 index e2f554203a0..00000000000 --- a/closed/src/java.base/windows/native/libjncrypto/NativeCrypto_md.c +++ /dev/null @@ -1,67 +0,0 @@ -/* - * =========================================================================== - * (c) Copyright IBM Corp. 2019, 2023 All Rights Reserved - * =========================================================================== - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * IBM designates this particular file as subject to the "Classpath" exception - * as provided by IBM in the LICENSE file that accompanied this code. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, see . - * - * =========================================================================== - */ - -#include - -#include "NativeCrypto_md.h" - -/* Load the crypto library (return NULL on error) */ -void * load_crypto_library(jboolean traceEnabled) { - void * result = NULL; - const char *libname3 = "libcrypto-3-x64.dll"; - const char *libname = "libcrypto-1_1-x64.dll"; - const char *oldname = "libeay32.dll"; - - result = LoadLibrary(libname3); - if (result == NULL) { - result = LoadLibrary(libname); - if (result == NULL) { - result = LoadLibrary(oldname); - } - } - - return result; -} - -/* Unload the crypto library */ -void unload_crypto_library(void *handle) { - FreeLibrary(handle); -} - -/* Find the symbol in the crypto library (return NULL if not found) */ -void * find_crypto_symbol(void *handle, const char *symname) { - void * symptr; - - symptr = GetProcAddress(handle, symname); - - return symptr; -} - - -/* Find the path that the library was loaded from */ -void get_library_path(void * handle, char * library_path) { - if (0 == GetModuleFileName(handle, library_path, 4096)) { - strcpy(library_path, "Unknown path"); - } -} diff --git a/make/common/MakeBase.gmk b/make/common/MakeBase.gmk index 49ad3d60f90..2a06d8eb8b3 100644 --- a/make/common/MakeBase.gmk +++ b/make/common/MakeBase.gmk @@ -290,6 +290,7 @@ ifeq ($(call isTargetOs, macosx), true) $(CP) -fRP '$(call DecodeSpace, $<)' '$(call DecodeSpace, $@)'; \ fi if [ -n "`$(XATTR) -ls '$(call DecodeSpace, $@)'`" ]; then \ + $(CHMOD) -h u+w '$(call DecodeSpace, $@)'; \ $(XATTR) -cs '$(call DecodeSpace, $@)'; \ fi endef diff --git a/make/conf/version-numbers.conf b/make/conf/version-numbers.conf index 0462cf6548a..29ccfb0801b 100644 --- a/make/conf/version-numbers.conf +++ b/make/conf/version-numbers.conf @@ -28,15 +28,15 @@ DEFAULT_VERSION_FEATURE=17 DEFAULT_VERSION_INTERIM=0 -DEFAULT_VERSION_UPDATE=14 +DEFAULT_VERSION_UPDATE=15 DEFAULT_VERSION_PATCH=0 DEFAULT_VERSION_EXTRA1=0 DEFAULT_VERSION_EXTRA2=0 DEFAULT_VERSION_EXTRA3=0 -DEFAULT_VERSION_DATE=2025-01-21 +DEFAULT_VERSION_DATE=2025-04-15 DEFAULT_VERSION_CLASSFILE_MAJOR=61 # "`$EXPR $DEFAULT_VERSION_FEATURE + 44`" DEFAULT_VERSION_CLASSFILE_MINOR=0 DEFAULT_VERSION_DOCS_API_SINCE=11 DEFAULT_ACCEPTABLE_BOOT_VERSIONS="16 17" DEFAULT_JDK_SOURCE_TARGET_VERSION=17 -DEFAULT_PROMOTED_VERSION_PRE= +DEFAULT_PROMOTED_VERSION_PRE=ea diff --git a/make/data/lsrdata/language-subtag-registry.txt b/make/data/lsrdata/language-subtag-registry.txt index 3079d77ed8b..b00ea67e7e8 100644 --- a/make/data/lsrdata/language-subtag-registry.txt +++ b/make/data/lsrdata/language-subtag-registry.txt @@ -1,4 +1,4 @@ -File-Date: 2024-06-14 +File-Date: 2024-11-19 %% Type: language Subtag: aa @@ -47991,6 +47991,16 @@ Added: 2008-10-14 Prefix: kw %% Type: variant +Subtag: kleinsch +Description: Kleinschmidt orthography +Description: Allattaasitaamut +Added: 2024-07-20 +Prefix: kl +Prefix: kl-tunumiit +Comments: Orthography for Greenlandic designed by Samuel Kleinschmidt, + used from 1851 to 1973. +%% +Type: variant Subtag: kociewie Description: The Kociewie dialect of Polish Added: 2014-11-27 diff --git a/make/hotspot/lib/CompileJvm.gmk b/make/hotspot/lib/CompileJvm.gmk index 230aa54f73a..508be109092 100644 --- a/make/hotspot/lib/CompileJvm.gmk +++ b/make/hotspot/lib/CompileJvm.gmk @@ -87,6 +87,13 @@ ifeq ($(call check-jvm-feature, zero), true) DISABLED_WARNINGS_gcc += return-type switch clobbered endif +ifeq ($(DEBUG_LEVEL), fastdebug) + ifeq ($(call And, $(call isTargetOs, linux) $(call isTargetCpu, aarch64)), true) + # False positive warnings for atomic_linux_aarch64.hpp on GCC >= 13 + DISABLED_WARNINGS_gcc += stringop-overflow + endif +endif + DISABLED_WARNINGS_clang := tautological-compare \ undefined-var-template sometimes-uninitialized unknown-pragmas \ delete-non-virtual-dtor missing-braces char-subscripts \ diff --git a/make/modules/java.base/Lib.gmk b/make/modules/java.base/Lib.gmk index 715d496d4a7..da246c12e7a 100644 --- a/make/modules/java.base/Lib.gmk +++ b/make/modules/java.base/Lib.gmk @@ -24,7 +24,7 @@ # # =========================================================================== -# (c) Copyright IBM Corp. 2018, 2018 All Rights Reserved +# (c) Copyright IBM Corp. 2018, 2025 All Rights Reserved # =========================================================================== include LibCommon.gmk @@ -74,6 +74,26 @@ $(eval $(call SetupJdkLibrary, BUILD_LIBNIO, \ OPTIMIZATION := HIGH, \ WARNINGS_AS_ERRORS_xlc := false, \ CFLAGS := $(CFLAGS_JDKLIB), \ + FileDispatcherImpl.c_CFLAGS := \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ + Net.c_CFLAGS := \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ + nio_util.c_CFLAGS := \ + -I$(OPENJ9_TOPDIR)/runtime/include \ + -I$(OPENJ9_TOPDIR)/runtime/oti \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR) \ + -I$(OPENJ9_TOPDIR)/runtime/jcl \ + -I$(OPENJ9_TOPDIR)/runtime/util \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ + SocketDispatcher.c_CFLAGS := \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ + UnixDomainSockets.c_CFLAGS := \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ DISABLED_WARNINGS_gcc := undef, \ DISABLED_WARNINGS_clang := undef, \ EXTRA_HEADER_DIRS := \ diff --git a/make/modules/java.base/lib/CoreLibraries.gmk b/make/modules/java.base/lib/CoreLibraries.gmk index c1db028fff8..8576bc9f2c8 100644 --- a/make/modules/java.base/lib/CoreLibraries.gmk +++ b/make/modules/java.base/lib/CoreLibraries.gmk @@ -23,6 +23,10 @@ # questions. # +# =========================================================================== +# (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved +# =========================================================================== + ########################################################################################## # libfdlibm is statically linked with libjava below and not delivered into the # product on its own. @@ -91,8 +95,30 @@ $(eval $(call SetupJdkLibrary, BUILD_LIBJAVA, \ OPTIMIZATION := HIGH, \ CFLAGS := $(CFLAGS_JDKLIB) \ $(LIBJAVA_CFLAGS), \ + check_version.c_CFLAGS := \ + -I$(OPENJ9_TOPDIR)/runtime/include \ + -I$(OPENJ9_TOPDIR)/runtime/oti \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR) \ + -I$(OPENJ9_TOPDIR)/runtime/jcl \ + -I$(OPENJ9_TOPDIR)/runtime/util \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ + io_util_md.c_CFLAGS := \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ jdk_util.c_CFLAGS := $(VERSION_CFLAGS), \ ProcessImpl_md.c_CFLAGS := $(VERSION_CFLAGS), \ + UnixFileSystem_md.c_CFLAGS := \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ + VM.c_CFLAGS := \ + -I$(OPENJ9_TOPDIR)/runtime/include \ + -I$(OPENJ9_TOPDIR)/runtime/oti \ + -I$(OPENJ9OMR_TOPDIR)/include_core \ + -I$(OPENJ9_VM_BUILD_DIR) \ + -I$(OPENJ9_TOPDIR)/runtime/jcl \ + -I$(OPENJ9_TOPDIR)/runtime/util \ + -I$(OPENJ9_VM_BUILD_DIR)/jcl, \ EXTRA_HEADER_DIRS := libfdlibm, \ WARNINGS_AS_ERRORS_xlc := false, \ DISABLED_WARNINGS_gcc := unused-result unused-function, \ diff --git a/make/test/JtregNativeHotspot.gmk b/make/test/JtregNativeHotspot.gmk index 92af1a8acc9..cd03747d98d 100644 --- a/make/test/JtregNativeHotspot.gmk +++ b/make/test/JtregNativeHotspot.gmk @@ -873,7 +873,7 @@ BUILD_HOTSPOT_JTREG_EXECUTABLES_LIBS_exesigtest := -ljvm ifeq ($(call isTargetOs, windows), true) BUILD_HOTSPOT_JTREG_EXECUTABLES_CFLAGS_exeFPRegs := -MT - BUILD_HOTSPOT_JTREG_EXCLUDE += exesigtest.c libterminatedThread.c libTestJNI.c libnativeStack.c + BUILD_HOTSPOT_JTREG_EXCLUDE += exesigtest.c libterminatedThread.c libTestJNI.c libnativeStack.c exeGetCreatedJavaVMs.c BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libatExit := jvm.lib else BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libbootclssearch_agent += -lpthread @@ -1511,6 +1511,7 @@ else BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libterminatedThread += -lpthread BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libatExit += -ljvm BUILD_HOTSPOT_JTREG_LIBRARIES_LIBS_libnativeStack += -lpthread + BUILD_HOTSPOT_JTREG_EXECUTABLES_LIBS_exeGetCreatedJavaVMs := -ljvm -lpthread endif # This evaluation is expensive and should only be done if this target was diff --git a/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java b/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java index 9cc8bc48e80..1b033391fa3 100644 --- a/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java +++ b/src/java.base/share/classes/javax/crypto/CryptoPolicyParser.java @@ -70,6 +70,7 @@ final class CryptoPolicyParser { // Convenience variables for parsing private StreamTokenizer st; private int lookahead; + private boolean allPermEntryFound = false; /** * Creates a CryptoPolicyParser object. @@ -128,7 +129,7 @@ void read(Reader policy) * The crypto jurisdiction policy must be consistent. The * following hashtable is used for checking consistency. */ - Hashtable> processedPermissions = null; + Hashtable> processedPermissions = new Hashtable<>(); /* * The main parsing loop. The loop is executed once for each entry @@ -191,6 +192,16 @@ private CryptoPermissionEntry parsePermissionEntry( e.cryptoPermission = match("permission type"); if (e.cryptoPermission.equals("javax.crypto.CryptoAllPermission")) { + /* + * This catches while processing the "javax.crypto.CryptoAllPermission" + * entry, but the "processedPermissions" Hashtable already contains + * an entry for "javax.crypto.CryptoPermission". + */ + if (!processedPermissions.isEmpty()) { + throw new ParsingException(st.lineno(), "Inconsistent policy"); + } + allPermEntryFound = true; + // Done with the CryptoAllPermission entry. e.alg = CryptoAllPermission.ALG_NAME; e.maxKeySize = Integer.MAX_VALUE; @@ -498,18 +509,21 @@ private boolean isConsistent(String alg, String exemptionMechanism, String thisExemptionMechanism = exemptionMechanism == null ? "none" : exemptionMechanism; - if (processedPermissions == null) { - processedPermissions = new Hashtable>(); + /* + * This catches while processing a "javax.crypto.CryptoPermission" entry, but + * "javax.crypto.CryptoAllPermission" entry already exists. + */ + if (allPermEntryFound) { + return false; + } + + if (processedPermissions.isEmpty()) { Vector exemptionMechanisms = new Vector<>(1); exemptionMechanisms.addElement(thisExemptionMechanism); processedPermissions.put(alg, exemptionMechanisms); return true; } - if (processedPermissions.containsKey(CryptoAllPermission.ALG_NAME)) { - return false; - } - Vector exemptionMechanisms; if (processedPermissions.containsKey(alg)) { diff --git a/src/java.base/share/classes/sun/security/action/GetPropertyAction.java b/src/java.base/share/classes/sun/security/action/GetPropertyAction.java index f4c07f29a28..b46578a833a 100644 --- a/src/java.base/share/classes/sun/security/action/GetPropertyAction.java +++ b/src/java.base/share/classes/sun/security/action/GetPropertyAction.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -162,6 +162,68 @@ public Properties run() { } } + /** + * Convenience method for fetching System property values that are timeouts. + * Accepted timeout values may be purely numeric, a numeric value + * followed by "s" (both interpreted as seconds), or a numeric value + * followed by "ms" (interpreted as milliseconds). + * + * @param prop the name of the System property + * @param def a default value (in milliseconds) + * @param dbg a Debug object, if null no debug messages will be sent + * + * @return an integer value corresponding to the timeout value in the System + * property in milliseconds. If the property value is empty, negative, + * or contains non-numeric characters (besides a trailing "s" or "ms") + * then the default value will be returned. If a negative value for + * the "def" parameter is supplied, zero will be returned if the + * property's value does not conform to the allowed syntax. + */ + public static int privilegedGetTimeoutProp(String prop, int def, Debug dbg) { + if (def < 0) { + def = 0; + } + + String rawPropVal = privilegedGetProperty(prop, "").trim(); + if (rawPropVal.length() == 0) { + return def; + } + + // Determine if "ms" or just "s" is on the end of the string. + // We may do a little surgery on the value so we'll retain + // the original value in rawPropVal for debug messages. + boolean isMillis = false; + String propVal = rawPropVal; + if (rawPropVal.toLowerCase().endsWith("ms")) { + propVal = rawPropVal.substring(0, rawPropVal.length() - 2); + isMillis = true; + } else if (rawPropVal.toLowerCase().endsWith("s")) { + propVal = rawPropVal.substring(0, rawPropVal.length() - 1); + } + + // Next check to make sure the string is built only from digits + if (propVal.matches("^\\d+$")) { + try { + int timeout = Integer.parseInt(propVal); + return isMillis ? timeout : timeout * 1000; + } catch (NumberFormatException nfe) { + if (dbg != null) { + dbg.println("Warning: Unexpected " + nfe + + " for timeout value " + rawPropVal + + ". Using default value of " + def + " msec."); + } + return def; + } + } else { + if (dbg != null) { + dbg.println("Warning: Incorrect syntax for timeout value " + + rawPropVal + ". Using default value of " + def + + " msec."); + } + return def; + } + } + /** * Convenience method for fetching System property values that are booleans. * diff --git a/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java b/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java index 03731b25cfb..1cab369b874 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java @@ -26,10 +26,7 @@ import java.io.IOException; import java.io.OutputStream; -import java.net.URI; -import java.net.URL; -import java.net.HttpURLConnection; -import java.net.URLEncoder; +import java.net.*; import java.security.cert.CertificateException; import java.security.cert.CertPathValidatorException; import java.security.cert.CertPathValidatorException.BasicReason; @@ -74,11 +71,20 @@ public final class OCSP { private static final int DEFAULT_CONNECT_TIMEOUT = 15000; /** - * Integer value indicating the timeout length, in seconds, to be - * used for the OCSP check. A timeout of zero is interpreted as - * an infinite timeout. + * Integer value indicating the timeout length, in milliseconds, to be + * used for establishing a connection to an OCSP responder. A timeout of + * zero is interpreted as an infinite timeout. */ - private static final int CONNECT_TIMEOUT = initializeTimeout(); + private static final int CONNECT_TIMEOUT = initializeTimeout( + "com.sun.security.ocsp.timeout", DEFAULT_CONNECT_TIMEOUT); + + /** + * Integer value indicating the timeout length, in milliseconds, to be + * used for reading an OCSP response from the responder. A timeout of + * zero is interpreted as an infinite timeout. + */ + private static final int READ_TIMEOUT = initializeTimeout( + "com.sun.security.ocsp.readtimeout", CONNECT_TIMEOUT); /** * Boolean value indicating whether OCSP client can use GET for OCSP @@ -107,16 +113,13 @@ public final class OCSP { * system property. If the property has not been set, or if its * value is negative, set the timeout length to the default. */ - private static int initializeTimeout() { - @SuppressWarnings("removal") - Integer tmp = java.security.AccessController.doPrivileged( - new GetIntegerAction("com.sun.security.ocsp.timeout")); - if (tmp == null || tmp < 0) { - return DEFAULT_CONNECT_TIMEOUT; + private static int initializeTimeout(String prop, int def) { + int timeoutVal = + GetPropertyAction.privilegedGetTimeoutProp(prop, def, debug); + if (debug != null) { + debug.println(prop + " set to " + timeoutVal + " milliseconds"); } - // Convert to milliseconds, as the system property will be - // specified in seconds - return tmp * 1000; + return timeoutVal; } private static boolean initializeBoolean(String prop, boolean def) { @@ -277,8 +280,10 @@ public static byte[] getOCSPBytes(List certIds, URI responderURI, Base64.getEncoder().encodeToString(bytes), "UTF-8")); if (USE_GET && encodedGetReq.length() <= 255) { - url = new URL(encodedGetReq.toString()); + url = new URI(encodedGetReq.toString()).toURL(); con = (HttpURLConnection)url.openConnection(); + con.setConnectTimeout(CONNECT_TIMEOUT); + con.setReadTimeout(READ_TIMEOUT); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("GET"); @@ -286,7 +291,7 @@ public static byte[] getOCSPBytes(List certIds, URI responderURI, url = responderURI.toURL(); con = (HttpURLConnection)url.openConnection(); con.setConnectTimeout(CONNECT_TIMEOUT); - con.setReadTimeout(CONNECT_TIMEOUT); + con.setReadTimeout(READ_TIMEOUT); con.setDoOutput(true); con.setDoInput(true); con.setRequestMethod("POST"); @@ -316,6 +321,8 @@ public static byte[] getOCSPBytes(List certIds, URI responderURI, return (contentLength == -1) ? con.getInputStream().readAllBytes() : IOUtils.readExactlyNBytes(con.getInputStream(), contentLength); + } catch (URISyntaxException urise) { + throw new IOException(urise); } finally { if (con != null) { con.disconnect(); diff --git a/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java b/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java index a3b9d176d1e..71abdbe87f4 100644 --- a/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java +++ b/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -50,7 +50,8 @@ import java.util.Collections; import java.util.List; import java.util.Locale; -import sun.security.action.GetIntegerAction; + +import sun.security.action.GetPropertyAction; import sun.security.x509.AccessDescription; import sun.security.x509.GeneralNameInterface; import sun.security.x509.URIName; @@ -127,8 +128,12 @@ class URICertStore extends CertStoreSpi { // allowed when downloading CRLs private static final int DEFAULT_CRL_READ_TIMEOUT = 15000; + // Default connect and read timeouts for CA certificate fetching (15 sec) + private static final int DEFAULT_CACERT_CONNECT_TIMEOUT = 15000; + private static final int DEFAULT_CACERT_READ_TIMEOUT = 15000; + /** - * Integer value indicating the connect timeout, in seconds, to be + * Integer value indicating the connect timeout, in milliseconds, to be * used for the CRL download. A timeout of zero is interpreted as * an infinite timeout. */ @@ -137,7 +142,7 @@ class URICertStore extends CertStoreSpi { DEFAULT_CRL_CONNECT_TIMEOUT); /** - * Integer value indicating the read timeout, in seconds, to be + * Integer value indicating the read timeout, in milliseconds, to be * used for the CRL download. A timeout of zero is interpreted as * an infinite timeout. */ @@ -145,22 +150,36 @@ class URICertStore extends CertStoreSpi { initializeTimeout("com.sun.security.crl.readtimeout", DEFAULT_CRL_READ_TIMEOUT); + /** + * Integer value indicating the connect timeout, in milliseconds, to be + * used for the CA certificate download. A timeout of zero is interpreted + * as an infinite timeout. + */ + private static final int CACERT_CONNECT_TIMEOUT = + initializeTimeout("com.sun.security.cert.timeout", + DEFAULT_CACERT_CONNECT_TIMEOUT); + + /** + * Integer value indicating the read timeout, in milliseconds, to be + * used for the CA certificate download. A timeout of zero is interpreted + * as an infinite timeout. + */ + private static final int CACERT_READ_TIMEOUT = + initializeTimeout("com.sun.security.cert.readtimeout", + DEFAULT_CACERT_READ_TIMEOUT); + /** * Initialize the timeout length by getting the specified CRL timeout * system property. If the property has not been set, or if its * value is negative, set the timeout length to the specified default. */ private static int initializeTimeout(String prop, int def) { - Integer tmp = GetIntegerAction.privilegedGetProperty(prop); - if (tmp == null || tmp < 0) { - return def; - } + int timeoutVal = + GetPropertyAction.privilegedGetTimeoutProp(prop, def, debug); if (debug != null) { - debug.println(prop + " set to " + tmp + " seconds"); + debug.println(prop + " set to " + timeoutVal + " milliseconds"); } - // Convert to milliseconds, as the system property will be - // specified in seconds - return tmp * 1000; + return timeoutVal; } /** @@ -276,6 +295,8 @@ static CertStore getInstance(AccessDescription ad) { connection.setIfModifiedSince(lastModified); } long oldLastModified = lastModified; + connection.setConnectTimeout(CACERT_CONNECT_TIMEOUT); + connection.setReadTimeout(CACERT_READ_TIMEOUT); try (InputStream in = connection.getInputStream()) { lastModified = connection.getLastModified(); if (oldLastModified != 0) { diff --git a/src/java.base/share/classes/sun/security/tools/keytool/Main.java b/src/java.base/share/classes/sun/security/tools/keytool/Main.java index 215b4a24c09..54b3a091090 100644 --- a/src/java.base/share/classes/sun/security/tools/keytool/Main.java +++ b/src/java.base/share/classes/sun/security/tools/keytool/Main.java @@ -1287,6 +1287,7 @@ && isKeyStoreRelated(command) kssave = true; } else if (command == LIST) { if (storePass == null + && !protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype) && !isPasswordlessKeyStore) { printNoIntegrityWarning(); @@ -1686,6 +1687,7 @@ private void doExportCert(String alias, PrintStream out) throws Exception { if (storePass == null + && !protectedPath && !KeyStoreUtil.isWindowsKeyStore(storetype) && !isPasswordlessKeyStore) { printNoIntegrityWarning(); diff --git a/src/java.base/share/classes/sun/security/x509/DNSName.java b/src/java.base/share/classes/sun/security/x509/DNSName.java index ee9e8a9c0a0..07259f4c7b9 100644 --- a/src/java.base/share/classes/sun/security/x509/DNSName.java +++ b/src/java.base/share/classes/sun/security/x509/DNSName.java @@ -202,18 +202,12 @@ public int hashCode() { * . These results are used in checking NameConstraints during * certification path verification. *

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

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

* RFC1034: By convention, domain names can be stored with arbitrary case, but * domain name comparisons for all present domain functions are done in a * case-insensitive manner, assuming an ASCII character set, and a high @@ -238,13 +232,13 @@ else if (inputName.getType() != NAME_DNS) constraintType = NAME_MATCH; else if (thisName.endsWith(inName)) { int inNdx = thisName.lastIndexOf(inName); - if (thisName.charAt(inNdx-1) == '.' ) + if (thisName.charAt(inNdx-1) == '.' ^ inName.charAt(0) == '.') constraintType = NAME_WIDENS; else constraintType = NAME_SAME_TYPE; } else if (inName.endsWith(thisName)) { int ndx = inName.lastIndexOf(thisName); - if (inName.charAt(ndx-1) == '.' ) + if (inName.charAt(ndx-1) == '.' ^ thisName.charAt(0) == '.') constraintType = NAME_NARROWS; else constraintType = NAME_SAME_TYPE; diff --git a/src/java.base/share/native/libjava/VM.c b/src/java.base/share/native/libjava/VM.c index 099ad46fff1..882cf45a5bb 100644 --- a/src/java.base/share/native/libjava/VM.c +++ b/src/java.base/share/native/libjava/VM.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include "jni.h" #include "jni_util.h" #include "jvm.h" @@ -30,6 +36,13 @@ #include "jdk_internal_misc_VM.h" +#if defined(AIX) || defined(WIN32) +#include "j9access.h" +/* tracehelp.c defines getTraceInterfaceFromVM(), used by J9_UTINTERFACE_FROM_VM(). */ +#include "tracehelp.c" +#include "ut_jcl_java.c" +#endif /* defined(AIX) || defined(WIN32) */ + /* Only register the performance-critical methods */ static JNINativeMethod methods[] = { {"getNanoTimeAdjustment", "(J)J", (void *)&JVM_GetNanoTimeAdjustment} @@ -42,6 +55,11 @@ Java_jdk_internal_misc_VM_latestUserDefinedLoader0(JNIEnv *env, jclass cls) { JNIEXPORT void JNICALL Java_jdk_internal_misc_VM_initialize(JNIEnv *env, jclass cls) { +#if defined(AIX) || defined(WIN32) + /* Other platforms do this in check_version.c JNI_OnLoad. */ + UT_JCL_JAVA_MODULE_LOADED(J9_UTINTERFACE_FROM_VM(((J9VMThread *) env)->javaVM)); +#endif /* defined(AIX) || defined(WIN32) */ + // Registers implementations of native methods described in methods[] // above. // In particular, registers JVM_GetNanoTimeAdjustment as the implementation diff --git a/src/java.base/share/native/libjava/check_version.c b/src/java.base/share/native/libjava/check_version.c index 17a590fea14..b8a1a909eb5 100644 --- a/src/java.base/share/native/libjava/check_version.c +++ b/src/java.base/share/native/libjava/check_version.c @@ -23,12 +23,30 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include "jni.h" #include "jni_util.h" #include "jvm.h" +#if !defined(AIX) && !defined(WIN32) +#include "j9access.h" +/* tracehelp.c defines getTraceInterfaceFromVM(), used by J9_UTINTERFACE_FROM_VM(). */ +#include "tracehelp.c" +#include "ut_jcl_java.c" +#endif /* !defined(AIX) && !defined(WIN32) */ + JNIEXPORT jint JNICALL DEF_JNI_OnLoad(JavaVM *vm, void *reserved) { +#if !defined(AIX) && !defined(WIN32) + /* Windows and AIX don't call JNI_OnLoad for libjava.dll, initialize the tracepoint elsewhere. */ + UT_JCL_JAVA_MODULE_LOADED(J9_UTINTERFACE_FROM_VM((J9JavaVM *)vm)); +#endif /* !defined(AIX) && !defined(WIN32) */ + return JNI_VERSION_1_2; } diff --git a/src/java.base/share/native/libnio/nio_util.c b/src/java.base/share/native/libnio/nio_util.c index 2235f0a5998..dbda9c4987c 100644 --- a/src/java.base/share/native/libnio/nio_util.c +++ b/src/java.base/share/native/libnio/nio_util.c @@ -23,10 +23,21 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include "jni.h" #include "jvm.h" #include "jni_util.h" +#include "j9access.h" +/* tracehelp.c defines getTraceInterfaceFromVM(), used by J9_UTINTERFACE_FROM_VM(). */ +#include "tracehelp.c" +#include "ut_jcl_nio.c" + JNIEXPORT jint JNICALL DEF_JNI_OnLoad(JavaVM *vm, void *reserved) { @@ -36,5 +47,7 @@ DEF_JNI_OnLoad(JavaVM *vm, void *reserved) return JNI_EVERSION; /* JNI version not supported */ } + UT_JCL_NIO_MODULE_LOADED(J9_UTINTERFACE_FROM_VM((J9JavaVM *)vm)); + return JNI_VERSION_1_2; } diff --git a/src/java.base/unix/native/libjava/UnixFileSystem_md.c b/src/java.base/unix/native/libjava/UnixFileSystem_md.c index 7c23aaa567c..9cb5b61d40a 100644 --- a/src/java.base/unix/native/libjava/UnixFileSystem_md.c +++ b/src/java.base/unix/native/libjava/UnixFileSystem_md.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include #include #include @@ -51,6 +57,8 @@ #include "java_io_FileSystem.h" #include "java_io_UnixFileSystem.h" +#include "ut_jcl_java.h" + #if defined(_AIX) #if !defined(NAME_MAX) #define NAME_MAX MAXNAMLEN @@ -281,6 +289,7 @@ Java_java_io_UnixFileSystem_createFileExclusively(JNIEnv *env, jclass cls, if (errno != EEXIST) JNU_ThrowIOExceptionWithLastError(env, "Could not open file"); } else { + Trc_io_UnixFileSystem_createFileExclusively_close(fd); if (close(fd) == -1) JNU_ThrowIOExceptionWithLastError(env, "Could not close file"); rv = JNI_TRUE; diff --git a/src/java.base/unix/native/libjava/io_util_md.c b/src/java.base/unix/native/libjava/io_util_md.c index e207c57d49b..f6bec874e53 100644 --- a/src/java.base/unix/native/libjava/io_util_md.c +++ b/src/java.base/unix/native/libjava/io_util_md.c @@ -22,6 +22,13 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include "jni.h" #include "jni_util.h" #include "jvm.h" @@ -39,6 +46,8 @@ #include #endif +#include "ut_jcl_java.h" + #ifdef MACOSX #include @@ -90,6 +99,11 @@ handleOpen(const char *path, int oflag, int mode) { fd = -1; } } + if (-1 == fd) { + Trc_io_handleOpen_err(path, oflag, mode, 0, 0, errno); + } else { + Trc_io_handleOpen(path, oflag, mode, 0, 0, (jlong)fd); + } return fd; } @@ -167,6 +181,7 @@ fileDescriptorClose(JNIEnv *env, jobject this) dup2(devnull, fd); close(devnull); } + Trc_io_fileDescriptorClose((jlong)fd); } else { int result; #if defined(_AIX) @@ -176,7 +191,10 @@ fileDescriptorClose(JNIEnv *env, jobject this) result = close(fd); #endif if (result == -1 && errno != EINTR) { + Trc_io_fileDescriptorClose_err((jlong)fd, errno); JNU_ThrowIOExceptionWithLastError(env, "close failed"); + } else { + Trc_io_fileDescriptorClose((jlong)fd); } } } diff --git a/src/java.base/unix/native/libjsig/jsig.c b/src/java.base/unix/native/libjsig/jsig.c index 1a0a6bec892..409b9399e8d 100644 --- a/src/java.base/unix/native/libjsig/jsig.c +++ b/src/java.base/unix/native/libjsig/jsig.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * Copyright (c) 2012, 2015 SAP SE. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * @@ -102,9 +102,9 @@ static sa_handler_t call_os_signal(int sig, sa_handler_t disp, if (os_signal == NULL) { // Deprecation warning first time through - printf(HOTSPOT_VM_DISTRO " VM warning: the use of signal() and sigset() " - "for signal chaining was deprecated in version 16.0 and will " - "be removed in a future release. Use sigaction() instead.\n"); + fprintf(stderr, HOTSPOT_VM_DISTRO " VM warning: the use of signal() and sigset() " + "for signal chaining was deprecated in version 16.0 and will " + "be removed in a future release. Use sigaction() instead.\n"); if (!is_sigset) { os_signal = (signal_function_t)dlsym(RTLD_NEXT, "signal"); } else { diff --git a/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c b/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c index c0c31d6ab2c..326de29e0b5 100644 --- a/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c +++ b/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include #include #include @@ -63,6 +69,8 @@ #include "sun_nio_ch_FileDispatcherImpl.h" #include "java_lang_Long.h" +#include "ut_jcl_nio.h" + static int preCloseFD = -1; /* File descriptor to which we dup other fd's before closing them for real */ @@ -301,6 +309,7 @@ Java_sun_nio_ch_FileDispatcherImpl_release0(JNIEnv *env, jobject this, static void closeFileDescriptor(JNIEnv *env, int fd) { if (fd != -1) { + Trc_nio_ch_FileDispatcherImpl_close(fd); int result = close(fd); if (result < 0) JNU_ThrowIOExceptionWithLastError(env, "Close failed"); diff --git a/src/java.base/unix/native/libnio/ch/Net.c b/src/java.base/unix/native/libnio/ch/Net.c index d4a15b34ea6..0c393a58b84 100644 --- a/src/java.base/unix/native/libnio/ch/Net.c +++ b/src/java.base/unix/native/libnio/ch/Net.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include #include #include @@ -30,6 +36,7 @@ #include #include #include +#include #include "jni.h" #include "jni_util.h" @@ -46,6 +53,8 @@ #include #endif +#include "ut_jcl_nio.h" + /** * IP_MULTICAST_ALL supported since 2.6.31 but may not be available at * build time. @@ -364,12 +373,22 @@ Java_sun_nio_ch_Net_connect0(JNIEnv *env, jclass clazz, jboolean preferIPv6, SOCKETADDRESS sa; int sa_len = 0; int rv; + int fd; if (NET_InetAddressToSockaddr(env, iao, port, &sa, &sa_len, preferIPv6) != 0) { return IOS_THROWN; } - rv = connect(fdval(env, fdo), &sa.sa, sa_len); + fd = fdval(env, fdo); + if (AF_INET == sa.sa4.sin_family) { + char buf[INET_ADDRSTRLEN]; + Trc_nio_ch_Net_connect4((jlong)fd, inet_ntop(AF_INET, &sa.sa4.sin_addr, buf, sizeof(buf)), port, sa_len); + } else if (AF_INET6 == sa.sa6.sin6_family) { + char buf[INET6_ADDRSTRLEN]; + Trc_nio_ch_Net_connect6((jlong)fd, inet_ntop(AF_INET6, &sa.sa6.sin6_addr, buf, sizeof(buf)), port, ntohl(sa.sa6.sin6_scope_id), sa_len); + } + + rv = connect(fd, &sa.sa, sa_len); if (rv != 0) { if (errno == EINPROGRESS) { return IOS_UNAVAILABLE; diff --git a/src/java.base/unix/native/libnio/ch/UnixDomainSockets.c b/src/java.base/unix/native/libnio/ch/UnixDomainSockets.c index f119537593a..4369a620ce8 100644 --- a/src/java.base/unix/native/libnio/ch/UnixDomainSockets.c +++ b/src/java.base/unix/native/libnio/ch/UnixDomainSockets.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include #include #include @@ -41,6 +47,8 @@ #include "nio_util.h" #include "nio.h" +#include "ut_jcl_nio.h" + /* Subtle platform differences in how unnamed sockets (empty path) * are returned from getsockname() */ @@ -132,12 +140,16 @@ Java_sun_nio_ch_UnixDomainSockets_connect0(JNIEnv *env, jclass clazz, jobject fd struct sockaddr_un sa; int sa_len = 0; int rv; + int fd; if (unixSocketAddressToSockaddr(env, path, &sa, &sa_len) != 0) { return IOS_THROWN; } - rv = connect(fdval(env, fdo), (struct sockaddr *)&sa, sa_len); + fd = fdval(env, fdo); + Trc_nio_ch_UnixDomainSockets_connect(fd, sa.sun_path, sa_len); + + rv = connect(fd, (struct sockaddr *)&sa, sa_len); if (rv != 0) { if (errno == EINPROGRESS) { return IOS_UNAVAILABLE; diff --git a/src/java.base/windows/native/libjava/io_util_md.c b/src/java.base/windows/native/libjava/io_util_md.c index fee837b6c0a..9afd0d773b5 100644 --- a/src/java.base/windows/native/libjava/io_util_md.c +++ b/src/java.base/windows/native/libjava/io_util_md.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include "jni.h" #include "jni_util.h" #include "jvm.h" @@ -41,6 +47,7 @@ #include #include +#include "ut_jcl_java.h" static DWORD MAX_INPUT_EVENTS = 2000; @@ -236,12 +243,22 @@ FD winFileHandleOpen(JNIEnv *env, jstring path, int flags) FILE_ATTRIBUTE_NORMAL; const DWORD flagsAndAttributes = maybeWriteThrough | maybeDeleteOnClose; HANDLE h = NULL; + char *pathStr = NULL; WCHAR *pathbuf = pathToNTPath(env, path, JNI_TRUE); if (pathbuf == NULL) { /* Exception already pending */ return -1; } + + if (TrcEnabled_Trc_io_handleOpen) { + int length = WideCharToMultiByte(CP_UTF8, 0, pathbuf, -1, NULL, 0, NULL, NULL); + pathStr = malloc(length); + if (NULL != pathStr) { + WideCharToMultiByte(CP_UTF8, 0, pathbuf, -1, pathStr, length, NULL, NULL); + } + } + h = CreateFileW( pathbuf, /* Wide char path name */ access, /* Read and/or write permission */ @@ -253,9 +270,13 @@ FD winFileHandleOpen(JNIEnv *env, jstring path, int flags) free(pathbuf); if (h == INVALID_HANDLE_VALUE) { + Trc_io_handleOpen_err(pathStr, access, sharing, disposition, flagsAndAttributes, GetLastError()); + free(pathStr); throwFileNotFoundException(env, path); return -1; } + Trc_io_handleOpen(pathStr, access, sharing, disposition, flagsAndAttributes, (jlong)h); + free(pathStr); return (jlong) h; } @@ -559,7 +580,10 @@ fileDescriptorClose(JNIEnv *env, jobject this) } if (CloseHandle(h) == 0) { /* Returns zero on failure */ + Trc_io_fileDescriptorClose_err((jlong)fd, GetLastError()); JNU_ThrowIOExceptionWithLastError(env, "close failed"); + } else { + Trc_io_fileDescriptorClose((jlong)fd); } } diff --git a/src/java.base/windows/native/libnio/ch/Net.c b/src/java.base/windows/native/libnio/ch/Net.c index d4410c0ca2d..99bf3647073 100644 --- a/src/java.base/windows/native/libnio/ch/Net.c +++ b/src/java.base/windows/native/libnio/ch/Net.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include #include @@ -37,6 +43,8 @@ #include "sun_nio_ch_Net.h" #include "sun_nio_ch_PollArrayWrapper.h" +#include "ut_jcl_nio.h" + /** * Definitions to allow for building with older SDK include files. */ @@ -239,6 +247,14 @@ Java_sun_nio_ch_Net_connect0(JNIEnv *env, jclass clazz, jboolean preferIPv6, job NET_EnableFastTcpLoopbackConnect((jint)s); } + if (AF_INET == sa.sa4.sin_family) { + char buf[INET_ADDRSTRLEN]; + Trc_nio_ch_Net_connect4((jlong)s, inet_ntop(AF_INET, &sa.sa4.sin_addr, buf, sizeof(buf)), port, sa_len); + } else if (AF_INET6 == sa.sa6.sin6_family) { + char buf[INET6_ADDRSTRLEN]; + Trc_nio_ch_Net_connect6((jlong)s, inet_ntop(AF_INET6, &sa.sa6.sin6_addr, buf, sizeof(buf)), port, ntohl(sa.sa6.sin6_scope_id), sa_len); + } + rv = connect(s, &sa.sa, sa_len); if (rv != 0) { int err = WSAGetLastError(); diff --git a/src/java.base/windows/native/libnio/ch/SocketDispatcher.c b/src/java.base/windows/native/libnio/ch/SocketDispatcher.c index ff74a0abf10..96f9846ee58 100644 --- a/src/java.base/windows/native/libnio/ch/SocketDispatcher.c +++ b/src/java.base/windows/native/libnio/ch/SocketDispatcher.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include #include #include @@ -34,6 +40,8 @@ #include "nio.h" #include "nio_util.h" +#include "ut_jcl_nio.h" + /************************************************************** * SocketDispatcher.c @@ -282,6 +290,7 @@ Java_sun_nio_ch_SocketDispatcher_writev0(JNIEnv *env, jclass clazz, JNIEXPORT void JNICALL Java_sun_nio_ch_SocketDispatcher_close0(JNIEnv *env, jclass clazz, jint fd) { + Trc_nio_ch_SocketDispatcher_close(fd); if (closesocket(fd) == SOCKET_ERROR) { JNU_ThrowIOExceptionWithLastError(env, "Socket close failed"); } diff --git a/src/java.base/windows/native/libnio/ch/UnixDomainSockets.c b/src/java.base/windows/native/libnio/ch/UnixDomainSockets.c index 209c30f3be7..7bd6f06a555 100644 --- a/src/java.base/windows/native/libnio/ch/UnixDomainSockets.c +++ b/src/java.base/windows/native/libnio/ch/UnixDomainSockets.c @@ -23,6 +23,12 @@ * questions. */ +/* + * =========================================================================== + * (c) Copyright IBM Corp. 2025, 2025 All Rights Reserved + * =========================================================================== + */ + #include #include @@ -38,6 +44,8 @@ #include "sun_nio_ch_Net.h" #include "sun_nio_ch_PollArrayWrapper.h" +#include "ut_jcl_nio.h" + /* The winsock provider ID of the Microsoft AF_UNIX implementation */ static GUID MS_PROVIDER_ID = {0xA00943D9,0x9C2E,0x4633,{0x9B,0x59,0,0x57,0xA3,0x16,0x09,0x94}}; @@ -192,12 +200,16 @@ Java_sun_nio_ch_UnixDomainSockets_connect0(JNIEnv *env, jclass clazz, jobject fd struct sockaddr_un sa; int sa_len = 0; int rv; + int fd; if (unixSocketAddressToSockaddr(env, addr, &sa, &sa_len) != 0) { return IOS_THROWN; } - rv = connect(fdval(env, fdo), (const struct sockaddr *)&sa, sa_len); + fd = fdval(env, fdo); + Trc_nio_ch_UnixDomainSockets_connect(fd, sa.sun_path, sa_len); + + rv = connect(fd, (const struct sockaddr *)&sa, sa_len); if (rv != 0) { int err = WSAGetLastError(); if (err == WSAEINPROGRESS || err == WSAEWOULDBLOCK) { diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m index 5826cbf31d1..79c5abdbc2c 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTWindow.m @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -1695,6 +1695,7 @@ + (AWTWindow *) lastKeyWindow { int shieldLevel = CGShieldingWindowLevel(); window.preFullScreenLevel = [nsWindow level]; [nsWindow setLevel: shieldLevel]; + [nsWindow makeKeyAndOrderFront: nil]; NSRect screenRect = [[nsWindow screen] frame]; [nsWindow setFrame:screenRect display:YES]; diff --git a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m index f9f13ca207f..e8b28d93068 100644 --- a/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m +++ b/src/java.desktop/macosx/native/libawt_lwawt/awt/a11y/MenuAccessibility.m @@ -32,9 +32,13 @@ @implementation MenuAccessibility - (NSAccessibilityRole _Nonnull)accessibilityRole { - return [[[self parent] javaRole] isEqualToString:@"combobox"] - ? NSAccessibilityPopUpButtonRole - : NSAccessibilityMenuRole; + if ([[[self parent] javaRole] isEqualToString:@"combobox"]) { + return NSAccessibilityPopUpButtonRole; + } else if ([[[self parent] javaRole] isEqualToString:@"menubar"]) { + return NSAccessibilityMenuBarItemRole; + } else { + return NSAccessibilityMenuRole; + } } - (BOOL)isAccessibilityElement diff --git a/src/java.desktop/share/classes/javax/swing/JTabbedPane.java b/src/java.desktop/share/classes/javax/swing/JTabbedPane.java index af5c917ee76..3406e6ea945 100644 --- a/src/java.desktop/share/classes/javax/swing/JTabbedPane.java +++ b/src/java.desktop/share/classes/javax/swing/JTabbedPane.java @@ -55,6 +55,7 @@ import javax.accessibility.AccessibleSelection; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; +import javax.accessibility.AccessibleValue; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.plaf.TabbedPaneUI; @@ -2074,7 +2075,7 @@ public void selectAllAccessibleSelection() { } private class Page extends AccessibleContext - implements Serializable, Accessible, AccessibleComponent { + implements Serializable, Accessible, AccessibleComponent, AccessibleValue { String title; Color background; Color foreground; @@ -2168,7 +2169,6 @@ public AccessibleContext getAccessibleContext() { return this; } - // AccessibleContext methods public String getAccessibleName() { @@ -2202,6 +2202,43 @@ public AccessibleStateSet getAccessibleStateSet() { return states; } + @Override + public AccessibleValue getAccessibleValue() { + return this; + } + + @Override + public Number getCurrentAccessibleValue() { + return (getPageIndex() == parent.getSelectedIndex() ? + Integer.valueOf(1) : Integer.valueOf(0)); + } + + @Override + public boolean setCurrentAccessibleValue(Number n) { + if (getPageIndex() != parent.getSelectedIndex()) { + if (n.intValue() != 0) { + // Set current page selected + parent.setSelectedIndex(getPageIndex()); + } + } else { + if (n.intValue() == 0) { + // Can not "deselect" because what page should i select instead? + return false; + } + } + return true; + } + + @Override + public Number getMinimumAccessibleValue() { + return Integer.valueOf(0); + } + + @Override + public Number getMaximumAccessibleValue() { + return Integer.valueOf(1); + } + public int getAccessibleIndexInParent() { return getPageIndex(); } @@ -2368,7 +2405,7 @@ public void removeFocusListener(FocusListener l) { * one exists and the page is disabled. Otherwise, null * is returned. */ - public AccessibleIcon [] getAccessibleIcon() { + public AccessibleIcon[] getAccessibleIcon() { AccessibleIcon accessibleIcon = null; if (enabled && icon instanceof ImageIcon) { AccessibleContext ac = diff --git a/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java b/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java index a980268bd94..c20ff2d9cfa 100644 --- a/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java +++ b/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -366,6 +366,8 @@ protected void moveCaret(MouseEvent e) { } } + private int savedBlinkRate = 0; + private boolean isBlinkRateSaved = false; // --- FocusListener methods -------------------------- /** @@ -379,8 +381,21 @@ protected void moveCaret(MouseEvent e) { public void focusGained(FocusEvent e) { if (component.isEnabled()) { if (component.isEditable()) { - setVisible(true); + if (isBlinkRateSaved) { + setBlinkRate(savedBlinkRate); + savedBlinkRate = 0; + isBlinkRateSaved = false; + } + } else { + if (getBlinkRate() != 0) { + if (!isBlinkRateSaved) { + savedBlinkRate = getBlinkRate(); + isBlinkRateSaved = true; + } + setBlinkRate(0); + } } + setVisible(true); setSelectionVisible(true); updateSystemSelection(); } @@ -1031,17 +1046,29 @@ public void setVisible(boolean e) { * @see Caret#setBlinkRate */ public void setBlinkRate(int rate) { + if (rate < 0) { + throw new IllegalArgumentException("Invalid blink rate: " + rate); + } if (rate != 0) { - if (flasher == null) { - flasher = new Timer(rate, handler); + if (component.isEditable()) { + if (flasher == null) { + flasher = new Timer(rate, handler); + } + flasher.setDelay(rate); + } else { + savedBlinkRate = rate; + isBlinkRateSaved = true; } - flasher.setDelay(rate); } else { if (flasher != null) { flasher.stop(); flasher.removeActionListener(handler); flasher = null; } + if (component.isEditable() && isBlinkRateSaved) { + savedBlinkRate = 0; + isBlinkRateSaved = false; + } } } @@ -1053,6 +1080,9 @@ public void setBlinkRate(int rate) { * @see Caret#getBlinkRate */ public int getBlinkRate() { + if (isBlinkRateSaved) { + return savedBlinkRate; + } return (flasher == null) ? 0 : flasher.getDelay(); } diff --git a/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp b/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp index 1a7a89fdef4..714becbca20 100644 --- a/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp +++ b/src/java.desktop/windows/native/libawt/windows/awt_Button.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -242,7 +242,7 @@ AwtButton::OwnerDrawItem(UINT /*ctrlId*/, DRAWITEMSTRUCT& drawInfo) RECT focusRect; VERIFY(::CopyRect(&focusRect, &rect)); VERIFY(::InflateRect(&focusRect,-inf,-inf)); - if(::DrawFocusRect(hDC, &focusRect) == 0) + if (!::IsRectEmpty(&focusRect) && (::DrawFocusRect(hDC, &focusRect) == 0)) VERIFY(::GetLastError() == 0); } diff --git a/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp b/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp index d77ebb74a3e..f50ddbb5d57 100644 --- a/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp +++ b/src/java.desktop/windows/native/libawt/windows/awt_Checkbox.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -290,13 +290,13 @@ AwtCheckbox::OwnerDrawItem(UINT /*ctrlId*/, DRAWITEMSTRUCT& drawInfo) if ((drawInfo.itemState & ODS_FOCUS) && ((drawInfo.itemAction & ODA_FOCUS)|| (drawInfo.itemAction &ODA_DRAWENTIRE))) { - if(::DrawFocusRect(hDC, &focusRect) == 0) + if (!::IsRectEmpty(&focusRect) && (::DrawFocusRect(hDC, &focusRect) == 0)) VERIFY(::GetLastError() == 0); } /* erase focus rect */ else if (!(drawInfo.itemState & ODS_FOCUS) && (drawInfo.itemAction & ODA_FOCUS)) { - if(::DrawFocusRect(hDC, &focusRect) == 0) + if (!::IsRectEmpty(&focusRect) && (::DrawFocusRect(hDC, &focusRect) == 0)) VERIFY(::GetLastError() == 0); } diff --git a/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp b/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp index 03f54d6491c..7c0ac107e56 100644 --- a/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp +++ b/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 2025, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -4499,7 +4499,7 @@ void AwtComponent::DrawListItem(JNIEnv *env, DRAWITEMSTRUCT &drawInfo) if ((drawInfo.itemState & ODS_FOCUS) && (drawInfo.itemAction & (ODA_FOCUS | ODA_DRAWENTIRE))) { if (!unfocusableChoice){ - if(::DrawFocusRect(hDC, &rect) == 0) + if (!::IsRectEmpty(&rect) && (::DrawFocusRect(hDC, &rect) == 0)) VERIFY(::GetLastError() == 0); } } diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java index 1184d293a62..d7574f593f9 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/Config.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -136,6 +136,9 @@ private static void debug(Object o) { // whether to print debug info during startup private boolean showInfo = false; + // whether to allow legacy mechanisms + private boolean allowLegacy = false; + // template manager, initialized from parsed attributes private TemplateManager templateManager; @@ -270,6 +273,10 @@ boolean getShowInfo() { return (SunPKCS11.debug != null) || showInfo; } + boolean getAllowLegacy() { + return allowLegacy; + } + TemplateManager getTemplateManager() { if (templateManager == null) { templateManager = new TemplateManager(); @@ -463,6 +470,8 @@ private void parse() throws IOException { destroyTokenAfterLogout = parseBooleanEntry(word); } else if (word.equals("showInfo")) { showInfo = parseBooleanEntry(word); + } else if (word.equals("allowLegacy")) { + allowLegacy = parseBooleanEntry(word); } else if (word.equals("keyStoreCompatibilityMode")) { keyStoreCompatibilityMode = parseBooleanEntry(word); } else if (word.equals("explicitCancel")) { diff --git a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java index a0093bde967..30ea3b9dd66 100644 --- a/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java +++ b/src/jdk.crypto.cryptoki/share/classes/sun/security/pkcs11/SunPKCS11.java @@ -1294,25 +1294,6 @@ public Object run() { } } - private static boolean isLegacy(CK_MECHANISM_INFO mechInfo) - throws PKCS11Exception { - // assume full support if no mech info available - // For vendor-specific mechanisms, often no mech info is provided - boolean partialSupport = false; - - if (mechInfo != null) { - if ((mechInfo.flags & CKF_DECRYPT) != 0) { - // non-legacy cipher mechs should support encryption - partialSupport |= ((mechInfo.flags & CKF_ENCRYPT) == 0); - } - if ((mechInfo.flags & CKF_VERIFY) != 0) { - // non-legacy signature mechs should support signing - partialSupport |= ((mechInfo.flags & CKF_SIGN) == 0); - } - } - return partialSupport; - } - // test if a token is present and initialize this provider for it if so. // does nothing if no token is found // called from constructor and by poller @@ -1363,12 +1344,6 @@ private void initToken(CK_SLOT_INFO slotInfo) throws PKCS11Exception { } continue; } - if (isLegacy(mechInfo)) { - if (showInfo) { - System.out.println("DISABLED due to legacy"); - } - continue; - } // we do not know of mechs with the upper 32 bits set if (longMech >>> 32 != 0) { @@ -1383,9 +1358,25 @@ private void initToken(CK_SLOT_INFO slotInfo) throws PKCS11Exception { if (ds == null) { continue; } + boolean allowLegacy = config.getAllowLegacy(); for (Descriptor d : ds) { Integer oldMech = supportedAlgs.get(d); if (oldMech == null) { + + // assume full support if no mech info available + if (!allowLegacy && mechInfo != null) { + if ((d.type == CIP && + (mechInfo.flags & CKF_ENCRYPT) == 0) || + (d.type == SIG && + (mechInfo.flags & CKF_SIGN) == 0)) { + if (showInfo) { + System.out.println("DISABLED " + d.type + + " " + d.algorithm + + " due to partial support"); + } + continue; + } + } supportedAlgs.put(d, integerMech); continue; } diff --git a/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md b/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md index 08d1e3c713d..7877f54fe6e 100644 --- a/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md +++ b/src/jdk.crypto.cryptoki/share/legal/pkcs11cryptotoken.md @@ -1,16 +1,16 @@ -## OASIS PKCS #11 Cryptographic Token Interface v3.0 +## OASIS PKCS #11 Cryptographic Token Interface v3.1 ### OASIS PKCS #11 Cryptographic Token Interface License

 
-Copyright © OASIS Open 2020. All Rights Reserved.
+Copyright © OASIS Open 2023. All Rights Reserved.
 
-    All capitalized terms in the following text have the meanings
+All capitalized terms in the following text have the meanings
 assigned to them in the OASIS Intellectual Property Rights Policy (the
 "OASIS IPR Policy"). The full Policy may be found at the OASIS website:
-[http://www.oasis-open.org/policies-guidelines/ipr]
+[https://www.oasis-open.org/policies-guidelines/ipr/].
 
-    This document and translations of it may be copied and furnished to
+This document and translations of it may be copied and furnished to
 others, and derivative works that comment on or otherwise explain it or
 assist in its implementation may be prepared, copied, published, and
 distributed, in whole or in part, without restriction of any kind,
@@ -23,10 +23,10 @@ Committee (in which case the rules applicable to copyrights, as set
 forth in the OASIS IPR Policy, must be followed) or as required to
 translate it into languages other than English.
 
-    The limited permissions granted above are perpetual and will not be
+The limited permissions granted above are perpetual and will not be
 revoked by OASIS or its successors or assigns.
 
-    This document and the information contained herein is provided on an
+This document and the information contained herein is provided on an
 "AS IS" basis and OASIS DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED,
 INCLUDING BUT NOT LIMITED TO ANY WARRANTY THAT THE USE OF THE
 INFORMATION HEREIN WILL NOT INFRINGE ANY OWNERSHIP RIGHTS OR ANY IMPLIED
@@ -35,7 +35,11 @@ AND ITS MEMBERS WILL NOT BE LIABLE FOR ANY DIRECT, INDIRECT, SPECIAL OR
 CONSEQUENTIAL DAMAGES ARISING OUT OF ANY USE OF THIS DOCUMENT OR ANY
 PART THEREOF.
 
-    [OASIS requests that any OASIS Party or any other party that
+As stated in the OASIS IPR Policy, the following three paragraphs in
+brackets apply to OASIS Standards Final Deliverable documents (Committee
+Specifications, OASIS Standards, or Approved Errata).
+
+[OASIS requests that any OASIS Party or any other party that
 believes it has patent claims that would necessarily be infringed by
 implementations of this OASIS Standards Final Deliverable, to notify
 OASIS TC Administrator and provide an indication of its willingness to
@@ -43,7 +47,7 @@ grant patent licenses to such patent claims in a manner consistent with
 the IPR Mode of the OASIS Technical Committee that produced this
 deliverable.]
 
-    [OASIS invites any party to contact the OASIS TC Administrator if it
+[OASIS invites any party to contact the OASIS TC Administrator if it
 is aware of a claim of ownership of any patent claims that would
 necessarily be infringed by implementations of this OASIS Standards
 Final Deliverable by a patent holder that is not willing to provide a
@@ -52,7 +56,7 @@ of the OASIS Technical Committee that produced this OASIS Standards
 Final Deliverable. OASIS may include such claims on its website, but
 disclaims any obligation to do so.]
 
-    [OASIS takes no position regarding the validity or scope of any
+[OASIS takes no position regarding the validity or scope of any
 intellectual property or other rights that might be claimed to pertain
 to the implementation or use of the technology described in this OASIS
 Standards Final Deliverable or the extent to which any license under
diff --git a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h
index 5b050def520..5933da0e3b7 100644
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11.h
@@ -1,8 +1,11 @@
-/* Copyright (c) OASIS Open 2016-2019. All Rights Reserved.
- * Distributed under the terms of the OASIS IPR Policy,
- * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
- * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
+/*
+ * PKCS #11 Specification Version 3.1
+ * OASIS Standard
+ * 23 July 2023
+ * Copyright (c) OASIS Open 2023. All Rights Reserved.
+ * Source: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/include/pkcs11-v3.1/
+ * Latest stage of narrative specification: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/pkcs11-spec-v3.1.html
+ * TC IPR Statement: https://www.oasis-open.org/committees/pkcs11/ipr.php
  */
 
 #ifndef _PKCS11_H_
@@ -47,7 +50,7 @@ extern "C" {
  *
  * typedef CK_BYTE CK_PTR CK_BYTE_PTR;
  *
- * If you're using windows, it might be defined by:
+ * If you're using Windows, it might be defined by:
  *
  * #define CK_PTR *
  *
@@ -65,7 +68,7 @@ extern "C" {
  *   CK_VOID_PTR pReserved
  * );
  *
- * If you're using Windows to declare a function in a Win32 cryptoki .dll,
+ * If you're using Windows to declare a function in a Win32 Cryptoki .dll,
  * it might be defined by:
  *
  * #define CK_DECLARE_FUNCTION(returnType, name) \
@@ -241,4 +244,3 @@ struct CK_FUNCTION_LIST {
 
 #endif /* _PKCS11_H_ */
 
-
diff --git a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h
index 0553c1dc73c..80c43400d05 100644
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11f.h
@@ -1,12 +1,11 @@
-/* Copyright (c) OASIS Open 2016, 2019. All Rights Reserved./
- * /Distributed under the terms of the OASIS IPR Policy,
- * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
- * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
- */
-
-/* Latest version of the specification:
- * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
+/*
+ * PKCS #11 Specification Version 3.1
+ * OASIS Standard
+ * 23 July 2023
+ * Copyright (c) OASIS Open 2023. All Rights Reserved.
+ * Source: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/include/pkcs11-v3.1/
+ * Latest stage of narrative specification: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/pkcs11-spec-v3.1.html
+ * TC IPR Statement: https://www.oasis-open.org/committees/pkcs11/ipr.php
  */
 
 /* This header file contains pretty much everything about all the
diff --git a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h
index db8e04ff9ea..3a25b739dd6 100644
--- a/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h
+++ b/src/jdk.crypto.cryptoki/share/native/libj2pkcs11/pkcs11t.h
@@ -1,8 +1,11 @@
-/* Copyright (c) OASIS Open 2016, 2019. All Rights Reserved./
- * /Distributed under the terms of the OASIS IPR Policy,
- * [http://www.oasis-open.org/policies-guidelines/ipr], AS-IS, WITHOUT ANY
- * IMPLIED OR EXPRESS WARRANTY; there is no warranty of MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE or NONINFRINGEMENT of the rights of others.
+/*
+ * PKCS #11 Specification Version 3.1
+ * OASIS Standard
+ * 23 July 2023
+ * Copyright (c) OASIS Open 2023. All Rights Reserved.
+ * Source: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/os/include/pkcs11-v3.1/
+ * Latest stage of narrative specification: https://docs.oasis-open.org/pkcs11/pkcs11-spec/v3.1/pkcs11-spec-v3.1.html
+ * TC IPR Statement: https://www.oasis-open.org/committees/pkcs11/ipr.php
  */
 
 /*
@@ -11,10 +14,6 @@
  * ===========================================================================
  */
 
-/* Latest version of the specification:
- * http://docs.oasis-open.org/pkcs11/pkcs11-base/v2.40/pkcs11-base-v2.40.html
- */
-
 /* See top of pkcs11.h for information about the macros that
  * must be defined and the structure-packing conventions that
  * must be set before including this file.
@@ -24,7 +23,7 @@
 #define _PKCS11T_H_ 1
 
 #define CRYPTOKI_VERSION_MAJOR          3
-#define CRYPTOKI_VERSION_MINOR          0
+#define CRYPTOKI_VERSION_MINOR          1
 #define CRYPTOKI_VERSION_AMENDMENT      0
 
 #define CK_TRUE         1
@@ -335,8 +334,11 @@ typedef CK_OBJECT_CLASS CK_PTR CK_OBJECT_CLASS_PTR;
 #define CKP_EXTENDED_PROVIDER         0x00000002UL
 #define CKP_AUTHENTICATION_TOKEN      0x00000003UL
 #define CKP_PUBLIC_CERTIFICATES_TOKEN 0x00000004UL
+#define CKP_COMPLETE_PROVIDER         0x00000005UL
+#define CKP_HKDF_TLS_TOKEN            0x00000006UL
 #define CKP_VENDOR_DEFINED            0x80000000UL
 
+
 /* CK_HW_FEATURE_TYPE is a value that identifies the hardware feature type
  * of an object with CK_OBJECT_CLASS equal to CKO_HW_FEATURE.
  */
@@ -415,9 +417,11 @@ typedef CK_ULONG          CK_KEY_TYPE;
 #define CKK_EC_EDWARDS          0x00000040UL
 #define CKK_EC_MONTGOMERY       0x00000041UL
 #define CKK_HKDF                0x00000042UL
+
 #define CKK_SHA512_224_HMAC     0x00000043UL
 #define CKK_SHA512_256_HMAC     0x00000044UL
 #define CKK_SHA512_T_HMAC       0x00000045UL
+#define CKK_HSS                 0x00000046UL
 
 #define CKK_VENDOR_DEFINED      0x80000000UL
 
@@ -487,9 +491,9 @@ typedef CK_ULONG          CK_ATTRIBUTE_TYPE;
 #define CKA_CERTIFICATE_CATEGORY        0x00000087UL
 #define CKA_JAVA_MIDP_SECURITY_DOMAIN   0x00000088UL
 #define CKA_URL                         0x00000089UL
-#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY  0x0000008AUL
-#define CKA_HASH_OF_ISSUER_PUBLIC_KEY   0x0000008BUL
-#define CKA_NAME_HASH_ALGORITHM         0x0000008CUL
+#define CKA_HASH_OF_SUBJECT_PUBLIC_KEY  0x0000008aUL
+#define CKA_HASH_OF_ISSUER_PUBLIC_KEY   0x0000008bUL
+#define CKA_NAME_HASH_ALGORITHM         0x0000008cUL
 #define CKA_CHECK_VALUE                 0x00000090UL
 
 #define CKA_KEY_TYPE           0x00000100UL
@@ -502,9 +506,9 @@ typedef CK_ULONG          CK_ATTRIBUTE_TYPE;
 #define CKA_UNWRAP             0x00000107UL
 #define CKA_SIGN               0x00000108UL
 #define CKA_SIGN_RECOVER       0x00000109UL
-#define CKA_VERIFY             0x0000010AUL
-#define CKA_VERIFY_RECOVER     0x0000010BUL
-#define CKA_DERIVE             0x0000010CUL
+#define CKA_VERIFY             0x0000010aUL
+#define CKA_VERIFY_RECOVER     0x0000010bUL
+#define CKA_DERIVE             0x0000010cUL
 #define CKA_START_DATE         0x00000110UL
 #define CKA_END_DATE           0x00000111UL
 #define CKA_MODULUS            0x00000120UL
@@ -561,12 +565,12 @@ typedef CK_ULONG          CK_ATTRIBUTE_TYPE;
 #define CKA_OTP_TIME_REQUIREMENT      0x00000225UL
 #define CKA_OTP_COUNTER_REQUIREMENT   0x00000226UL
 #define CKA_OTP_PIN_REQUIREMENT       0x00000227UL
-#define CKA_OTP_COUNTER               0x0000022EUL
-#define CKA_OTP_TIME                  0x0000022FUL
-#define CKA_OTP_USER_IDENTIFIER       0x0000022AUL
-#define CKA_OTP_SERVICE_IDENTIFIER    0x0000022BUL
-#define CKA_OTP_SERVICE_LOGO          0x0000022CUL
-#define CKA_OTP_SERVICE_LOGO_TYPE     0x0000022DUL
+#define CKA_OTP_COUNTER               0x0000022eUL
+#define CKA_OTP_TIME                  0x0000022fUL
+#define CKA_OTP_USER_IDENTIFIER       0x0000022aUL
+#define CKA_OTP_SERVICE_IDENTIFIER    0x0000022bUL
+#define CKA_OTP_SERVICE_LOGO          0x0000022cUL
+#define CKA_OTP_SERVICE_LOGO_TYPE     0x0000022dUL
 
 #define CKA_GOSTR3410_PARAMS            0x00000250UL
 #define CKA_GOSTR3411_PARAMS            0x00000251UL
@@ -592,6 +596,7 @@ typedef CK_ULONG          CK_ATTRIBUTE_TYPE;
 #define CKA_SUPPORTED_CMS_ATTRIBUTES    0x00000503UL
 #define CKA_ALLOWED_MECHANISMS          (CKF_ARRAY_ATTRIBUTE|0x00000600UL)
 #define CKA_PROFILE_ID                  0x00000601UL
+
 #define CKA_X2RATCHET_BAG               0x00000602UL
 #define CKA_X2RATCHET_BAGSIZE           0x00000603UL
 #define CKA_X2RATCHET_BOBS1STMSG        0x00000604UL
@@ -609,6 +614,13 @@ typedef CK_ULONG          CK_ATTRIBUTE_TYPE;
 #define CKA_X2RATCHET_NS                0x00000610UL
 #define CKA_X2RATCHET_PNS               0x00000611UL
 #define CKA_X2RATCHET_RK                0x00000612UL
+/* HSS */
+#define CKA_HSS_LEVELS                  0x00000617UL
+#define CKA_HSS_LMS_TYPE                0x00000618UL
+#define CKA_HSS_LMOTS_TYPE              0x00000619UL
+#define CKA_HSS_LMS_TYPES               0x0000061aUL
+#define CKA_HSS_LMOTS_TYPES             0x0000061bUL
+#define CKA_HSS_KEYS_REMAINING          0x0000061cUL
 
 #define CKA_VENDOR_DEFINED              0x80000000UL
 
@@ -650,11 +662,11 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_RIPEMD160_RSA_PKCS         0x00000008UL
 #define CKM_RSA_PKCS_OAEP              0x00000009UL
 
-#define CKM_RSA_X9_31_KEY_PAIR_GEN     0x0000000AUL
-#define CKM_RSA_X9_31                  0x0000000BUL
-#define CKM_SHA1_RSA_X9_31             0x0000000CUL
-#define CKM_RSA_PKCS_PSS               0x0000000DUL
-#define CKM_SHA1_RSA_PKCS_PSS          0x0000000EUL
+#define CKM_RSA_X9_31_KEY_PAIR_GEN     0x0000000aUL
+#define CKM_RSA_X9_31                  0x0000000bUL
+#define CKM_SHA1_RSA_X9_31             0x0000000cUL
+#define CKM_RSA_PKCS_PSS               0x0000000dUL
+#define CKM_SHA1_RSA_PKCS_PSS          0x0000000eUL
 
 #define CKM_DSA_KEY_PAIR_GEN           0x00000010UL
 #define CKM_DSA                        0x00000011UL
@@ -665,8 +677,8 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_DSA_SHA512                 0x00000016UL
 #define CKM_DSA_SHA3_224               0x00000018UL
 #define CKM_DSA_SHA3_256               0x00000019UL
-#define CKM_DSA_SHA3_384               0x0000001AUL
-#define CKM_DSA_SHA3_512               0x0000001BUL
+#define CKM_DSA_SHA3_384               0x0000001aUL
+#define CKM_DSA_SHA3_512               0x0000001bUL
 
 #define CKM_DH_PKCS_KEY_PAIR_GEN       0x00000020UL
 #define CKM_DH_PKCS_DERIVE             0x00000021UL
@@ -688,12 +700,12 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 
 #define CKM_SHA512_224                 0x00000048UL
 #define CKM_SHA512_224_HMAC            0x00000049UL
-#define CKM_SHA512_224_HMAC_GENERAL    0x0000004AUL
-#define CKM_SHA512_224_KEY_DERIVATION  0x0000004BUL
-#define CKM_SHA512_256                 0x0000004CUL
-#define CKM_SHA512_256_HMAC            0x0000004DUL
-#define CKM_SHA512_256_HMAC_GENERAL    0x0000004EUL
-#define CKM_SHA512_256_KEY_DERIVATION  0x0000004FUL
+#define CKM_SHA512_224_HMAC_GENERAL    0x0000004aUL
+#define CKM_SHA512_224_KEY_DERIVATION  0x0000004bUL
+#define CKM_SHA512_256                 0x0000004cUL
+#define CKM_SHA512_256_HMAC            0x0000004dUL
+#define CKM_SHA512_256_HMAC_GENERAL    0x0000004eUL
+#define CKM_SHA512_256_KEY_DERIVATION  0x0000004fUL
 
 #define CKM_SHA512_T                   0x00000050UL
 #define CKM_SHA512_T_HMAC              0x00000051UL
@@ -787,25 +799,25 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_SECURID                    0x00000282UL
 #define CKM_HOTP_KEY_GEN               0x00000290UL
 #define CKM_HOTP                       0x00000291UL
-#define CKM_ACTI                       0x000002A0UL
-#define CKM_ACTI_KEY_GEN               0x000002A1UL
-
-#define CKM_SHA3_256                   0x000002B0UL
-#define CKM_SHA3_256_HMAC              0x000002B1UL
-#define CKM_SHA3_256_HMAC_GENERAL      0x000002B2UL
-#define CKM_SHA3_256_KEY_GEN           0x000002B3UL
-#define CKM_SHA3_224                   0x000002B5UL
-#define CKM_SHA3_224_HMAC              0x000002B6UL
-#define CKM_SHA3_224_HMAC_GENERAL      0x000002B7UL
-#define CKM_SHA3_224_KEY_GEN           0x000002B8UL
-#define CKM_SHA3_384                   0x000002C0UL
-#define CKM_SHA3_384_HMAC              0x000002C1UL
-#define CKM_SHA3_384_HMAC_GENERAL      0x000002C2UL
-#define CKM_SHA3_384_KEY_GEN           0x000002C3UL
-#define CKM_SHA3_512                   0x000002D0UL
-#define CKM_SHA3_512_HMAC              0x000002D1UL
-#define CKM_SHA3_512_HMAC_GENERAL      0x000002D2UL
-#define CKM_SHA3_512_KEY_GEN           0x000002D3UL
+#define CKM_ACTI                       0x000002a0UL
+#define CKM_ACTI_KEY_GEN               0x000002a1UL
+
+#define CKM_SHA3_256                   0x000002b0UL
+#define CKM_SHA3_256_HMAC              0x000002b1UL
+#define CKM_SHA3_256_HMAC_GENERAL      0x000002b2UL
+#define CKM_SHA3_256_KEY_GEN           0x000002b3UL
+#define CKM_SHA3_224                   0x000002b5UL
+#define CKM_SHA3_224_HMAC              0x000002b6UL
+#define CKM_SHA3_224_HMAC_GENERAL      0x000002b7UL
+#define CKM_SHA3_224_KEY_GEN           0x000002b8UL
+#define CKM_SHA3_384                   0x000002c0UL
+#define CKM_SHA3_384_HMAC              0x000002c1UL
+#define CKM_SHA3_384_HMAC_GENERAL      0x000002c2UL
+#define CKM_SHA3_384_KEY_GEN           0x000002c3UL
+#define CKM_SHA3_512                   0x000002d0UL
+#define CKM_SHA3_512_HMAC              0x000002d1UL
+#define CKM_SHA3_512_HMAC_GENERAL      0x000002d2UL
+#define CKM_SHA3_512_KEY_GEN           0x000002d3UL
 
 
 #define CKM_CAST_KEY_GEN               0x00000300UL
@@ -876,9 +888,9 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_SHA3_256_KEY_DERIVATION    0x00000397UL
 #define CKM_SHA3_224_KEY_DERIVATION    0x00000398UL
 #define CKM_SHA3_384_KEY_DERIVATION    0x00000399UL
-#define CKM_SHA3_512_KEY_DERIVATION    0x0000039AUL
-#define CKM_SHAKE_128_KEY_DERIVATION   0x0000039BUL
-#define CKM_SHAKE_256_KEY_DERIVATION   0x0000039CUL
+#define CKM_SHA3_512_KEY_DERIVATION    0x0000039aUL
+#define CKM_SHAKE_128_KEY_DERIVATION   0x0000039bUL
+#define CKM_SHAKE_256_KEY_DERIVATION   0x0000039cUL
 #define CKM_SHA3_256_KEY_DERIVE  CKM_SHA3_256_KEY_DERIVATION
 #define CKM_SHA3_224_KEY_DERIVE  CKM_SHA3_224_KEY_DERIVATION
 #define CKM_SHA3_384_KEY_DERIVE  CKM_SHA3_384_KEY_DERIVATION
@@ -886,40 +898,42 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_SHAKE_128_KEY_DERIVE CKM_SHAKE_128_KEY_DERIVATION
 #define CKM_SHAKE_256_KEY_DERIVE CKM_SHAKE_256_KEY_DERIVATION
 
-#define CKM_PBE_MD2_DES_CBC            0x000003A0UL
-#define CKM_PBE_MD5_DES_CBC            0x000003A1UL
-#define CKM_PBE_MD5_CAST_CBC           0x000003A2UL
-#define CKM_PBE_MD5_CAST3_CBC          0x000003A3UL
-#define CKM_PBE_MD5_CAST5_CBC          0x000003A4UL /* Deprecated */
-#define CKM_PBE_MD5_CAST128_CBC        0x000003A4UL
-#define CKM_PBE_SHA1_CAST5_CBC         0x000003A5UL /* Deprecated */
-#define CKM_PBE_SHA1_CAST128_CBC       0x000003A5UL
-#define CKM_PBE_SHA1_RC4_128           0x000003A6UL
-#define CKM_PBE_SHA1_RC4_40            0x000003A7UL
-#define CKM_PBE_SHA1_DES3_EDE_CBC      0x000003A8UL
-#define CKM_PBE_SHA1_DES2_EDE_CBC      0x000003A9UL
-#define CKM_PBE_SHA1_RC2_128_CBC       0x000003AAUL
-#define CKM_PBE_SHA1_RC2_40_CBC        0x000003ABUL
-
-#define CKM_PKCS5_PBKD2                0x000003B0UL
-
-#define CKM_PBA_SHA1_WITH_SHA1_HMAC    0x000003C0UL
-
-#define CKM_WTLS_PRE_MASTER_KEY_GEN         0x000003D0UL
-#define CKM_WTLS_MASTER_KEY_DERIVE          0x000003D1UL
-#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC   0x000003D2UL
-#define CKM_WTLS_PRF                        0x000003D3UL
-#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  0x000003D4UL
-#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  0x000003D5UL
-
-#define CKM_TLS12_MAC                       0x000003D8UL
-#define CKM_TLS12_KDF                       0x000003D9UL
-#define CKM_TLS12_MASTER_KEY_DERIVE         0x000003E0UL
-#define CKM_TLS12_KEY_AND_MAC_DERIVE        0x000003E1UL
-#define CKM_TLS12_MASTER_KEY_DERIVE_DH      0x000003E2UL
-#define CKM_TLS12_KEY_SAFE_DERIVE           0x000003E3UL
-#define CKM_TLS_MAC                         0x000003E4UL
-#define CKM_TLS_KDF                         0x000003E5UL
+#define CKM_PBE_MD2_DES_CBC            0x000003a0UL
+#define CKM_PBE_MD5_DES_CBC            0x000003a1UL
+#define CKM_PBE_MD5_CAST_CBC           0x000003a2UL
+#define CKM_PBE_MD5_CAST3_CBC          0x000003a3UL
+#define CKM_PBE_MD5_CAST5_CBC          0x000003a4UL /* Deprecated */
+#define CKM_PBE_MD5_CAST128_CBC        0x000003a4UL
+#define CKM_PBE_SHA1_CAST5_CBC         0x000003a5UL /* Deprecated */
+#define CKM_PBE_SHA1_CAST128_CBC       0x000003a5UL
+#define CKM_PBE_SHA1_RC4_128           0x000003a6UL
+#define CKM_PBE_SHA1_RC4_40            0x000003a7UL
+#define CKM_PBE_SHA1_DES3_EDE_CBC      0x000003a8UL
+#define CKM_PBE_SHA1_DES2_EDE_CBC      0x000003a9UL
+#define CKM_PBE_SHA1_RC2_128_CBC       0x000003aaUL
+#define CKM_PBE_SHA1_RC2_40_CBC        0x000003abUL
+
+#define CKM_PKCS5_PBKD2                0x000003b0UL
+
+#define CKM_PBA_SHA1_WITH_SHA1_HMAC    0x000003c0UL
+
+#define CKM_WTLS_PRE_MASTER_KEY_GEN         0x000003d0UL
+#define CKM_WTLS_MASTER_KEY_DERIVE          0x000003d1UL
+#define CKM_WTLS_MASTER_KEY_DERIVE_DH_ECC   0x000003d2UL
+#define CKM_WTLS_PRF                        0x000003d3UL
+#define CKM_WTLS_SERVER_KEY_AND_MAC_DERIVE  0x000003d4UL
+#define CKM_WTLS_CLIENT_KEY_AND_MAC_DERIVE  0x000003d5UL
+
+#define CKM_TLS10_MAC_SERVER                0x000003d6UL
+#define CKM_TLS10_MAC_CLIENT                0x000003d7UL
+#define CKM_TLS12_MAC                       0x000003d8UL
+#define CKM_TLS12_KDF                       0x000003d9UL
+#define CKM_TLS12_MASTER_KEY_DERIVE         0x000003e0UL
+#define CKM_TLS12_KEY_AND_MAC_DERIVE        0x000003e1UL
+#define CKM_TLS12_MASTER_KEY_DERIVE_DH      0x000003e2UL
+#define CKM_TLS12_KEY_SAFE_DERIVE           0x000003e3UL
+#define CKM_TLS_MAC                         0x000003e4UL
+#define CKM_TLS_KDF                         0x000003e5UL
 
 #define CKM_KEY_WRAP_LYNKS             0x00000400UL
 #define CKM_KEY_WRAP_SET_OAEP          0x00000401UL
@@ -989,7 +1003,7 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_ECDSA_SHA256               0x00001044UL
 #define CKM_ECDSA_SHA384               0x00001045UL
 #define CKM_ECDSA_SHA512               0x00001046UL
-#define CKM_EC_KEY_PAIR_GEN_W_EXTRA_BITS 0x0000140BUL
+#define CKM_EC_KEY_PAIR_GEN_W_EXTRA_BITS 0x0000140bUL
 
 #define CKM_ECDH1_DERIVE               0x00001050UL
 #define CKM_ECDH1_COFACTOR_DERIVE      0x00001051UL
@@ -1018,12 +1032,12 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_AES_GCM                    0x00001087UL
 #define CKM_AES_CCM                    0x00001088UL
 #define CKM_AES_CTS                    0x00001089UL
-#define CKM_AES_CMAC                   0x0000108AUL
-#define CKM_AES_CMAC_GENERAL           0x0000108BUL
+#define CKM_AES_CMAC                   0x0000108aUL
+#define CKM_AES_CMAC_GENERAL           0x0000108bUL
 
-#define CKM_AES_XCBC_MAC               0x0000108CUL
-#define CKM_AES_XCBC_MAC_96            0x0000108DUL
-#define CKM_AES_GMAC                   0x0000108EUL
+#define CKM_AES_XCBC_MAC               0x0000108cUL
+#define CKM_AES_XCBC_MAC_96            0x0000108dUL
+#define CKM_AES_GMAC                   0x0000108eUL
 
 #define CKM_BLOWFISH_KEY_GEN           0x00001090UL
 #define CKM_BLOWFISH_CBC               0x00001091UL
@@ -1072,6 +1086,7 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_AES_KEY_WRAP               0x00002109UL     /* WAS: 0x00001090 */
 #define CKM_AES_KEY_WRAP_PAD           0x0000210AUL     /* WAS: 0x00001091 */
 #define CKM_AES_KEY_WRAP_KWP           0x0000210BUL
+#define CKM_AES_KEY_WRAP_PKCS7         0x0000210CUL
 
 #define CKM_RSA_PKCS_TPM_1_1           0x00004001UL
 #define CKM_RSA_PKCS_OAEP_TPM_1_1      0x00004002UL
@@ -1131,6 +1146,14 @@ typedef CK_ULONG          CK_MECHANISM_TYPE;
 #define CKM_SP800_108_FEEDBACK_KDF     0x000003adUL
 #define CKM_SP800_108_DOUBLE_PIPELINE_KDF 0x000003aeUL
 
+#define CKM_IKE2_PRF_PLUS_DERIVE       0x0000402eUL
+#define CKM_IKE_PRF_DERIVE             0x0000402fUL
+#define CKM_IKE1_PRF_DERIVE            0x00004030UL
+#define CKM_IKE1_EXTENDED_DERIVE       0x00004031UL
+#define CKM_HSS_KEY_PAIR_GEN           0x00004032UL
+#define CKM_HSS                        0x00004033UL
+
+
 #define CKM_VENDOR_DEFINED             0x80000000UL
 
 typedef CK_MECHANISM_TYPE CK_PTR CK_MECHANISM_TYPE_PTR;
@@ -1326,6 +1349,7 @@ typedef CK_ULONG          CK_RV;
 #define CKR_FUNCTION_REJECTED                 0x00000200UL
 #define CKR_TOKEN_RESOURCE_EXCEEDED           0x00000201UL
 #define CKR_OPERATION_CANCEL_FAILED           0x00000202UL
+#define CKR_KEY_EXHAUSTED                     0x00000203UL
 
 #define CKR_VENDOR_DEFINED                    0x80000000UL
 
@@ -1442,6 +1466,7 @@ typedef CK_RSA_PKCS_MGF_TYPE CK_PTR CK_RSA_PKCS_MGF_TYPE_PTR;
 #define CKG_MGF1_SHA3_384     0x00000008UL
 #define CKG_MGF1_SHA3_512     0x00000009UL
 
+
 /* CK_RSA_PKCS_OAEP_SOURCE_TYPE  is used to indicate the source
  * of the encoding parameter when formatting a message block
  * for the PKCS #1 OAEP encryption scheme.
@@ -1707,8 +1732,7 @@ typedef struct CK_DES_CBC_ENCRYPT_DATA_PARAMS {
     CK_ULONG    length;
 } CK_DES_CBC_ENCRYPT_DATA_PARAMS;
 
-typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR \
-        CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+typedef CK_DES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_DES_CBC_ENCRYPT_DATA_PARAMS_PTR;
 
 typedef struct CK_AES_CBC_ENCRYPT_DATA_PARAMS {
     CK_BYTE     iv[16];
@@ -1716,8 +1740,7 @@ typedef struct CK_AES_CBC_ENCRYPT_DATA_PARAMS {
     CK_ULONG    length;
 } CK_AES_CBC_ENCRYPT_DATA_PARAMS;
 
-typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR \
-        CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR;
+typedef CK_AES_CBC_ENCRYPT_DATA_PARAMS CK_PTR CK_AES_CBC_ENCRYPT_DATA_PARAMS_PTR;
 
 /* CK_SKIPJACK_PRIVATE_WRAP_PARAMS provides the parameters to the
  * CKM_SKIPJACK_PRIVATE_WRAP mechanism
@@ -2057,6 +2080,7 @@ typedef CK_ULONG CK_GENERATOR_FUNCTION;
 #define CKG_GENERATE         0x00000001UL
 #define CKG_GENERATE_COUNTER 0x00000002UL
 #define CKG_GENERATE_RANDOM  0x00000003UL
+#define CKG_GENERATE_COUNTER_XOR 0x00000004UL
 
 typedef struct CK_GCM_MESSAGE_PARAMS {
     CK_BYTE_PTR           pIv;
@@ -2067,7 +2091,7 @@ typedef struct CK_GCM_MESSAGE_PARAMS {
     CK_ULONG              ulTagBits;
 } CK_GCM_MESSAGE_PARAMS;
 
-typedef CK_GCM_MESSAGE_PARAMS CK_GCM_MESSAGE_PARAMS_PTR;
+typedef CK_GCM_MESSAGE_PARAMS CK_PTR CK_GCM_MESSAGE_PARAMS_PTR;
 
 typedef struct CK_CCM_PARAMS {
     CK_ULONG    ulDataLen;
@@ -2090,7 +2114,7 @@ typedef struct CK_CCM_MESSAGE_PARAMS {
     CK_ULONG              ulMACLen;
 } CK_CCM_MESSAGE_PARAMS;
 
-typedef CK_CCM_MESSAGE_PARAMS CK_CCM_MESSAGE_PARAMS_PTR;
+typedef CK_CCM_MESSAGE_PARAMS CK_PTR CK_CCM_MESSAGE_PARAMS_PTR;
 
 /* Deprecated. Use CK_GCM_PARAMS */
 typedef struct CK_AES_GCM_PARAMS {
@@ -2355,7 +2379,6 @@ typedef struct CK_SALSA20_PARAMS {
     CK_BYTE_PTR pNonce;
     CK_ULONG    ulNonceBits;
 } CK_SALSA20_PARAMS;
-
 typedef CK_SALSA20_PARAMS CK_PTR CK_SALSA20_PARAMS_PTR;
 
 typedef struct CK_SALSA20_CHACHA20_POLY1305_PARAMS {
@@ -2439,6 +2462,7 @@ typedef struct CK_XEDDSA_PARAMS {
 } CK_XEDDSA_PARAMS;
 typedef CK_XEDDSA_PARAMS CK_PTR CK_XEDDSA_PARAMS_PTR;
 
+/* HKDF params */
 typedef struct CK_HKDF_PARAMS {
     CK_BBOOL          bExtract;
     CK_BBOOL          bExpand;
@@ -2456,5 +2480,60 @@ typedef CK_HKDF_PARAMS CK_PTR CK_HKDF_PARAMS_PTR;
 #define CKF_HKDF_SALT_DATA   0x00000002UL
 #define CKF_HKDF_SALT_KEY    0x00000004UL
 
+/* HSS */
+typedef CK_ULONG                   CK_HSS_LEVELS;
+typedef CK_ULONG                   CK_LMS_TYPE;
+typedef CK_ULONG                   CK_LMOTS_TYPE;
+
+typedef struct specifiedParams {
+    CK_HSS_LEVELS levels;
+    CK_LMS_TYPE   lm_type[8];
+    CK_LMOTS_TYPE lm_ots_type[8];
+} specifiedParams;
+
+/* IKE Params */
+typedef struct CK_IKE2_PRF_PLUS_DERIVE_PARAMS {
+    CK_MECHANISM_TYPE prfMechanism;
+    CK_BBOOL          bHasSeedKey;
+    CK_OBJECT_HANDLE  hSeedKey;
+    CK_BYTE_PTR       pSeedData;
+    CK_ULONG          ulSeedDataLen;
+} CK_IKE2_PRF_PLUS_DERIVE_PARAMS;
+typedef CK_IKE2_PRF_PLUS_DERIVE_PARAMS CK_PTR CK_IKE2_PRF_PLUS_DERIVE_PARAMS_PTR;
+
+typedef struct CK_IKE_PRF_DERIVE_PARAMS {
+    CK_MECHANISM_TYPE prfMechanism;
+    CK_BBOOL          bDataAsKey;
+    CK_BBOOL          bRekey;
+    CK_BYTE_PTR       pNi;
+    CK_ULONG          ulNiLen;
+    CK_BYTE_PTR       pNr;
+    CK_ULONG          ulNrLen;
+    CK_OBJECT_HANDLE  hNewKey;
+} CK_IKE_PRF_DERIVE_PARAMS;
+typedef CK_IKE_PRF_DERIVE_PARAMS CK_PTR CK_IKE_PRF_DERIVE_PARAMS_PTR;
+
+typedef struct CK_IKE1_PRF_DERIVE_PARAMS {
+    CK_MECHANISM_TYPE prfMechanism;
+    CK_BBOOL          bHasPrevKey;
+    CK_OBJECT_HANDLE  hKeygxy;
+    CK_OBJECT_HANDLE  hPrevKey;
+    CK_BYTE_PTR       pCKYi;
+    CK_ULONG          ulCKYiLen;
+    CK_BYTE_PTR       pCKYr;
+    CK_ULONG          ulCKYrLen;
+    CK_BYTE           keyNumber;
+} CK_IKE1_PRF_DERIVE_PARAMS;
+typedef CK_IKE1_PRF_DERIVE_PARAMS CK_PTR CK_IKE1_PRF_DERIVE_PARAMS_PTR;
+
+typedef struct CK_IKE1_EXTENDED_DERIVE_PARAMS {
+    CK_MECHANISM_TYPE prfMechanism;
+    CK_BBOOL          bHasKeygxy;
+    CK_OBJECT_HANDLE  hKeygxy;
+    CK_BYTE_PTR       pExtraData;
+    CK_ULONG          ulExtraDataLen;
+} CK_IKE1_EXTENDED_DERIVE_PARAMS;
+typedef CK_IKE1_EXTENDED_DERIVE_PARAMS CK_PTR CK_IKE1_EXTENDED_DERIVE_PARAMS_PTR;
+
 #endif /* _PKCS11T_H_ */
 
diff --git a/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java b/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java
index df75739188f..6957939cae4 100644
--- a/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java
+++ b/src/jdk.jartool/share/classes/sun/security/tools/jarsigner/Main.java
@@ -2151,7 +2151,7 @@ void loadKeyStore(String keyStoreName, boolean prompt) {
                     && !KeyStoreUtil.isWindowsKeyStore(storetype)) {
                 storepass = getPass
                         (rb.getString("Enter.Passphrase.for.keystore."));
-            } else if (!token && storepass == null && prompt) {
+            } else if (!token && storepass == null && prompt && !protectedPath) {
                 storepass = getPass
                         (rb.getString("Enter.Passphrase.for.keystore."));
             }
diff --git a/src/jdk.javadoc/share/man/javadoc.1 b/src/jdk.javadoc/share/man/javadoc.1
index 41f53c98482..2a7b5cfc93a 100644
--- a/src/jdk.javadoc/share/man/javadoc.1
+++ b/src/jdk.javadoc/share/man/javadoc.1
@@ -584,6 +584,12 @@ For example:
 .TP
 .B \f[CB]\-docfilessubdirs\f[R]
 Recursively copies doc\-file subdirectories.
+Enables deep copying of doc\-files directories.
+Subdirectories and all contents are recursively copied to the
+destination.
+For example, the directory \f[CB]doc\-files/example/images\f[R] and all of
+its contents are copied.
+There is also an option to exclude subdirectories.
 .RS
 .RE
 .TP
@@ -602,12 +608,7 @@ For example,
 .TP
 .B \f[CB]\-excludedocfilessubdir\f[R] \f[I]name\f[R]
 Excludes any doc files sub directories with the given name.
-Enables deep copying of doc\-files directories.
-Subdirectories and all contents are recursively copied to the
-destination.
-For example, the directory \f[CB]doc\-files/example/images\f[R] and all of
-its contents are copied.
-There is also an option to exclude subdirectories.
+See \f[B]\f[VB]-docfilessubdirs\f[B]\f[R].
 .RS
 .RE
 .TP
diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java
index 5c910a87376..8f648fe2c46 100644
--- a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java
+++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdDump.java
@@ -201,55 +201,55 @@ public String[] printHelp() {
 
                Options:
 
-                 begin           (Optional) Specify the time from which recording data will be included
-                                 in the dump file. The format is specified as local time.
-                                 (STRING, no default value)
+                 begin            (Optional) Specify the time from which recording data will be
+                                  included in the dump file. The format is specified as local time.
+                                  (STRING, no default value)
 
-                 end             (Optional) Specify the time to which recording data will be included
-                                 in the dump file. The format is specified as local time.
-                                 (STRING, no default value)
+                 end              (Optional) Specify the time to which recording data will be included
+                                  in the dump file. The format is specified as local time.
+                                  (STRING, no default value)
 
-                                 Note: For both begin and end, the time must be in a format that can
-                                 be read by any of these methods:
+                                  Note: For both begin and end, the time must be in a format that can
+                                  be read by any of these methods:
 
-                                  java.time.LocalTime::parse(String),
-                                  java.time.LocalDateTime::parse(String)
-                                  java.time.Instant::parse(String)
+                                   java.time.LocalTime::parse(String),
+                                   java.time.LocalDateTime::parse(String)
+                                   java.time.Instant::parse(String)
 
-                                 For example, "13:20:15", "2020-03-17T09:00:00" or
-                                 "2020-03-17T09:00:00Z".
+                                  For example, "13:20:15", "2020-03-17T09:00:00" or
+                                  "2020-03-17T09:00:00Z".
 
-                                 Note: begin and end times correspond to the timestamps found within
-                                 the recorded information in the flight recording data.
+                                  Note: begin and end times correspond to the timestamps found within
+                                  the recorded information in the flight recording data.
 
-                                 Another option is to use a time relative to the current time that is
-                                 specified by a negative integer followed by "s", "m" or "h".
-                                 For example, "-12h", "-15m" or "-30s"
+                                  Another option is to use a time relative to the current time that is
+                                  specified by a negative integer followed by "s", "m" or "h".
+                                  For example, "-12h", "-15m" or "-30s"
 
-                 filename        (Optional) Name of the file to which the flight recording data is
-                                 dumped. If no filename is given, a filename is generated from the PID
-                                 and the current date. The filename may also be a directory in which
-                                 case, the filename is generated from the PID and the current date in
-                                 the specified directory. (STRING, no default value)
+                 filename         (Optional) Name of the file to which the flight recording data is
+                                  dumped. If no filename is given, a filename is generated from the PID
+                                  and the current date. The filename may also be a directory in which
+                                  case, the filename is generated from the PID and the current date in
+                                  the specified directory. (STRING, no default value)
 
-                 maxage          (Optional) Length of time for dumping the flight recording data to a
-                                 file. (INTEGER followed by 's' for seconds 'm' for minutes or 'h' for
-                                 hours, no default value)
+                 maxage           (Optional) Length of time for dumping the flight recording data to a
+                                  file. (INTEGER followed by 's' for seconds 'm' for minutes or 'h' for
+                                  hours, no default value)
 
-                 maxsize         (Optional) Maximum size for the amount of data to dump from a flight
-                                 recording in bytes if one of the following suffixes is not used:
-                                 'm' or 'M' for megabytes OR 'g' or 'G' for gigabytes.
-                                 (STRING, no default value)
+                 maxsize          (Optional) Maximum size for the amount of data to dump from a flight
+                                  recording in bytes if one of the following suffixes is not used:
+                                  'm' or 'M' for megabytes OR 'g' or 'G' for gigabytes.
+                                  (STRING, no default value)
 
-                 name            (Optional) Name of the recording. If no name is given, data from all
-                                 recordings is dumped. (STRING, no default value)
+                 name             (Optional) Name of the recording. If no name is given, data from all
+                                  recordings is dumped. (STRING, no default value)
 
-                 path-to-gc-root (Optional) Flag for saving the path to garbage collection (GC) roots
-                                 at the time the recording data is dumped. The path information is
-                                 useful for finding memory leaks but collecting it can cause the
-                                 application to pause for a short period of time. Turn on this flag
-                                 only when you have an application that you suspect has a memory
-                                 leak. (BOOLEAN, false)
+                 path-to-gc-roots (Optional) Flag for saving the path to garbage collection (GC) roots
+                                  at the time the recording data is dumped. The path information is
+                                  useful for finding memory leaks but collecting it can cause the
+                                  application to pause for a short period of time. Turn on this flag
+                                  only when you have an application that you suspect has a memory
+                                  leak. (BOOLEAN, false)
 
                Options must be specified using the  or = syntax.
 
@@ -261,7 +261,7 @@ public String[] printHelp() {
                 $ jcmd  JFR.dump name=1 filename=%s
                 $ jcmd  JFR.dump maxage=1h
                 $ jcmd  JFR.dump maxage=1h maxsize=50M
-                $ jcmd  JFR.dump fillename=leaks.jfr path-to-gc-root=true
+                $ jcmd  JFR.dump filename=leaks.jfr path-to-gc-roots=true
                 $ jcmd  JFR.dump begin=13:15
                 $ jcmd  JFR.dump begin=13:15 end=21:30:00
                 $ jcmd  JFR.dump end=18:00 maxage=10m
diff --git a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java
index 56e25a3e7ea..fd5713fe114 100644
--- a/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java
+++ b/src/jdk.jfr/share/classes/jdk/jfr/internal/dcmd/DCmdStart.java
@@ -306,78 +306,78 @@ private boolean hasJDKEvents(Map settings) {
 
     @Override
     public String[] printHelp() {
-        // 0123456789001234567890012345678900123456789001234567890012345678900123456789001234567890
+            // 0123456789001234567890012345678900123456789001234567890012345678900123456789001234567890
         return """
                Syntax : JFR.start [options]
 
                Options:
 
-                 delay           (Optional) Length of time to wait before starting to record
-                                 (INTEGER followed by 's' for seconds 'm' for minutes or h' for
-                                 hours, 0s)
-
-                 disk            (Optional) Flag for also writing the data to disk while recording
-                                 (BOOLEAN, true)
-
-                 dumponexit      (Optional) Flag for writing the recording to disk when the Java
-                                 Virtual Machine (JVM) shuts down. If set to 'true' and no value
-                                 is given for filename, the recording is written to a file in the
-                                 directory where the process was started. The file name is a
-                                 system-generated name that contains the process ID, the recording
-                                 ID and the current time stamp. (For example:
-                                 id-1-2021_09_14_09_00.jfr) (BOOLEAN, false)
-
-                 duration        (Optional) Length of time to record. Note that 0s means forever
-                                 (INTEGER followed by 's' for seconds 'm' for minutes or 'h' for
-                                 hours, 0s)
-
-                 filename        (Optional) Name of the file to which the flight recording data is
-                                 written when the recording is stopped. If no filename is given, a
-                                 filename is generated from the PID and the current date and is
-                                 placed in the directory where the process was started. The
-                                 filename may also be a directory in which case, the filename is
-                                 generated from the PID and the current date in the specified
-                                 directory. (STRING, no default value)
-
-                 maxage          (Optional) Maximum time to keep the recorded data on disk. This
-                                 parameter is valid only when the disk parameter is set to true.
-                                 Note 0s means forever. (INTEGER followed by 's' for seconds 'm'
-                                 for minutes or 'h' for hours, 0s)
-
-                 maxsize         (Optional) Maximum size of the data to keep on disk in bytes if
-                                 one of the following suffixes is not used: 'm' or 'M' for
-                                 megabytes OR 'g' or 'G' for gigabytes. This parameter is valid
-                                 only when the disk parameter is set to 'true'. The value must not
-                                 be less than the value for the maxchunksize parameter set with
-                                 the JFR.configure command. (STRING, 0 (no max size))
-
-                 name            (Optional) Name of the recording. If no name is provided, a name
-                                 is generated. Make note of the generated name that is shown in
-                                 the response to the command so that you can use it with other
-                                 commands. (STRING, system-generated default name)
-
-                 path-to-gc-root (Optional) Flag for saving the path to garbage collection (GC)
-                                 roots at the end of a recording. The path information is useful
-                                 for finding memory leaks but collecting it is time consuming.
-                                 Turn on this flag only when you have an application that you
-                                 suspect has a memory leak. If the settings parameter is set to
-                                 'profile', then the information collected includes the stack
-                                 trace from where the potential leaking object wasallocated.
-                                 (BOOLEAN, false)
-
-                 settings        (Optional) Name of the settings file that identifies which events
-                                 to record. To specify more than one file, use the settings
-                                 parameter repeatedly. Include the path if the file is not in
-                                 JAVA-HOME/lib/jfr. The following profiles are included with the
-                                 JDK in the JAVA-HOME/lib/jfr directory: 'default.jfc': collects a
-                                 predefined set of information with low overhead, so it has minimal
-                                 impact on performance and can be used with recordings that run
-                                 continuously; 'profile.jfc': Provides more data than the
-                                 'default.jfc' profile, but with more overhead and impact on
-                                 performance. Use this configuration for short periods of time
-                                 when more information is needed. Use none to start a recording
-                                 without a predefined configuration file. (STRING,
-                                 JAVA-HOME/lib/jfr/default.jfc)
+                 delay            (Optional) Length of time to wait before starting to record
+                                  (INTEGER followed by 's' for seconds 'm' for minutes or h' for
+                                  hours, 0s)
+
+                 disk             (Optional) Flag for also writing the data to disk while recording
+                                  (BOOLEAN, true)
+
+                 dumponexit       (Optional) Flag for writing the recording to disk when the Java
+                                  Virtual Machine (JVM) shuts down. If set to 'true' and no value
+                                  is given for filename, the recording is written to a file in the
+                                  directory where the process was started. The file name is a
+                                  system-generated name that contains the process ID, the recording
+                                  ID and the current time stamp. (For example:
+                                  id-1-2021_09_14_09_00.jfr) (BOOLEAN, false)
+
+                 duration         (Optional) Length of time to record. Note that 0s means forever
+                                  (INTEGER followed by 's' for seconds 'm' for minutes or 'h' for
+                                  hours, 0s)
+
+                 filename         (Optional) Name of the file to which the flight recording data is
+                                  written when the recording is stopped. If no filename is given, a
+                                  filename is generated from the PID and the current date and is
+                                  placed in the directory where the process was started. The
+                                  filename may also be a directory in which case, the filename is
+                                  generated from the PID and the current date in the specified
+                                  directory. (STRING, no default value)
+
+                 maxage           (Optional) Maximum time to keep the recorded data on disk. This
+                                  parameter is valid only when the disk parameter is set to true.
+                                  Note 0s means forever. (INTEGER followed by 's' for seconds 'm'
+                                  for minutes or 'h' for hours, 0s)
+
+                 maxsize          (Optional) Maximum size of the data to keep on disk in bytes if
+                                  one of the following suffixes is not used: 'm' or 'M' for
+                                  megabytes OR 'g' or 'G' for gigabytes. This parameter is valid
+                                  only when the disk parameter is set to 'true'. The value must not
+                                  be less than the value for the maxchunksize parameter set with
+                                  the JFR.configure command. (STRING, 0 (no max size))
+
+                 name             (Optional) Name of the recording. If no name is provided, a name
+                                  is generated. Make note of the generated name that is shown in
+                                  the response to the command so that you can use it with other
+                                  commands. (STRING, system-generated default name)
+
+                 path-to-gc-roots (Optional) Flag for saving the path to garbage collection (GC)
+                                  roots at the end of a recording. The path information is useful
+                                  for finding memory leaks but collecting it is time consuming.
+                                  Turn on this flag only when you have an application that you
+                                  suspect has a memory leak. If the settings parameter is set to
+                                  'profile', then the information collected includes the stack
+                                  trace from where the potential leaking object was allocated.
+                                  (BOOLEAN, false)
+
+                 settings         (Optional) Name of the settings file that identifies which events
+                                  to record. To specify more than one file, use the settings
+                                  parameter repeatedly. Include the path if the file is not in
+                                  JAVA-HOME/lib/jfr. The following profiles are included with the
+                                  JDK in the JAVA-HOME/lib/jfr directory: 'default.jfc': collects a
+                                  predefined set of information with low overhead, so it has minimal
+                                  impact on performance and can be used with recordings that run
+                                  continuously; 'profile.jfc': Provides more data than the
+                                  'default.jfc' profile, but with more overhead and impact on
+                                  performance. Use this configuration for short periods of time
+                                  when more information is needed. Use none to start a recording
+                                  without a predefined configuration file. (STRING,
+                                  JAVA-HOME/lib/jfr/default.jfc)
 
                Event settings and .jfc options can also be specified using the following syntax:
 
diff --git a/src/jdk.jpackage/share/native/common/Log.cpp b/src/jdk.jpackage/share/native/common/Log.cpp
index 66154ee8247..8227bb1cce4 100644
--- a/src/jdk.jpackage/share/native/common/Log.cpp
+++ b/src/jdk.jpackage/share/native/common/Log.cpp
@@ -40,10 +40,6 @@ namespace {
     // variables are initialized if any. This will result in AV. To avoid such
     // use cases keep logging module free from static variables that require
     // initialization with functions called by CRT.
-    //
-
-    // by default log everything
-    const Logger::LogLevel defaultLogLevel = Logger::LOG_TRACE;
 
     char defaultLogAppenderMemory[sizeof(StreamLogAppender)] = {};
 
diff --git a/test/failure_handler/Makefile b/test/failure_handler/Makefile
index 9c7489685b5..ec0361abdd1 100644
--- a/test/failure_handler/Makefile
+++ b/test/failure_handler/Makefile
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -38,7 +38,7 @@ SOURCES := ${SRC_DIR}/jdk/test/failurehandler/*.java                   \
 
 CONF_DIR = src/share/conf
 
-JAVA_RELEASE = 7
+JAVA_RELEASE = 15
 
 TARGET_JAR = ${IMAGE_DIR}/lib/jtregFailureHandler.jar
 
@@ -107,4 +107,3 @@ build: classes
 
 .PHONY: all build classes test require_env clean
 .DEFAULT: all
-
diff --git a/test/failure_handler/README b/test/failure_handler/README
index 8929cc21667..a03136ae3aa 100644
--- a/test/failure_handler/README
+++ b/test/failure_handler/README
@@ -1,4 +1,4 @@
-Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 
 This code is free software; you can redistribute it and/or modify it
@@ -32,7 +32,7 @@ The library uses JTHarness Observer and jtreg TimeoutHandler extensions points.
 
 DEPENDENCES
 
-The library requires jtreg 4b13+ and JDK 7+.
+The library requires jtreg 4b13+ and JDK 15+.
 
 BUILDING
 
@@ -102,4 +102,3 @@ $ ${JTREG_HOME}/bin/jtreg -jdk:${JAVA_HOME}                                   \
  -timeoutHandler:jdk.test.failurehandler.jtreg.GatherProcessInfoTimeoutHandler\
  -observer:jdk.test.failurehandler.jtreg.GatherDiagnosticInfoObserver         \
  ${WS}/hotspot/test/
-
diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/CoreInfoGatherer.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/CoreInfoGatherer.java
new file mode 100644
index 00000000000..7d0e28b9930
--- /dev/null
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/CoreInfoGatherer.java
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2021, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.test.failurehandler;
+
+import java.nio.file.Path;
+
+public interface CoreInfoGatherer {
+    void gatherCoreInfo(HtmlSection section, Path core);
+}
diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java
index 9b04d0d66a1..15a63cfae2c 100644
--- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/GathererFactory.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,6 +51,10 @@ public ProcessInfoGatherer getProcessInfoGatherer() {
         return create();
     }
 
+    public CoreInfoGatherer getCoreInfoGatherer() {
+        return create();
+    }
+
     private ToolKit create() {
         Properties osProperty = Utils.getProperties(osName);
         try {
diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java
index 58c55b0625e..f1e926f4e0b 100644
--- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/ToolKit.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,19 +26,25 @@
 import jdk.test.failurehandler.action.ActionSet;
 import jdk.test.failurehandler.action.ActionHelper;
 
+import java.io.IOException;
 import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.LinkedList;
 import java.util.List;
 import java.util.Queue;
 import java.util.Deque;
+import java.util.zip.GZIPInputStream;
 
-public class ToolKit implements EnvironmentInfoGatherer, ProcessInfoGatherer {
+public class ToolKit implements EnvironmentInfoGatherer, ProcessInfoGatherer, CoreInfoGatherer {
     private final List actions = new ArrayList<>();
     private final ActionHelper helper;
+    private final PrintWriter log;
 
     public ToolKit(ActionHelper helper, PrintWriter log, String... names) {
         this.helper = helper;
+        this.log = log;
         for (String name : names) {
             actions.add(new ActionSet(helper, log, name));
         }
@@ -51,6 +57,27 @@ public void gatherEnvironmentInfo(HtmlSection section) {
         }
     }
 
+    @Override
+    public void gatherCoreInfo(HtmlSection section, Path core) {
+        if (core.getFileName().toString().endsWith(".gz")) {
+            Path unpackedCore = Path.of(core.toString().replace(".gz", ""));
+            try (GZIPInputStream gzis = new GZIPInputStream(Files.newInputStream(core))) {
+                Files.copy(gzis, unpackedCore);
+                for (ActionSet set : actions) {
+                    set.gatherCoreInfo(section, unpackedCore);
+                }
+                Files.delete(unpackedCore);
+            } catch (IOException ioe) {
+                log.printf("Unexpected exception whilc opening %s", core.getFileName().toString());
+                ioe.printStackTrace(log);
+            }
+        } else {
+            for (ActionSet set : actions) {
+                set.gatherCoreInfo(section, core);
+            }
+        }
+    }
+
     @Override
     public void gatherProcessInfo(HtmlSection section, long pid) {
         // as some of actions can kill a process, we need to get children of all
diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java
index 4cdced07dbb..92e31197795 100644
--- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionHelper.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,8 +23,6 @@
 
 package jdk.test.failurehandler.action;
 
-import com.sun.tools.attach.VirtualMachine;
-import com.sun.tools.attach.VirtualMachineDescriptor;
 import jdk.test.failurehandler.value.InvalidValueException;
 import jdk.test.failurehandler.value.Value;
 import jdk.test.failurehandler.value.ValueHandler;
@@ -134,7 +132,7 @@ public ProcessBuilder prepareProcess(PrintWriter log, String app,
                 .directory(workDir.toFile());
     }
 
-    private File findApp(String app) {
+    public File findApp(String app) {
         String name = app + executableSuffix;
         for (Path pathElem : paths) {
             File result = pathElem.resolve(name).toFile();
diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java
index 3ed5b31403d..d67611697bf 100644
--- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/ActionSet.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,19 +23,26 @@
 
 package jdk.test.failurehandler.action;
 
+import jdk.test.failurehandler.CoreInfoGatherer;
 import jdk.test.failurehandler.ProcessInfoGatherer;
 import jdk.test.failurehandler.EnvironmentInfoGatherer;
 import jdk.test.failurehandler.HtmlSection;
 import jdk.test.failurehandler.Utils;
 
+import java.io.IOException;
 import java.io.PrintWriter;
+import java.nio.file.Files;
+import java.nio.file.Path;
 import java.util.ArrayList;
 import java.util.List;
 import java.util.Properties;
+import java.util.zip.GZIPInputStream;
 
-public class ActionSet implements ProcessInfoGatherer, EnvironmentInfoGatherer {
+public class ActionSet implements ProcessInfoGatherer, EnvironmentInfoGatherer, CoreInfoGatherer {
     private static final String ENVIRONMENT_PROPERTY = "environment";
     private static final String ON_PID_PROPERTY = "onTimeout";
+    private static final String CORES_PROPERTY = "cores";
+
 
     private final ActionHelper helper;
 
@@ -46,6 +53,7 @@ public String getName() {
     private final String name;
     private final List environmentActions;
     private final List processActions;
+    private final List coreActions;
 
 
     public ActionSet(ActionHelper helper, PrintWriter log, String name) {
@@ -55,6 +63,7 @@ public ActionSet(ActionHelper helper, PrintWriter log, String name) {
         Properties p = Utils.getProperties(name);
         environmentActions = getSimpleActions(log, p, ENVIRONMENT_PROPERTY);
         processActions = getPatternActions(log, p, ON_PID_PROPERTY);
+        coreActions = getPatternActions(log, p, CORES_PROPERTY);
     }
 
     private List getSimpleActions(PrintWriter log, Properties p,
@@ -123,4 +132,11 @@ public void gatherEnvironmentInfo(HtmlSection section) {
             helper.runPatternAction(action, section);
         }
     }
+
+    @Override
+    public void gatherCoreInfo(HtmlSection section, Path core) {
+        for (PatternAction action : coreActions) {
+            helper.runPatternAction(action, section, core.toString());
+        }
+    }
 }
diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java
index 62ae9d77efa..2af3221c9f5 100644
--- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/action/PatternAction.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -59,6 +59,9 @@ public ProcessBuilder prepareProcess(HtmlSection section,
         for (int i = 0, n = args.length; i < n; ++i) {
             args[i] = args[i].replace(pattern, value) ;
         }
+        for (int i = 0, n = args.length; i < n; ++i) {
+            args[i] = args[i].replace("%java", helper.findApp("java").getAbsolutePath());
+        }
         return action.prepareProcess(section.getWriter(), helper);
     }
 
diff --git a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java
index 89577e52d05..96c5f4f2858 100644
--- a/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java
+++ b/test/failure_handler/src/share/classes/jdk/test/failurehandler/jtreg/GatherDiagnosticInfoObserver.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,10 +33,9 @@
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.PrintWriter;
+import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.util.HashMap;
-import java.util.Map;
 
 /**
  * The jtreg test execution observer, which gathers info about
@@ -45,6 +44,8 @@
 public class GatherDiagnosticInfoObserver implements Harness.Observer {
     public static final String LOG_FILENAME = "environment.log";
     public static final String ENVIRONMENT_OUTPUT = "environment.html";
+    public static final String CORES_OUTPUT = "cores.html";
+
 
     private Path compileJdk;
     private Path testJdk;
@@ -64,18 +65,19 @@ public void finishedTest(TestResult tr) {
         workDir.toFile().mkdir();
 
         String name = getClass().getName();
-        PrintWriter log;
+        PrintWriter log1;
         boolean needClose = false;
         try {
-            log = new PrintWriter(new FileWriter(
+            log1 = new PrintWriter(new FileWriter(
                     workDir.resolve(LOG_FILENAME).toFile(), true), true);
             needClose = true;
         } catch (IOException e) {
-            log = new PrintWriter(System.out);
-            log.printf("ERROR: %s cannot open log file %s", name,
+            log1 = new PrintWriter(System.out);
+            log1.printf("ERROR: %s cannot open log file %s", name,
                     LOG_FILENAME);
-            e.printStackTrace(log);
+            e.printStackTrace(log1);
         }
+        final PrintWriter log = log1;
         try {
             log.printf("%s ---%n", name);
             GathererFactory gathererFactory = new GathererFactory(
@@ -83,6 +85,11 @@ public void finishedTest(TestResult tr) {
                     testJdk, compileJdk);
             gatherEnvInfo(workDir, name, log,
                     gathererFactory.getEnvironmentInfoGatherer());
+            Files.walk(workDir)
+                    .filter(Files::isRegularFile)
+                    .filter(f -> (f.getFileName().toString().contains("core") || f.getFileName().toString().contains("mdmp")))
+                    .forEach(core -> gatherCoreInfo(workDir, name,
+                            core, log, gathererFactory.getCoreInfoGatherer()));
         } catch (Throwable e) {
             log.printf("ERROR: exception in observer %s:", name);
             e.printStackTrace(log);
@@ -96,6 +103,22 @@ public void finishedTest(TestResult tr) {
         }
     }
 
+    private void gatherCoreInfo(Path workDir, String name, Path core, PrintWriter log,
+                               CoreInfoGatherer gatherer) {
+        File output = workDir.resolve(CORES_OUTPUT).toFile();
+        try (HtmlPage html = new HtmlPage(new PrintWriter(
+                new FileWriter(output, true), true))) {
+            try (ElapsedTimePrinter timePrinter
+                         = new ElapsedTimePrinter(new Stopwatch(), name, log)) {
+                gatherer.gatherCoreInfo(html.getRootSection(), core);
+            }
+        } catch (Throwable e) {
+            log.printf("ERROR: exception in observer on getting environment "
+                    + "information %s:", name);
+            e.printStackTrace(log);
+        }
+    }
+
     private void gatherEnvInfo(Path workDir, String name, PrintWriter log,
                                EnvironmentInfoGatherer gatherer) {
         File output = workDir.resolve(ENVIRONMENT_OUTPUT).toFile();
diff --git a/test/failure_handler/src/share/conf/common.properties b/test/failure_handler/src/share/conf/common.properties
index f02fbb2daae..bf5b0bb3986 100644
--- a/test/failure_handler/src/share/conf/common.properties
+++ b/test/failure_handler/src/share/conf/common.properties
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2015, 2019, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2015, 2021, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -35,7 +35,7 @@ onTimeout=\
         jcmd.vm.symboltable jcmd.vm.uptime jcmd.vm.dynlibs \
         jcmd.vm.system_properties jcmd.vm.info \
   jcmd.gc.heap_info jcmd.gc.class_histogram jcmd.gc.finalizer_info \
-  jstack
+  jstack jhsdb.jstack
 
 jinfo.app=jinfo
 
@@ -51,6 +51,7 @@ jcmd.vm.symboltable.args=%p VM.symboltable
 jcmd.vm.uptime.args=%p VM.uptime
 jcmd.vm.dynlibs.args=%p VM.dynlibs
 jcmd.vm.system_properties.args=%p VM.system_properties
+jcmd.vm.info.args=%p VM.info
 
 jcmd.gc.class_histogram.args=%p GC.class_histogram
 jcmd.gc.finalizer_info.args=%p GC.finalizer_info
@@ -60,6 +61,15 @@ jstack.app=jstack
 jstack.args=-e -l %p
 jstack.params.repeat=6
 
+jhsdb.app=jhsdb
+jhsdb.jstack.args=jstack --mixed --pid %p
+jhsdb.jstack.params.repeat=6
+
+cores=jhsdb.jstack
+jhsdb.jstack.app=jhsdb
+# Assume that java standard laucher has been used
+jhsdb.jstack.args=jstack --mixed --core %p --exe %java
+
 ################################################################################
 # environment info to gather
 ################################################################################
diff --git a/test/failure_handler/src/share/conf/linux.properties b/test/failure_handler/src/share/conf/linux.properties
index 69ce7799d73..e5b589b3cfa 100644
--- a/test/failure_handler/src/share/conf/linux.properties
+++ b/test/failure_handler/src/share/conf/linux.properties
@@ -32,6 +32,7 @@ onTimeout=\
   native.pmap.normal native.pmap.everything \
   native.files native.locks \
   native.stack native.core
+
 ################################################################################
 native.pattern=%p
 native.javaOnly=false
@@ -55,6 +56,13 @@ native.stack.params.repeat=6
 # has to be the last command
 native.core.app=kill
 native.core.args=-ABRT %p
+
+cores=native.gdb
+native.gdb.app=gdb
+# Assume that java standard laucher has been used
+native.gdb.args=%java\0-c\0%p\0-batch\0-ex\0thread apply all backtrace
+native.gdb.args.delimiter=\0
+
 ################################################################################
 # environment info to gather
 ################################################################################
@@ -128,4 +136,3 @@ screenshot.args=-c\0\
     ' | jshell -
 screenshot.args.delimiter=\0
 ################################################################################
-
diff --git a/test/failure_handler/src/share/conf/mac.properties b/test/failure_handler/src/share/conf/mac.properties
index bc90ff81d8c..492d8116a0c 100644
--- a/test/failure_handler/src/share/conf/mac.properties
+++ b/test/failure_handler/src/share/conf/mac.properties
@@ -64,6 +64,13 @@ native.stack.args=-c\0DevToolsSecurity --status | grep -q enabled && lldb -o 'at
 # has to be the last command
 native.core.app=kill
 native.core.args=-ABRT %p
+
+cores=native.lldb
+native.lldb.app=lldb
+native.lldb.delimiter=\0
+# Assume that java standard laucher has been used
+native.lldb.args=--core\0%p\0%java\0-o\0thread backtrace all\0-o\0quit
+
 ################################################################################
 # environment info to gather
 ################################################################################
diff --git a/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp b/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp
index 7a3845e336a..875186b83d0 100644
--- a/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp
+++ b/test/hotspot/gtest/gc/shared/test_memset_with_concurrent_readers.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,6 +26,7 @@
 #include "utilities/globalDefinitions.hpp"
 
 #include "utilities/vmassert_uninstall.hpp"
+#include 
 #include 
 #include 
 #include "utilities/vmassert_reinstall.hpp"
diff --git a/test/hotspot/gtest/logging/logTestFixture.cpp b/test/hotspot/gtest/logging/logTestFixture.cpp
index bc153b76fb9..fa0344d709a 100644
--- a/test/hotspot/gtest/logging/logTestFixture.cpp
+++ b/test/hotspot/gtest/logging/logTestFixture.cpp
@@ -112,7 +112,7 @@ void LogTestFixture::clear_snapshot() {
   if (_configuration_snapshot == NULL) {
     return;
   }
-  assert(_n_snapshots > 0, "non-null array should have at least 1 element");
+  ASSERT_GT(_n_snapshots, size_t(0)) << "non-null array should have at least 1 element";
   for (size_t i = 0; i < _n_snapshots; i++) {
     os::free(_configuration_snapshot[i]);
   }
diff --git a/test/hotspot/gtest/logging/logTestUtils.inline.hpp b/test/hotspot/gtest/logging/logTestUtils.inline.hpp
index 4295c6a000f..224999987f4 100644
--- a/test/hotspot/gtest/logging/logTestUtils.inline.hpp
+++ b/test/hotspot/gtest/logging/logTestUtils.inline.hpp
@@ -57,14 +57,14 @@ static inline void delete_file(const char* filename) {
 }
 
 static inline void create_directory(const char* name) {
-  assert(!file_exists(name), "can't create directory: %s already exists", name);
+  ASSERT_FALSE(file_exists(name)) << "can't create directory: " << name << " already exists";
   bool failed;
 #ifdef _WINDOWS
   failed = !CreateDirectory(name, NULL);
 #else
   failed = mkdir(name, 0777);
 #endif
-  assert(!failed, "failed to create directory %s", name);
+  ASSERT_FALSE(failed) << "failed to create directory " << name;
 }
 
 static inline void delete_empty_directory(const char* name) {
diff --git a/test/hotspot/gtest/logging/test_logConfiguration.cpp b/test/hotspot/gtest/logging/test_logConfiguration.cpp
index 38b66488115..7ed17fa765f 100644
--- a/test/hotspot/gtest/logging/test_logConfiguration.cpp
+++ b/test/hotspot/gtest/logging/test_logConfiguration.cpp
@@ -36,6 +36,8 @@
 #include "unittest.hpp"
 #include "utilities/ostream.hpp"
 
+using testing::HasSubstr;
+
 class LogConfigurationTest : public LogTestFixture {
  protected:
   static char _all_decorators[256];
@@ -71,26 +73,26 @@ TEST_VM_F(LogConfigurationTest, describe) {
   const char* description = ss.as_string();
 
   // Verify that stdout and stderr are listed by default
-  EXPECT_PRED2(string_contains_substring, description, StdoutLog.name());
-  EXPECT_PRED2(string_contains_substring, description, StderrLog.name());
+  EXPECT_THAT(description, HasSubstr(StdoutLog.name()));
+  EXPECT_THAT(description, HasSubstr(StderrLog.name()));
 
   // Verify that each tag, level and decorator is listed
   for (size_t i = 0; i < LogTag::Count; i++) {
-    EXPECT_PRED2(string_contains_substring, description, LogTag::name(static_cast(i)));
+    EXPECT_THAT(description, HasSubstr(LogTag::name(static_cast(i))));
   }
   for (size_t i = 0; i < LogLevel::Count; i++) {
-    EXPECT_PRED2(string_contains_substring, description, LogLevel::name(static_cast(i)));
+    EXPECT_THAT(description, HasSubstr(LogLevel::name(static_cast(i))));
   }
   for (size_t i = 0; i < LogDecorators::Count; i++) {
-    EXPECT_PRED2(string_contains_substring, description, LogDecorators::name(static_cast(i)));
+    EXPECT_THAT(description, HasSubstr(LogDecorators::name(static_cast(i))));
   }
 
   // Verify that the default configuration is printed
   char expected_buf[256];
   int ret = jio_snprintf(expected_buf, sizeof(expected_buf), "=%s", LogLevel::name(LogLevel::Default));
   ASSERT_NE(-1, ret);
-  EXPECT_PRED2(string_contains_substring, description, expected_buf);
-  EXPECT_PRED2(string_contains_substring, description, "#1: stderr all=off");
+  EXPECT_THAT(description, HasSubstr(expected_buf));
+  EXPECT_THAT(description, HasSubstr("#1: stderr all=off"));
 
   // Verify default decorators are listed
   LogDecorators default_decorators;
@@ -107,7 +109,7 @@ TEST_VM_F(LogConfigurationTest, describe) {
       ASSERT_NE(-1, ret);
     }
   }
-  EXPECT_PRED2(string_contains_substring, description, expected_buf);
+  EXPECT_THAT(description, HasSubstr(expected_buf));
 
   // Add a new output and verify that it gets described after it has been added
   const char* what = "all=trace";
@@ -493,8 +495,8 @@ TEST_VM_F(LogConfigurationTest, parse_invalid_tagset) {
   bool success = LogConfiguration::parse_log_arguments("stdout", invalid_tagset, NULL, NULL, &ss);
   const char* msg = ss.as_string();
   EXPECT_TRUE(success) << "Should only cause a warning, not an error";
-  EXPECT_TRUE(string_contains_substring(msg, "No tag set matches selection:"));
-  EXPECT_TRUE(string_contains_substring(msg, invalid_tagset));
+  EXPECT_THAT(msg, HasSubstr("No tag set matches selection:"));
+  EXPECT_THAT(msg, HasSubstr(invalid_tagset));
 }
 
 TEST_VM_F(LogConfigurationTest, output_name_normalization) {
@@ -559,7 +561,7 @@ TEST_VM_F(LogConfigurationTest, suggest_similar_selection) {
 
   const char* suggestion = ss.as_string();
   SCOPED_TRACE(suggestion);
-  EXPECT_TRUE(string_contains_substring(ss.as_string(), "Did you mean any of the following?"));
+  EXPECT_THAT(suggestion, HasSubstr("Did you mean any of the following?"));
   EXPECT_TRUE(string_contains_substring(suggestion, "logging") ||
               string_contains_substring(suggestion, "start") ||
               string_contains_substring(suggestion, "exit") ||
diff --git a/test/hotspot/gtest/logging/test_logFileOutput.cpp b/test/hotspot/gtest/logging/test_logFileOutput.cpp
index eb5a848d316..7ea5f78b9e1 100644
--- a/test/hotspot/gtest/logging/test_logFileOutput.cpp
+++ b/test/hotspot/gtest/logging/test_logFileOutput.cpp
@@ -169,12 +169,26 @@ TEST_VM(LogFileOutput, invalid_file) {
   ResourceMark rm;
   stringStream ss;
 
+  // Generate sufficiently unique directory path and log spec for that path
+  ss.print("%s%s%s%d", os::get_temp_directory(), os::file_separator(), "tmplogdir", os::current_process_id());
+  char* path = ss.as_string();
+  ss.reset();
+
+  ss.print("%s%s", "file=", path);
+  char* log_spec = ss.as_string();
+  ss.reset();
+
+  ss.print("%s is not a regular file", path);
+  char* expected_output_substring = ss.as_string();
+  ss.reset();
+
   // Attempt to log to a directory (existing log not a regular file)
-  create_directory("tmplogdir");
-  LogFileOutput bad_file("file=tmplogdir");
+  create_directory(path);
+  LogFileOutput bad_file(log_spec);
   EXPECT_FALSE(bad_file.initialize("", &ss))
     << "file was initialized when there was an existing directory with the same name";
-  EXPECT_TRUE(string_contains_substring(ss.as_string(), "tmplogdir is not a regular file"))
-    << "missing expected error message, received msg: %s" << ss.as_string();
-  delete_empty_directory("tmplogdir");
+  char* logger_output = ss.as_string();
+  EXPECT_THAT(logger_output, testing::HasSubstr(expected_output_substring))
+    << "missing expected error message, received msg: %s" << logger_output;
+  delete_empty_directory(path);
 }
diff --git a/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp b/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp
index 7cb37ff4349..51aa3bb6838 100644
--- a/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp
+++ b/test/hotspot/gtest/logging/test_logTagSetDescriptions.cpp
@@ -42,7 +42,7 @@ TEST_VM(LogTagSetDescriptions, describe) {
     ResourceMark rm;
     stringStream stream;
     LogConfiguration::describe(&stream);
-    EXPECT_PRED2(string_contains_substring, stream.as_string(), expected)
+    EXPECT_THAT(stream.base(), testing::HasSubstr(expected))
       << "missing log tag set descriptions in LogConfiguration::describe";
   }
 }
diff --git a/test/hotspot/gtest/memory/test_guardedMemory.cpp b/test/hotspot/gtest/memory/test_guardedMemory.cpp
index b080b1315fd..6fa3abf99cc 100644
--- a/test/hotspot/gtest/memory/test_guardedMemory.cpp
+++ b/test/hotspot/gtest/memory/test_guardedMemory.cpp
@@ -140,7 +140,7 @@ TEST(GuardedMemory, wrap) {
   if (HasFatalFailure()) {
     return;
   }
-  EXPECT_EQ(0, strcmp(str, str_copy)) << "Not identical copy";
+  EXPECT_STREQ(str, str_copy) << "Not identical copy";
   EXPECT_TRUE(GuardedMemory::free_copy(str_copy)) << "Free copy failed to verify";
 
   void* no_data = NULL;
diff --git a/test/hotspot/gtest/oops/test_instanceKlass.cpp b/test/hotspot/gtest/oops/test_instanceKlass.cpp
index 9b170b5d723..079bb609212 100644
--- a/test/hotspot/gtest/oops/test_instanceKlass.cpp
+++ b/test/hotspot/gtest/oops/test_instanceKlass.cpp
@@ -27,6 +27,8 @@
 #include "oops/instanceKlass.hpp"
 #include "unittest.hpp"
 
+using testing::HasSubstr;
+
 // Tests for InstanceKlass::is_class_loader_instance_klass() function
 TEST_VM(InstanceKlass, class_loader_class) {
   InstanceKlass* klass = vmClasses::ClassLoader_klass();
diff --git a/test/hotspot/gtest/oops/test_markWord.cpp b/test/hotspot/gtest/oops/test_markWord.cpp
index e2f673b192a..fb9b6285f3d 100644
--- a/test/hotspot/gtest/oops/test_markWord.cpp
+++ b/test/hotspot/gtest/oops/test_markWord.cpp
@@ -41,20 +41,17 @@
 
 // The test doesn't work for PRODUCT because it needs WizardMode
 #ifndef PRODUCT
-static bool test_pattern(stringStream* st, const char* pattern) {
-  return (strstr(st->as_string(), pattern) != NULL);
-}
 
 static void assert_test_pattern(Handle object, const char* pattern) {
   stringStream st;
   object->print_on(&st);
-  ASSERT_TRUE(test_pattern(&st, pattern)) << pattern << " not in " << st.as_string();
+  ASSERT_THAT(st.base(), testing::HasSubstr(pattern));
 }
 
 static void assert_not_test_pattern(Handle object, const char* pattern) {
   stringStream st;
   object->print_on(&st);
-  ASSERT_FALSE(test_pattern(&st, pattern)) << pattern << " found in " << st.as_string();
+  ASSERT_THAT(st.base(), testing::Not(testing::HasSubstr(pattern)));
 }
 
 class LockerThread : public JavaTestThread {
diff --git a/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp b/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp
index 7802c5c2d21..0403ef37d30 100644
--- a/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp
+++ b/test/hotspot/gtest/runtime/test_ThreadsListHandle.cpp
@@ -171,8 +171,10 @@ TEST_VM(ThreadsListHandle, sanity) {
       // Verify the current thread refers to tlh2:
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2.list())
           << "thr->_threads_hazard_ptr must match tlh2.list()";
-      EXPECT_EQ(tlh1.list(), tlh2.list())
-          << "tlh1.list() must match tlh2.list()";
+    // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+    // until the root cause of test failure(JDK-8315141) has been fixed
+    //   EXPECT_EQ(tlh1.list(), tlh2.list())
+    //       << "tlh1.list() must match tlh2.list()";
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2)
           << "thr->_threads_list_ptr must match list_ptr2";
       EXPECT_NE(list_ptr1, list_ptr2)
@@ -291,8 +293,10 @@ TEST_VM(ThreadsListHandle, sanity) {
       // Verify the current thread refers to tlh2:
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2.list())
           << "thr->_threads_hazard_ptr must match tlh2.list()";
-      EXPECT_EQ(tlh1.list(), tlh2.list())
-          << "tlh1.list() must match tlh2.list()";
+    // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+    // until the root cause of test failure(JDK-8315141) has been fixed
+    //   EXPECT_EQ(tlh1.list(), tlh2.list())
+    //       << "tlh1.list() must match tlh2.list()";
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2)
           << "thr->_threads_list_ptr must match list_ptr2";
       EXPECT_NE(list_ptr1, list_ptr2)
@@ -339,8 +343,10 @@ TEST_VM(ThreadsListHandle, sanity) {
         // Verify the current thread refers to tlh3:
         EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh3.list())
             << "thr->_threads_hazard_ptr must match tlh3.list()";
-        EXPECT_EQ(tlh1.list(), tlh3.list())
-            << "tlh1.list() must match tlh3.list()";
+        // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+        // until the root cause of test failure(JDK-8315141) has been fixed
+        // EXPECT_EQ(tlh1.list(), tlh3.list())
+        //     << "tlh1.list() must match tlh3.list()";
         EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr3)
             << "thr->_threads_list_ptr must match list_ptr3";
         EXPECT_NE(list_ptr1, list_ptr3)
@@ -523,8 +529,10 @@ TEST_VM(ThreadsListHandle, sanity) {
       // Verify the current thread refers to tlh2a:
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2a.list())
           << "thr->_threads_hazard_ptr must match tlh2a.list()";
-      EXPECT_EQ(tlh1.list(), tlh2a.list())
-          << "tlh1.list() must match tlh2a.list()";
+    // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+    // until the root cause of test failure(JDK-8315141) has been fixed
+    //   EXPECT_EQ(tlh1.list(), tlh2a.list())
+    //       << "tlh1.list() must match tlh2a.list()";
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2a)
           << "thr->_threads_list_ptr must match list_ptr2a";
       EXPECT_NE(list_ptr1, list_ptr2a)
@@ -601,8 +609,10 @@ TEST_VM(ThreadsListHandle, sanity) {
       // Verify the current thread refers to tlh2b:
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_hazard_ptr(thr), tlh2b.list())
           << "thr->_threads_hazard_ptr must match tlh2b.list()";
-      EXPECT_EQ(tlh1.list(), tlh2b.list())
-          << "tlh1.list() must match tlh2b.list()";
+    // Disable unstable check of ThreadsListHandle.sanity_vm ThreadList values,
+    // until the root cause of test failure(JDK-8315141) has been fixed
+    //   EXPECT_EQ(tlh1.list(), tlh2b.list())
+    //       << "tlh1.list() must match tlh2b.list()";
       EXPECT_EQ(ThreadsListHandleTest::get_Thread_threads_list_ptr(thr), list_ptr2b)
           << "thr->_threads_list_ptr must match list_ptr2b";
       EXPECT_NE(list_ptr1, list_ptr2b)
diff --git a/test/hotspot/gtest/runtime/test_globals.cpp b/test/hotspot/gtest/runtime/test_globals.cpp
index 34f23eadcfa..5c4daf8d7bd 100644
--- a/test/hotspot/gtest/runtime/test_globals.cpp
+++ b/test/hotspot/gtest/runtime/test_globals.cpp
@@ -81,11 +81,11 @@ TEST_VM(FlagGuard, ccstr_flag) {
 TEST_VM(FlagAccess, ccstr_flag) {
   FLAG_SET_CMDLINE(SharedArchiveConfigFile, "");
   ASSERT_EQ(FLAG_IS_CMDLINE(SharedArchiveConfigFile), true);
-  ASSERT_EQ(strcmp(SharedArchiveConfigFile, ""), 0);
+  EXPECT_STREQ(SharedArchiveConfigFile, "");
 
   FLAG_SET_ERGO(SharedArchiveConfigFile, "foobar");
   ASSERT_EQ(FLAG_IS_ERGO(SharedArchiveConfigFile), true);
-  ASSERT_EQ(strcmp(SharedArchiveConfigFile, "foobar") , 0);
+  EXPECT_STREQ(SharedArchiveConfigFile, "foobar");
 
   FLAG_SET_ERGO(SharedArchiveConfigFile, nullptr);
   ASSERT_EQ(FLAG_IS_ERGO(SharedArchiveConfigFile), true);
@@ -93,7 +93,7 @@ TEST_VM(FlagAccess, ccstr_flag) {
 
   FLAG_SET_ERGO(SharedArchiveConfigFile, "xyz");
   ASSERT_EQ(FLAG_IS_ERGO(SharedArchiveConfigFile), true);
-  ASSERT_EQ(strcmp(SharedArchiveConfigFile, "xyz"), 0);
+  EXPECT_STREQ(SharedArchiveConfigFile, "xyz");
 }
 
 template 
diff --git a/test/hotspot/gtest/runtime/test_os.cpp b/test/hotspot/gtest/runtime/test_os.cpp
index 0c9de336196..25dd74c86c7 100644
--- a/test/hotspot/gtest/runtime/test_os.cpp
+++ b/test/hotspot/gtest/runtime/test_os.cpp
@@ -34,6 +34,8 @@
 #include "unittest.hpp"
 #include "runtime/frame.inline.hpp"
 
+using testing::HasSubstr;
+
 static size_t small_page_size() {
   return os::vm_page_size();
 }
@@ -167,7 +169,7 @@ static void do_test_print_hex_dump(address addr, size_t len, int unitsize, const
   os::print_hex_dump(&ss, addr, addr + len, unitsize);
 //  tty->print_cr("expected: %s", expected);
 //  tty->print_cr("result: %s", buf);
-  ASSERT_NE(strstr(buf, expected), (char*)NULL);
+  EXPECT_THAT(buf, HasSubstr(expected));
 }
 
 TEST_VM(os, test_print_hex_dump) {
@@ -769,7 +771,7 @@ TEST_VM(os, pagesizes_test_print) {
   char buffer[256];
   stringStream ss(buffer, sizeof(buffer));
   pss.print_on(&ss);
-  ASSERT_EQ(strcmp(expected, buffer), 0);
+  EXPECT_STREQ(expected, buffer);
 }
 
 TEST_VM(os, dll_address_to_function_and_library_name) {
@@ -778,9 +780,9 @@ TEST_VM(os, dll_address_to_function_and_library_name) {
   stringStream st(output, sizeof(output));
 
 #define EXPECT_CONTAINS(haystack, needle) \
-  EXPECT_NE(::strstr(haystack, needle), (char*)NULL)
+  EXPECT_THAT(haystack, HasSubstr(needle));
 #define EXPECT_DOES_NOT_CONTAIN(haystack, needle) \
-  EXPECT_EQ(::strstr(haystack, needle), (char*)NULL)
+  EXPECT_THAT(haystack, Not(HasSubstr(needle)));
 // #define LOG(...) tty->print_cr(__VA_ARGS__); // enable if needed
 #define LOG(...)
 
diff --git a/test/hotspot/jtreg/ProblemList.txt b/test/hotspot/jtreg/ProblemList.txt
index a9b6e4c0288..a588af5eaf0 100644
--- a/test/hotspot/jtreg/ProblemList.txt
+++ b/test/hotspot/jtreg/ProblemList.txt
@@ -115,13 +115,13 @@ serviceability/sa/TestRevPtrsForInvokeDynamic.java 8241235 generic-all
 serviceability/jvmti/ModuleAwareAgents/ThreadStart/MAAThreadStart.java 8225354 windows-all
 serviceability/dcmd/gc/RunFinalizationTest.java 8227120 generic-all
 
-serviceability/sa/ClhsdbCDSCore.java  8294316,8267433 macosx-x64
-serviceability/sa/ClhsdbFindPC.java#id1  8294316,8267433 macosx-x64
-serviceability/sa/ClhsdbFindPC.java#id3  8294316,8267433 macosx-x64
-serviceability/sa/ClhsdbPmap.java#id1  8294316,8267433 macosx-x64
-serviceability/sa/ClhsdbPstack.java#id1  8294316,8267433 macosx-x64
-serviceability/sa/TestJmapCore.java  8294316,8267433 macosx-x64
-serviceability/sa/TestJmapCoreMetaspace.java  8294316,8267433 macosx-x64
+serviceability/sa/ClhsdbCDSCore.java  8267433 macosx-x64
+serviceability/sa/ClhsdbFindPC.java#id1  8267433 macosx-x64
+serviceability/sa/ClhsdbFindPC.java#id3  8267433 macosx-x64
+serviceability/sa/ClhsdbPmap.java#id1  8267433 macosx-x64
+serviceability/sa/ClhsdbPstack.java#id1  8267433 macosx-x64
+serviceability/sa/TestJmapCore.java  8267433 macosx-x64
+serviceability/sa/TestJmapCoreMetaspace.java  8267433 macosx-x64
 
 #############################################################################
 
@@ -161,6 +161,7 @@ vmTestbase/vm/mlvm/meth/stress/jdi/breakpointInCompiledCode/Test.java 8257761 ge
 vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2none_a/TestDescription.java 8013267 generic-all
 vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2manyDiff_b/TestDescription.java 8013267 generic-all
 vmTestbase/vm/mlvm/indy/func/jvmti/mergeCP_indy2manySame_b/TestDescription.java 8013267 generic-all
+vmTestbase/vm/mlvm/meth/stress/compiler/deoptimize/Test.java#id1 8325905 generic-all
 
 vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn001/forceEarlyReturn001.java 7199837 generic-all
 
diff --git a/test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyDisjointLarge.java b/test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyDisjointLarge.java
new file mode 100644
index 00000000000..70d983e6ccd
--- /dev/null
+++ b/test/hotspot/jtreg/compiler/arraycopy/TestArrayCopyDisjointLarge.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package compiler.arraycopy;
+import java.util.Random;
+
+/**
+ * @test
+ * @bug 8310159
+ * @summary Test large arrayCopy.
+ *
+ * @run main/timeout=600 compiler.arraycopy.TestArrayCopyDisjointLarge
+ *
+ */
+
+public class TestArrayCopyDisjointLarge {
+
+    public static final int ARRLEN = 4194304;
+    public static int fromPos, toPos;
+    public static byte[] fromByteArr, toByteArr;
+
+    public static void setup() {
+        fromPos = 0;
+        toPos = 0;
+
+        fromByteArr = new byte[ARRLEN];
+        toByteArr = new byte[ARRLEN];
+        for (int i = 0 ; i < ARRLEN ; i++) {
+            fromByteArr[i] = (byte)i;
+        }
+    }
+
+    public static void validate(String msg, byte[] toByteArr, int length, int fromPos, int toPos) {
+        for(int i = 0 ; i < length; i++) {
+            if (fromByteArr[i + fromPos] != toByteArr[i + toPos]) {
+                System.out.println(msg + "[" + toByteArr.getClass() + "] Result mismtach at i = " + i
+                                + " expected = " + fromByteArr[i + fromPos]
+                                + " actual   = " + toByteArr[i + toPos]
+                                + " fromPos = " + fromPos
+                                + " toPos = " + toPos);
+                throw new Error("Fail");
+            }
+        }
+    }
+
+    public static void testByte(int length, int fromPos, int toPos) {
+        System.arraycopy(fromByteArr, fromPos, toByteArr, toPos, length);
+        validate(" Test ByteArr ", toByteArr, length, fromPos, toPos);
+    }
+
+    public static void main(String [] args) {
+        int base_size = 2621440;
+        Random r = new Random(1024);
+        int [] lengths = {base_size - 1, base_size, base_size + 1, base_size + 63, base_size + 64,
+                                base_size + 65, base_size + 255, base_size + 256, base_size + 257,
+                                base_size + r.nextInt(2048)};
+        setup();
+
+        for (int i = 0 ; i < 20 ; i++ ) {
+            testByte(lengths[i % lengths.length], 0, 0);
+            testByte(lengths[i % lengths.length], 0, 9);
+            testByte(lengths[i % lengths.length], 9, 0);
+            testByte(lengths[i % lengths.length], 9, 9);
+            testByte(lengths[i % lengths.length], r.nextInt(2048) , r.nextInt(2048));
+        }
+    }
+}
diff --git a/test/hotspot/jtreg/compiler/loopopts/LongCountedLoopInInfiniteLoop.jasm b/test/hotspot/jtreg/compiler/loopopts/LongCountedLoopInInfiniteLoop.jasm
new file mode 100644
index 00000000000..e7f75d46b5b
--- /dev/null
+++ b/test/hotspot/jtreg/compiler/loopopts/LongCountedLoopInInfiniteLoop.jasm
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+super public class LongCountedLoopInInfiniteLoop
+{
+  public Method "":"()V"
+    stack 1 locals 1
+  {
+        aload_0;
+        invokespecial    Method java/lang/Object."":"()V";
+        return;
+  }
+  Method test:"()V"
+    stack 3 locals 3
+  {
+        // #1 = 0;
+        iconst_0;
+        istore_1;
+
+    LOOPa:
+        // if #1 >= 10: goto END
+        iload_1;
+        bipush    10;
+        if_icmpge    END;
+
+        // if #1 > 1: goto LOOPc
+        iload_1;
+        iconst_1;
+        if_icmpgt    LOOPc;
+
+        // #2 = 0;
+        iconst_0;
+        istore_2;
+
+    LOOPb:
+        // if #2 > 2: goto LOOPa
+        iload_2;
+        iconst_2;
+        if_icmpgt    LOOPa;
+
+        // #2 ++
+        iinc    2, 1;
+
+        goto    LOOPb;
+
+    LOOPc:
+        // #1 ++
+        iinc    1, 1;
+
+        goto    LOOPa;
+
+    END:
+        return;
+    
+  }
+}
diff --git a/test/hotspot/jtreg/compiler/loopopts/MoveStoreAfterInfiniteLoop.jasm b/test/hotspot/jtreg/compiler/loopopts/MoveStoreAfterInfiniteLoop.jasm
new file mode 100644
index 00000000000..f93a2aa1170
--- /dev/null
+++ b/test/hotspot/jtreg/compiler/loopopts/MoveStoreAfterInfiniteLoop.jasm
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+super public class MoveStoreAfterInfiniteLoop
+{
+  static Field a:I;
+  static Field b:I;
+  static Field c:S;
+
+  public Method "":"()V"
+	stack 1 locals 1
+  {
+		aload_0;
+		invokespecial	Method java/lang/Object."":"()V";
+		return;
+  }
+
+public static Method test:"()V"
+    stack 3 locals 3
+  {
+    LTOP:
+        iconst_0;
+        istore_1;
+
+    LOUTER:
+        iload_1;
+        bipush    10;
+        if_icmpge    LTOP;
+
+        getstatic    Field c:"S";
+        putstatic    Field a:"I";
+
+        iconst_0;
+        istore_2;
+
+    LINNER:
+        iload_2;
+        iconst_2;
+        if_icmpge    LBOTTOM;
+
+        getstatic    Field b:"I";
+        i2s;
+        putstatic    Field c:"S";
+
+        iinc    2, 1;
+
+        goto    LINNER;
+
+    LBOTTOM:
+        iinc    1, 1;
+
+        goto    LOUTER;
+  }
+}
diff --git a/test/hotspot/jtreg/compiler/loopopts/TestLongCountedLoopInInfiniteLoop.java b/test/hotspot/jtreg/compiler/loopopts/TestLongCountedLoopInInfiniteLoop.java
new file mode 100644
index 00000000000..4dc16797258
--- /dev/null
+++ b/test/hotspot/jtreg/compiler/loopopts/TestLongCountedLoopInInfiniteLoop.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2024, Red Hat, Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8336478
+ * @summary C2: assert(!n->as_Loop()->is_loop_nest_inner_loop() || _loop_opts_cnt == 0) failed: should have been turned into a counted loop
+ * @compile LongCountedLoopInInfiniteLoop.jasm
+ * @run main/othervm -XX:+UnlockExperimentalVMOptions -Xcomp -XX:PerMethodTrapLimit=0 -XX:PerMethodSpecTrapLimit=0
+ *                   -XX:+IgnoreUnrecognizedVMOptions -XX:StressLongCountedLoop=2000000
+ *                   -XX:CompileCommand=compileonly,TestLongCountedLoopInInfiniteLoop::test TestLongCountedLoopInInfiniteLoop
+ */
+
+public class TestLongCountedLoopInInfiniteLoop {
+    public static void main(String[] args) {
+        LongCountedLoopInInfiniteLoop obj = new LongCountedLoopInInfiniteLoop();
+        test(false, obj);
+    }
+
+    private static void test(boolean flag, LongCountedLoopInInfiniteLoop obj) {
+        if (flag) {
+            obj.test();
+        }
+    }
+}
diff --git a/test/hotspot/jtreg/compiler/loopopts/TestMoveStoreAfterInfiniteLoop.java b/test/hotspot/jtreg/compiler/loopopts/TestMoveStoreAfterInfiniteLoop.java
new file mode 100644
index 00000000000..322e7a5053c
--- /dev/null
+++ b/test/hotspot/jtreg/compiler/loopopts/TestMoveStoreAfterInfiniteLoop.java
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2024, Red Hat, Inc. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8338100
+ * @summary C2: assert(!n_loop->is_member(get_loop(lca))) failed: control must not be back in the loop
+ * @compile MoveStoreAfterInfiniteLoop.jasm
+ * @run main/othervm -Xcomp -XX:-TieredCompilation -XX:CompileOnly=TestMoveStoreAfterInfiniteLoop::test
+ *                   -XX:CompileCommand=inline,MoveStoreAfterInfiniteLoop::test TestMoveStoreAfterInfiniteLoop
+ */
+
+public class TestMoveStoreAfterInfiniteLoop {
+    public static void main(String[] args) {
+        new MoveStoreAfterInfiniteLoop();
+        test(false);
+    }
+
+    private static void test(boolean flag) {
+        if (flag) {
+            MoveStoreAfterInfiniteLoop.test();
+        }
+    }
+}
diff --git a/test/hotspot/jtreg/compiler/loopopts/superword/TestEliminateAllocationWithCastP2XUse.java b/test/hotspot/jtreg/compiler/loopopts/superword/TestEliminateAllocationWithCastP2XUse.java
new file mode 100644
index 00000000000..416781d1b00
--- /dev/null
+++ b/test/hotspot/jtreg/compiler/loopopts/superword/TestEliminateAllocationWithCastP2XUse.java
@@ -0,0 +1,183 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package compiler.loopopts.superword;
+
+/*
+ * @test
+ * @bug 8342498
+ * @summary Test SuperWord, when it aligns to field-store, and the corresponding allocation is eliminated.
+ * @run driver compiler.loopopts.superword.TestEliminateAllocationWithCastP2XUse
+ * @run main/othervm -Xbatch
+ *                   -XX:-SplitIfBlocks -XX:LoopMaxUnroll=8
+ *                   -XX:+UnlockDiagnosticVMOptions -XX:DominatorSearchLimit=45
+ *                   compiler.loopopts.superword.TestEliminateAllocationWithCastP2XUse
+ */
+
+public class TestEliminateAllocationWithCastP2XUse {
+    public static void main(String args[]) {
+        byte[] a = new byte[10_000];
+        for (int i = 0; i < 10000; i++) {
+            test(a);
+        }
+    }
+
+    // Summary:
+    //  - Some B allocations are detected as NoEscape, but cannot be removed because of a field load.
+    //  - The field loads cannot be LoadNode::split_through_phi because DominatorSearchLimit is too low
+    //    for the dominates query to look through some IfNode / IfProj path.
+    //  - We go into loop-opts.
+    //  - In theory, the Stores of B::offset would be moved out of the loop. But we disable
+    //    PhaseIdealLoop::try_move_store_after_loop by setting -XX:-SplitIfBlocks.
+    //  - The field loads are folded away because of some MaxUnroll trick, where the val constant folds to 1.
+    //  - SuperWord eventually kicks in, and vectorizes the array stores.
+    //  - Since some vectorization has happened, SuperWord wants to align the main loop with a memory reference
+    //    in the loop. The code here is not very smart, and just picks the memory reference that occurs the
+    //    most often. But the B::offset stores occur more often than the array stores, and so we align to
+    //    one of the B::offset stores. This inserts a CastP2X under the CheckCastPP of the B allocation.
+    //  - Once loop opts is over, we eventually go into macro expansion.
+    //  - During macro expansion, we now discover that the Allocations were marked NoEscape, and that by now
+    //    there are no field loads any more: yay, we can remove the allocation!
+    //  - ... except that there is the CastP2X from SuperWord alignment ...
+    //  - The Allocation removal code wants to pattern match the CastP2X as part of a GC barrier, but then
+    //    the pattern does not conform to the expecatation - it is after all from SuperWord. This leads to
+    //    an assert, and SIGSEGV in product, at least with G1GC.
+    public static long test(byte[] a) {
+        // Delay val == 1 until loop-opts, with MaxUnroll trick.
+        int val = 0;
+        for (int i = 0; i < 4; i++) {
+            if ((i % 2) == 0) {
+                val = 1;
+            }
+        }
+        // during loop opts, we learn val == 1
+        // But we don't know that during EscapeAnalysis (EA) yet.
+
+        // 9 Allocations, discovered as NoEscape during EA.
+        B b1 = new B();
+        B b2 = new B();
+        B b3 = new B();
+        B b4 = new B();
+        B b5 = new B();
+        B b6 = new B();
+        B b7 = new B();
+        B b8 = new B();
+        B b9 = new B();
+
+        // Some path of IfNode / IfProj.
+        // Only folds away once we know val == 1
+        // This delays the LoadNode::split_through_phi, because it needs a dominates call
+        // to succeed, but it cannot look through this path because we set -XX:DominatorSearchLimit=45
+        // i.e. just a little too low to be able to look through.
+        // Without the LoadNode::split_through_phi before the end of EA, the Allocation cannot yet be
+        // removed, due to a "Field load", i.e. that Load for B::offset.
+        // But later, this path can actually fold away, when we know that val == 1. At that point,
+        // also the Load from B::offset folds away because LoadNode::split_through_phi succeeds
+        // At that point the B allocations have no Loads any more, and can be removed... but this only
+        // happens at macro expansion, after all loop opts.
+        if (val == 1010) { throw new RuntimeException("never"); }
+        if (val == 1020) { throw new RuntimeException("never"); }
+        if (val == 1030) { throw new RuntimeException("never"); }
+        if (val == 1040) { throw new RuntimeException("never"); }
+        if (val == 1060) { throw new RuntimeException("never"); }
+        if (val == 1070) { throw new RuntimeException("never"); }
+        if (val == 1080) { throw new RuntimeException("never"); }
+        if (val == 1090) { throw new RuntimeException("never"); }
+
+        if (val == 2010) { throw new RuntimeException("never"); }
+        if (val == 2020) { throw new RuntimeException("never"); }
+        if (val == 2030) { throw new RuntimeException("never"); }
+        if (val == 2040) { throw new RuntimeException("never"); }
+        if (val == 2060) { throw new RuntimeException("never"); }
+        if (val == 2070) { throw new RuntimeException("never"); }
+        if (val == 2080) { throw new RuntimeException("never"); }
+        if (val == 2090) { throw new RuntimeException("never"); }
+
+        if (val == 3010) { throw new RuntimeException("never"); }
+        if (val == 3020) { throw new RuntimeException("never"); }
+        if (val == 3030) { throw new RuntimeException("never"); }
+        if (val == 3040) { throw new RuntimeException("never"); }
+        if (val == 3060) { throw new RuntimeException("never"); }
+        if (val == 3070) { throw new RuntimeException("never"); }
+        if (val == 3080) { throw new RuntimeException("never"); }
+        if (val == 3090) { throw new RuntimeException("never"); }
+
+        if (val == 4010) { throw new RuntimeException("never"); }
+        if (val == 4020) { throw new RuntimeException("never"); }
+        if (val == 4030) { throw new RuntimeException("never"); }
+        if (val == 4040) { throw new RuntimeException("never"); }
+        if (val == 4060) { throw new RuntimeException("never"); }
+        if (val == 4070) { throw new RuntimeException("never"); }
+        if (val == 4080) { throw new RuntimeException("never"); }
+        if (val == 4090) { throw new RuntimeException("never"); }
+
+        long mulVal = 1;
+        for (int i = 0; i < a.length; i++) {
+            mulVal *= 3;
+            // We do some vector store, so that SuperWord succeeds, and creates the
+            // alignment code, which emits the CastP2X.
+            a[i]++;
+            // But we also have 9 Stores for the B::offset.
+            // SuperWord now sees more of these stores than of the array stores, and picks
+            // one of the B::offset stores as the alignment reference... creating a CastP2X
+            // for the CheckCastPP of the B allocation.
+            b1.offset = mulVal;
+            b2.offset = mulVal;
+            b3.offset = mulVal;
+            b4.offset = mulVal;
+            b5.offset = mulVal;
+            b6.offset = mulVal;
+            b7.offset = mulVal;
+            b8.offset = mulVal;
+            b9.offset = mulVal;
+        }
+
+        // This folds the loads away, once we know val == 1
+        // That happens during loop-opts, so after EA, but before macro expansion.
+        long ret = 0;
+        if (val == 42) {
+            ret = b1.offset +
+                  b2.offset +
+                  b3.offset +
+                  b4.offset +
+                  b5.offset +
+                  b6.offset +
+                  b7.offset +
+                  b8.offset +
+                  b9.offset;
+        }
+
+        return ret;
+    }
+
+    static class B {
+        // Add padding so that the old SuperWord::can_create_pairs accepts the field store to B.offset
+        long pad1 = 0;   // at 16
+        long pad2 = 0;   // at 24
+        long pad3 = 0;   // at 32
+        long pad4 = 0;   // at 40
+        long pad5 = 0;   // at 48
+        long pad6 = 0;   // at 56
+        long offset = 0; // offset at 64 bytes
+    }
+}
diff --git a/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/TestGetCreatedJavaVMs.java b/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/TestGetCreatedJavaVMs.java
new file mode 100644
index 00000000000..a84f6d7b327
--- /dev/null
+++ b/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/TestGetCreatedJavaVMs.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @library /test/lib
+ * @requires os.family != "Windows"
+ * @run driver TestGetCreatedJavaVMs
+ */
+import jdk.test.lib.Utils;
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.process.OutputAnalyzer;
+
+
+public class TestGetCreatedJavaVMs {
+    public static void main(String args[]) throws Exception {
+        ProcessBuilder pb = ProcessTools.createNativeTestProcessBuilder("GetCreatedJavaVMs");
+        OutputAnalyzer output = ProcessTools.executeProcess(pb);
+        output.shouldHaveExitValue(0);
+        output.reportDiagnosticSummary();
+    }
+}
diff --git a/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/exeGetCreatedJavaVMs.c b/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/exeGetCreatedJavaVMs.c
new file mode 100644
index 00000000000..a6fe23851f4
--- /dev/null
+++ b/test/hotspot/jtreg/runtime/jni/getCreatedJavaVMs/exeGetCreatedJavaVMs.c
@@ -0,0 +1,104 @@
+/*
+ * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* This code tests concurrent creation of and then attach to a JVM.
+ * Two threads race to create the JVM, the loser then checks GetCreatedJavaVMs
+ * and attaches to the returned JVM. Prior to the fix this could crash as the
+ * JVM is not fully initialized.
+ */
+#include "jni.h"
+#include 
+#include 
+#include 
+#include 
+#include 
+
+#define NUM_THREADS 2
+
+void *thread_runner(void *threadid) {
+  int tid;
+  tid = (int)(intptr_t)threadid;
+
+  JavaVM *vm;
+  JNIEnv *env = 0;
+
+  JavaVMInitArgs vm_args;
+  JavaVMOption options[0];
+  vm_args.version = JNI_VERSION_1_2;
+  vm_args.nOptions = 0;
+  vm_args.options = options;
+  vm_args.ignoreUnrecognized = JNI_FALSE;
+
+  printf("[%d] BEGIN JNI_CreateJavaVM\n", tid);
+  jint create_res = JNI_CreateJavaVM(&vm, (void **)&env, &vm_args);
+  printf("[%d] END JNI_CreateJavaVM\n", tid);
+
+  if (create_res != JNI_OK) {
+    printf("[%d] Error creating JVM: %d\n", tid, create_res);
+    if (create_res == JNI_EEXIST) {
+      jsize count;
+      printf("[%d] BEGIN JNI_GetCreatedJavaVMs\n", tid);
+      jint get_res = JNI_GetCreatedJavaVMs(&vm, 1, &count);
+      printf("[%d] END JNI_GetCreatedJavaVMs\n", tid);
+
+      if (get_res != JNI_OK) {
+        printf("[%d] Error obtaining created VMs: %d\n", tid, get_res);
+        pthread_exit(NULL);
+      } else {
+        printf("[%d] Obtained %d created VMs\n", tid, count);
+      }
+      if (count > 0) {
+        printf("[%d] BEGIN AttachCurrentThread\n", tid);
+        get_res = (*vm)->AttachCurrentThread(vm, (void **)&env, NULL);
+        printf("[%d] END AttachCurrentThread - %s\n", tid,
+               (get_res == JNI_OK ? "succeeded" : "failed"));
+        if (get_res == JNI_OK) {
+          (*vm)->DetachCurrentThread(vm);
+        }
+      }
+      pthread_exit(NULL);
+    } else {
+      pthread_exit(NULL);
+    }
+  } else {
+    printf("[%d] Created a JVM\n", tid);
+  }
+
+  pthread_exit(NULL);
+}
+
+int main (int argc, char* argv[]) {
+  pthread_t threads[NUM_THREADS];
+  for (int i = 0; i < NUM_THREADS; i++ ) {
+    printf("[*] Creating thread %d\n", i);
+    int status = pthread_create(&threads[i], NULL, thread_runner, (void *)(intptr_t)i);
+    if (status != 0) {
+      printf("[*] Error creating thread %d - %d\n", i, status);
+      exit(-1);
+    }
+  }
+  for (int i = 0; i < NUM_THREADS; i++ ) {
+    pthread_join(threads[i], NULL);
+  }
+  return 0;
+}
diff --git a/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/FieldIndicesTest.java b/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/FieldIndicesTest.java
new file mode 100644
index 00000000000..88a7f63fcc1
--- /dev/null
+++ b/test/hotspot/jtreg/serviceability/jvmti/FollowReferences/FieldIndices/FieldIndicesTest.java
@@ -0,0 +1,128 @@
+/*
+ * Copyright (c) 2024, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8317636
+ * @summary The test verifies heap walking API (FollowReferences) reports
+ *     field indeces in correct order (as described by jvmtiHeapReferenceInfoField spec).
+ *     For simplification only primitive field callback is tested
+ *     and all fields in the test classes are 'int'.
+ *     Field IDs are not reported to the callback, so the test uses field values
+ *     to distinguish between fields, so all field values in the test classes should be unique.
+ * @run main/othervm/native -agentlib:FieldIndicesTest FieldIndicesTest
+ */
+
+import java.lang.ref.Reference;
+
+// Test class hierarchy is based on the example described in the spec.
+// Extra fields added to improve coverage.
+interface I0 {
+    int p = 10;
+    // extra fields
+    public int p5 = 11;
+    int p6 = 12;
+    public int p1 = 13;
+}
+
+interface I1 extends I0 {
+    int x = 20;
+    // extra fields
+    int x1 = 21;
+    public int x2 = 22;
+}
+
+interface I2 extends I0 {
+    int y = 30;
+    // extra fields
+    int y9 = 31;
+    public int y4 = 32;
+    public int y3 = 33;
+}
+
+class C1 implements I1 {
+    public static int a = 40;
+    private int b = 41;
+    // extra fields
+    private int a1 = 42;
+    protected static int b7 = 43;
+    static int b2 = 44;
+    final protected int a3 = 45;
+    static int a2 = 46;
+    public int b1 = 47;
+}
+
+class C2 extends C1 implements I2 {
+    static int q = 60;
+    final int r = 61;
+    // extra fields
+    private int q11 = 61;
+    final static int q9 = 62;
+    static int q2 = 63;
+    final protected int r3 = 64;
+    public int r7 = 65;
+}
+
+public class FieldIndicesTest {
+    static {
+        System.loadLibrary("FieldIndicesTest");
+    }
+
+    private static native void prepare(Object testObject);
+
+    private static native void test(Object rootObject);
+
+    private static native boolean testFailed();
+
+    private static void prepare(String name, Object testObject) {
+        System.out.println(">>prepare(" + name + ")");
+        prepare(testObject);
+        System.out.println("<>test(" + name + ")");
+        test(rootObject);
+        System.out.println("<
+#include 
+#include "jvmti.h"
+#include "jvmti_common.h"
+
+extern "C" {
+
+static jvmtiEnv* jvmti = nullptr;
+static bool test_failed = false;
+
+static void* allocate(JNIEnv* env, jlong size) {
+  unsigned char* result = nullptr;
+  check_jvmti_status(env,
+    jvmti->Allocate(size, &result),
+    "Allocate failed");
+  return result;
+}
+
+static void deallocate(JNIEnv* env, void* mem) {
+  check_jvmti_status(env,
+    jvmti->Deallocate((unsigned char*)mem),
+    "Deallocate failed");
+}
+
+// Converts JNI class name signature to simple name (in place).
+static void sig2name(char* str) {
+  size_t len = strlen(str);
+  if (len >=2 && str[0] == 'L' && str[len-1] == ';') {
+    len -=2;
+    memmove(str, str+1, len);
+    str[len] = '\0';
+  }
+  // Replace '/' with '.'.
+  for (char* pos = str; (pos = strchr(pos, '/')) != nullptr; ) {
+    *pos = '.';
+  }
+}
+
+static bool is_static_field(JNIEnv* env, jclass klass, jfieldID fid) {
+  enum {
+    ACC_STATIC        = 0x0008
+  };
+
+  jint access_flags = 0;
+  check_jvmti_status(env,
+    jvmti->GetFieldModifiers(klass, fid, &access_flags),
+    "GetFieldModifiers failed");
+  return (access_flags & ACC_STATIC) != 0;
+}
+
+static void verify_int_field(JNIEnv* env, jclass klass, jfieldID fid) {
+  char* name = nullptr;
+  char* sig = nullptr;
+  check_jvmti_status(env,
+    jvmti->GetFieldName(klass, fid, &name, &sig, nullptr),
+    "GetFieldName failed");
+
+  if (strcmp(sig, "I") != 0) {
+    printf("ERROR: field '%s' is not int ('%s')\n", name, sig);
+    fflush(nullptr);
+    fatal(env, "unexpected field type");
+  }
+
+  deallocate(env, name);
+  deallocate(env, sig);
+}
+
+
+/*
+Per jvmtiHeapReferenceInfoField spec (reference information for
+JVMTI_HEAP_REFERENCE_FIELD and JVMTI_HEAP_REFERENCE_STATIC_FIELD references.):
+If the referrer object is not an interface, then the field indices are determined as follows:
+- make a list of all the fields in C and its superclasses,
+  starting with all the fields in java.lang.Object and ending with all the fields in C.
+- Within this list, put the fields for a given class in the order returned by GetClassFields.
+- Assign the fields in this list indices n, n+1, ..., in order,
+  where n is the count of the fields in all the interfaces implemented by C.
+  Note that C implements all interfaces directly implemented by its superclasses;
+  as well as all superinterfaces of these interfaces.
+If the referrer object is an interface, then the field indices are determined as follows:
+- make a list of the fields directly declared in I.
+- Within this list, put the fields in the order returned by GetClassFields.
+- Assign the fields in this list indices n, n+1, ..., in order,
+  where n is the count of the fields in all the superinterfaces of I.
+
+'Klass' struct contains all required data to calculate field indices.
+Also contains static field values.
+For each test class, the 'Klass' struct is created and a pointer to it is set as the jclass's tag.
+*/
+
+struct Klass {
+  jclass klass;
+  char* name;
+  Klass* super_klass;
+
+  struct Field {
+    jfieldID id;
+    char* name;
+
+    // Field value for static fields (0 for instance fields).
+    // All fields in the test classes are 'int'.
+    jint value;
+
+    void init(JNIEnv* env, jclass klass, jfieldID fid);
+  };
+
+  // Fields of the class and its superclasses
+  // as described in jvmtiHeapReferenceInfoField spec.
+  Field* fields;
+  jint field_count;
+
+  // Interfaces implemented by this klass, superclasses and superinterfaces.
+  Klass** interfaces;
+  jint interface_count;
+
+  // Number of fields in all implemented interfaces.
+  jint interface_field_count;
+
+  static Klass* explore(JNIEnv* env, jclass klass);
+
+private:
+  // Initializes fields, field_count.
+  void explore_fields(JNIEnv* env);
+  // Initializes interfaces, interface_count.
+  void explore_interfaces(JNIEnv* env);
+
+  void print() const;
+};
+
+/*
+For each test object, the 'Object' struct is created and a pointer to it is set as the jobject's tag.
+*/
+struct Object {
+  Klass* klass;
+  // Values of instance fields (0 for static fields).
+  // Size of the array == klass->field_count.
+  jint* field_values;
+
+  static Object* explore(JNIEnv* env, jobject obj);
+};
+
+
+void Klass::Field::init(JNIEnv* env, jclass klass, jfieldID fid) {
+  id = fid;
+  check_jvmti_status(env,
+    jvmti->GetFieldName(klass, fid, &name, nullptr, nullptr),
+    "GetFieldName failed");
+  if (is_static_field(env, klass, fid)) {
+    verify_int_field(env, klass, fid);
+    value = env->GetStaticIntField(klass, fid);
+  } else {
+    value = 0;
+  }
+}
+
+void Klass::explore_fields(JNIEnv* env) {
+  jint this_count;
+  jfieldID* this_fields;
+  check_jvmti_status(env,
+    jvmti->GetClassFields(klass, &this_count, &this_fields),
+    "GetClassFields failed");
+
+  jint super_count = super_klass != nullptr ? super_klass->field_count : 0;
+
+  fields = (Field*)allocate(env, sizeof(Field) * (super_count + this_count));
+  field_count = 0;
+
+  if (super_klass != 0) {
+    // super_klass->fields already contains fields from all superclasses in the required order.
+    for (int i = 0; i < super_count; i++) {
+      fields[field_count++].init(env, super_klass->klass, super_klass->fields[i].id);
+    }
+  }
+
+  // Add field of this class to the end of the list.
+  for (int i = 0; i < this_count; i++) {
+    fields[field_count++].init(env, klass, this_fields[i]);
+  }
+  deallocate(env, this_fields);
+}
+
+
+// Calculates maximum number of implemented interfaces of the klass and its superinterfaces.
+static jint get_max_interface_count(JNIEnv* env, jclass klass) {
+  jint interface_count;
+  jclass* interfaces;
+  check_jvmti_status(env,
+    jvmti->GetImplementedInterfaces(klass, &interface_count, &interfaces),
+    "GetImplementedInterfaces failed");
+
+  jint result = interface_count;
+  // interfaces implemented by superinterfaces
+  for (jint i = 0; i < interface_count; i++) {
+    result += get_max_interface_count(env, interfaces[i]);
+  }
+
+  deallocate(env, interfaces);
+
+  return result;
+}
+
+// Explores all interfaces implemented by 'klass', sorts out duplicates,
+// and stores the interfaces in the 'arr' starting from 'index'.
+// Returns number of the interfaces added.
+static jint fill_interfaces(Klass** arr, jint index, JNIEnv* env, jclass klass) {
+  jint interface_count;
+  jclass* interfaces;
+  check_jvmti_status(env,
+    jvmti->GetImplementedInterfaces(klass, &interface_count, &interfaces),
+    "GetImplementedInterfaces failed");
+
+  jint count = 0;
+  for (jint i = 0; i < interface_count; i++) {
+    // Skip interface if it's already in the array
+    // (i.e. implemented by another superclass/superinterface).
+    bool dup = false;
+    for (jint j = 0; j < index; j++) {
+      if (env->IsSameObject(arr[j]->klass, interfaces[i]) == JNI_TRUE) {
+        dup = true;
+        break;
+      }
+    }
+    if (dup) {
+      continue;
+    }
+
+    // Add the interface.
+    arr[index + count] = Klass::explore(env, interfaces[i]);
+    count++;
+
+    // And explore its superinterfaces.
+    count += fill_interfaces(arr, index + count, env, interfaces[i]);
+  }
+
+  deallocate(env, interfaces);
+
+  return count;
+}
+
+void Klass::explore_interfaces(JNIEnv* env) {
+  jint max_count = get_max_interface_count(env, klass);
+  if (super_klass != nullptr) {
+    max_count += super_klass->interface_count;
+  }
+
+  // Allocate array for maximum possible count.
+  interfaces = (Klass**)allocate(env, sizeof(Klass*) * max_count);
+
+  interface_count = 0;
+  if (super_klass != nullptr) {
+    // Add all interfaces implemented by super_klass first.
+    interface_count = super_klass->interface_count;
+    memcpy(interfaces, super_klass->interfaces, sizeof(Klass*) * super_klass->interface_count);
+  }
+
+  // Interfaces implemented by the klass.
+  interface_count += fill_interfaces(interfaces, interface_count, env, klass);
+}
+
+void Klass::print() const {
+  printf("Explored klass: %s, super: %s\n",
+         name, super_klass == nullptr ? nullptr : super_klass->name);
+  printf("  interfaces (%d):\n", (int)interface_count);
+  for (jint i = 0; i < interface_count; i++) {
+    printf("    %d: %s\n", (int)i, interfaces[i]->name);
+  }
+  printf("  fields (%d):\n", (int)field_count);
+  for (jint i = 0; i < field_count; i++) {
+    printf("    %d: %s (value = %d)\n",
+           (int)i, fields[i].name, (int)fields[i].value);
+  }
+  printf("  interface_field_count: %d\n", (int)interface_field_count);
+}
+
+Klass* Klass::explore(JNIEnv* env, jclass klass) {
+  jlong tag = 0;
+  check_jvmti_status(env,
+    jvmti->GetTag(klass, &tag),
+    "GetTag failed");
+  if (tag != 0) { // already explored
+    return (Klass*)tag;
+  }
+
+  Klass* result = (Klass*)allocate(env, sizeof(Klass));
+
+  result->klass = (jclass)env->NewGlobalRef(klass);
+
+  check_jvmti_status(env,
+    jvmti->GetClassSignature(klass, &result->name, nullptr),
+    "GetClassSignature failed");
+  sig2name(result->name);
+
+  // Explore superclass first.
+  jclass super_klass = env->GetSuperclass(klass);
+  result->super_klass = super_klass == nullptr ? nullptr : Klass::explore(env, super_klass);
+
+  result->explore_fields(env);
+
+  result->explore_interfaces(env);
+
+  // Calculate interface_field_count.
+  result->interface_field_count = 0;
+  for (jint i = 0; i < result->interface_count; i++) {
+    result->interface_field_count += result->interfaces[i]->field_count;
+  }
+
+  check_jvmti_status(env,
+    jvmti->SetTag(klass, (jlong)result),
+    "SetTag failed");
+
+  result->print();
+
+  return result;
+}
+
+Object* Object::explore(JNIEnv* env, jobject obj) {
+  jlong tag = 0;
+  check_jvmti_status(env,
+    jvmti->GetTag(obj, &tag),
+    "GetTag failed");
+  if (tag != 0) { // already explored
+    return (Object*)tag;
+  }
+
+  jclass obj_klass = env->GetObjectClass(obj);
+  Klass* klass = Klass::explore(env, obj_klass);
+  jint* values = (jint*)allocate(env, sizeof(jint) * klass->field_count);
+
+  for (jint i = 0; i < klass->field_count; i++) {
+    jfieldID fid = klass->fields[i].id;
+    if (is_static_field(env, obj_klass, fid)) {
+      values[i] = 0;
+    } else {
+      verify_int_field(env, obj_klass, fid);
+      values[i] = env->GetIntField(obj, fid);
+    }
+  }
+
+  Object* result = (Object*)allocate(env, sizeof(Object));
+  result->klass = klass;
+  result->field_values = values;
+
+  check_jvmti_status(env,
+    jvmti->SetTag(obj, (jlong)result),
+    "SetTag failed");
+
+  return result;
+}
+
+
+JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *jvm, char *options, void *reserved) {
+  jint res = jvm->GetEnv((void **)&jvmti, JVMTI_VERSION_1_1);
+  if (res != JNI_OK || jvmti == nullptr) {
+    printf("jvm->GetEnv failed\n");
+    fflush(nullptr);
+    return JNI_ERR;
+  }
+
+  jvmtiCapabilities caps;
+  memset(&caps, 0, sizeof(caps));
+  caps.can_tag_objects = 1;
+  jvmtiError err = jvmti->AddCapabilities(&caps);
+  if (err != JVMTI_ERROR_NONE) {
+    printf("AddCapabilities failed: %s (%d)\n", TranslateError(err), err);
+    fflush(nullptr);
+    return JNI_ERR;
+  }
+
+  return JNI_OK;
+}
+
+
+static bool check_index_bounds(jint index, Klass* klass) {
+  if (index < klass->interface_field_count) {
+    printf("ERROR: field_index is too small (%d < %d)\n",
+           (int)index, (int)klass->interface_field_count);
+    test_failed = true;
+    return false;
+  }
+  if (index >= klass->interface_field_count + klass->field_count) {
+    printf("ERROR: field_index is too big (%d >= %d)\n",
+           (int)index, (int)(klass->interface_field_count + klass->field_count));
+    test_failed = true;
+    return false;
+  }
+  return true;
+}
+
+static char* get_field_name(Klass* klass, jint index) {
+  index -= klass->interface_field_count;
+  if (index < 0 || index >= klass->field_count) {
+    return nullptr;
+  }
+  return klass->fields[index].name;
+}
+
+
+jint JNICALL primitiveFieldCallback(
+   jvmtiHeapReferenceKind        reference_kind,
+   const jvmtiHeapReferenceInfo* reference_info,
+   jlong                         class_tag,
+   jlong*                        tag_ptr,
+   jvalue                        value,
+   jvmtiPrimitiveType            value_type,
+   void*                         user_data)
+{
+  if (*tag_ptr == 0) {
+    return 0;
+  }
+
+  jint index = reference_info->field.index;
+  jint int_value = value.i;
+  if (value_type != JVMTI_PRIMITIVE_TYPE_INT) {
+    printf("ERROR: unexpected value type in primitiveFieldCallback: '%c'\n", (char)value_type);
+    test_failed = true;
+    int_value = -1;
+  }
+
+  if (reference_kind == JVMTI_HEAP_REFERENCE_FIELD) {
+    Object* obj = (Object*)(*tag_ptr);
+    Klass* klass = obj->klass;
+    printf("primitiveFieldCallback(JVMTI_HEAP_REFERENCE_FIELD): "
+           "klass=%s, index=%d, type=%c, value=%d\n",
+           klass->name, index,
+           (int)value_type, (int)value.i);
+    if (check_index_bounds(index, klass)) {
+      jint expected_value = obj->field_values[index - klass->interface_field_count];
+      if (int_value != expected_value) {
+        printf("  ERROR: wrong instance value: (%d, expected %d)\n",
+               (int)int_value, (int)expected_value);
+        test_failed = true;
+      } else {
+        printf("  OK: field %s.%s, value %d\n",
+               klass->name, get_field_name(klass, index), (int)int_value);
+      }
+    }
+  } else if (reference_kind == JVMTI_HEAP_REFERENCE_STATIC_FIELD) {
+    Klass* klass = (Klass*)(*tag_ptr);
+    printf("primitiveFieldCallback(JVMTI_HEAP_REFERENCE_STATIC_FIELD): "
+           "klass=%s, index=%d, type=%c, value=%d\n",
+           klass->name, index,
+           (int)value_type, (int)value.i);
+    if (check_index_bounds(index, klass)) {
+      jint expected_value = klass->fields[index - klass->interface_field_count].value;
+      if (int_value != expected_value) {
+        printf("  ERROR: wrong static value: (%d, expected %d)\n\n\n",
+               (int)int_value, (int)expected_value);
+        test_failed = true;
+      } else {
+        printf("  OK: field %s.%s, value %d\n",
+               klass->name, get_field_name(klass, index), (int)int_value);
+      }
+    }
+  } else {
+    printf("ERROR: unexpected reference_kind in primitiveFieldCallback: %d\n", (int)reference_kind);
+    test_failed = true;
+  }
+
+  fflush(nullptr);
+  return 0;
+}
+
+
+JNIEXPORT void JNICALL
+Java_FieldIndicesTest_prepare(JNIEnv *env, jclass cls, jobject testObj) {
+  Object::explore(env, testObj);
+  fflush(nullptr);
+}
+
+JNIEXPORT void JNICALL
+Java_FieldIndicesTest_test(JNIEnv *env, jclass cls, jobject rootObject) {
+  jvmtiHeapCallbacks heapCallbacks;
+  memset(&heapCallbacks, 0, sizeof(heapCallbacks));
+
+  heapCallbacks.primitive_field_callback = primitiveFieldCallback;
+
+  check_jvmti_status(env,
+    jvmti->FollowReferences(JVMTI_HEAP_FILTER_UNTAGGED, // heap_filter
+                            nullptr,                    // class
+                            rootObject,                 // initial_object
+                            &heapCallbacks,
+                            nullptr),
+    "FollowReferences failed");
+  fflush(nullptr);
+}
+
+JNIEXPORT jboolean JNICALL
+Java_FieldIndicesTest_testFailed(JNIEnv *env, jclass cls) {
+  return test_failed ? JNI_TRUE : JNI_FALSE;
+}
+
+}
diff --git a/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java b/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java
index cf20b0df8a0..8d1a5fac9ae 100644
--- a/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java
+++ b/test/hotspot/jtreg/vmTestbase/jit/escape/LockElision/MatMul/MatMul.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -85,7 +85,7 @@ public static void main(String[] args) {
     }
 
     public int run() {
-        log = new Log(System.out, verbose);
+        log = new Log(System.out);
         log.display("Parallel matrix multiplication test");
 
         Matrix a = Matrix.randomMatrix(dim);
diff --git a/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java b/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java
index 3ce0a825285..61a19baf98e 100644
--- a/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java
+++ b/test/hotspot/jtreg/vmTestbase/metaspace/stressHierarchy/common/StressHierarchyBaseClass.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2021, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,13 +24,13 @@
 
 import java.net.MalformedURLException;
 
+import vm.share.gc.HeapOOMEException;
 import vm.share.gc.TriggerUnloadingByFillingMetaspace;
 import vm.share.gc.TriggerUnloadingHelper;
 import vm.share.gc.TriggerUnloadingWithWhiteBox;
 
 import metaspace.stressHierarchy.common.classloader.tree.Node;
 import metaspace.stressHierarchy.common.classloader.tree.Tree;
-import metaspace.stressHierarchy.common.exceptions.GotWrongOOMEException;
 import metaspace.stressHierarchy.common.exceptions.TimeIsOverException;
 import metaspace.stressHierarchy.common.generateHierarchy.GenerateHierarchyHelper;
 import metaspace.stressHierarchy.common.generateHierarchy.GenerateHierarchyHelper.Type;
@@ -109,8 +109,8 @@ public void run() {
 
             System.out.println("Whole test took " + ((System.currentTimeMillis() - startTimeStamp)/1000/60.0) +" min");
             log.info("Test PASSED");
-        } catch (GotWrongOOMEException e) {
-            log.info("GotWrongOOMEExc: " + e.getMessage());
+        } catch (HeapOOMEException e) {
+            log.info("HeapOOMEException: " + e.getMessage());
             log.info("Got wrong type of OOME. We are passing test as it breaks test logic. We have dedicated test configurations" +
             " for each OOME type provoking class unloading, that's why we are not missing test coverage here.");
         } catch (OutOfMemoryError e) {
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java b/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java
index 9c03396d67f..4366287380f 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jdi/LaunchingConnector/launchnosuspend/launchnosuspend001.java
@@ -71,7 +71,6 @@ private launchnosuspend001 (String args[], PrintStream out) {
 
         argHandler = new ArgumentHandler(args);
         log = new Log(this.out, argHandler);
-        //log.enableVerbose(true);
     }
 
     private PrintStream out;
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java b/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java
index 420dd065053..3d1fb85f075 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002.java
@@ -139,13 +139,34 @@ private void sendCommand(long threadID, Value value, boolean expectError, int er
         }
     }
 
+    // get thread ID for "startNewThread" command
+    private long getNewThreadId() throws Exception {
+        final String debugeeClassSig = "L" + getDebugeeClassName().replace('.', '/') + ";";
+        log.display("  getting classID for " + debugeeClassSig);
+        long classID = debuggee.getReferenceTypeID(debugeeClassSig);
+        log.display("  got classID: " + classID);
+
+        log.display("  getting testNewThread field value");
+        JDWP.Value value = debuggee.getStaticFieldValue(classID, "testNewThread", JDWP.Tag.THREAD);
+
+        long threadID = ((Long)value.getValue()).longValue();
+        log.display("  got threadID: " + threadID);
+        return threadID;
+    }
+
     private int createThreadStartEventRequest() {
         try {
+            long newThreadId = getNewThreadId();
             // create command packet and fill requred out data
             CommandPacket command = new CommandPacket(JDWP.Command.EventRequest.Set);
             command.addByte(JDWP.EventKind.THREAD_START);
             command.addByte(JDWP.SuspendPolicy.ALL);
-            command.addInt(0);
+            // we want the THREAD_START event only for the test thread
+            // and not any others that might be started by debuggee VM,
+            // so add THREAD_ONLY modifier
+            command.addInt(1);
+            command.addByte(JDWP.EventModifierKind.THREAD_ONLY);
+            command.addObjectID(newThreadId);
             command.setLength();
 
             transport.write(command);
@@ -175,7 +196,7 @@ public void doTest() {
         Value value;
 
         value = new Value(JDWP.Tag.INT, 0);
-        // create command with invalid trheadID, expect INVALID_OBJECT error
+        // create command with invalid threadID, expect INVALID_OBJECT error
         sendCommand(-1, value, true, JDWP.Error.INVALID_OBJECT);
 
         // create StateTestThread
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java b/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java
index 131ab11e8f8..f5a740ec2f1 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jdwp/ThreadReference/ForceEarlyReturn/forceEarlyReturn002/forceEarlyReturn002a.java
@@ -51,14 +51,7 @@ public boolean parseCommand(String command) {
 
             return true;
         } else if (command.equals(COMMAND_START_NEW_THREAD)) {
-            Thread thread = new Thread(new Runnable() {
-                public void run() {
-                    log.display("Thread exit");
-                }
-            });
-
-            thread.setName("forceEarlyReturn002a_NewThread");
-            thread.start();
+            testNewThread.start();
 
             return true;
         }
@@ -66,6 +59,21 @@ public void run() {
         return false;
     }
 
+    @Override
+    protected void init(String args[]) {
+        super.init(args);
+
+        // create thread for "NewThread" command in advance
+        testNewThread = new Thread(new Runnable() {
+            public void run() {
+                log.display("Thread exit");
+            }
+        });
+        testNewThread.setName("forceEarlyReturn002a_NewThread");
+    }
+
+    private static Thread testNewThread;
+
     private Thread testThreadInNative;
 
     private void stopThreadInNative() {
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java
index 91f315ee7a9..b690955307e 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/IterateThroughHeap/filter_tagged/HeapFilter.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2020, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,7 +49,6 @@ public int runTest(String args[], PrintStream out) {
         log = new Log(out, argHandler);
         testObjects = new Object[]{new TaggedClass(),
                                    new UntaggedClass()};
-        log.enableVerbose(true);
         log.display("Verifying reachable objects.");
         status = checkStatus(status);
         testObjects = null;
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java
index fd98b382d2a..e2a48a948e9 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/jvmti/SuspendThread/suspendthrd003.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2021, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2022, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -88,6 +88,9 @@ public int runIt(String argv[], PrintStream out) {
         int res = -1;
         long start_time = System.currentTimeMillis();
         while (System.currentTimeMillis() < start_time + (timeMax * 1000)) {
+            // Start each loop with a clear log buffer so we only
+            // track the run that can potentially fail:
+            log.clearLogBuffer();
             count++;
 
             // Original suspendthrd001 test block starts here:
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java
index 5dd252db244..4a41e6d2c4b 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isCollectionUsageThresholdExceeded/isexceeded001.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,7 +40,6 @@ public static void main(String[] argv) {
     public static int run(String[] argv, PrintStream out) {
         ArgumentHandler argHandler = new ArgumentHandler(argv);
         Log log = new Log(out, argHandler);
-        log.enableVerbose(true);
 
         monitor = Monitor.getMemoryMonitor(log, argHandler);
         List pools = monitor.getMemoryPoolMBeans();
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java
index 390bfdd6251..a684c03e67a 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/MemoryPoolMBean/isUsageThresholdExceeded/isexceeded001.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2022, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -47,7 +47,6 @@ public static void main(String[] argv) {
     public static int run(String[] argv, PrintStream out) {
         ArgumentHandler argHandler = new ArgumentHandler(argv);
         Log log = new Log(out, argHandler);
-        log.enableVerbose(true); // show log output
 
         MemoryMonitor monitor = Monitor.getMemoryMonitor(log, argHandler);
         List pools = monitor.getMemoryPoolMBeans();
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java
index d698e5aec83..67f0d17f561 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/monitoring/stress/lowmem/lowmem001.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2018, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -58,7 +58,7 @@ public static void main(String[] args) {
 
     @Override
     public void run() {
-        Log log = new Log(System.out, true);
+        Log log = new Log(System.out);
         // System.err is duplicated into buffer
         // it should be empty
         MyStream stream = new MyStream(System.err);
diff --git a/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java b/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java
index 990e45133ee..a9086bcf253 100644
--- a/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java
+++ b/test/hotspot/jtreg/vmTestbase/nsk/share/Log.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2021, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2022, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,15 +36,9 @@
 import java.util.HashSet;
 import java.util.Vector;
 
-import nsk.share.test.LazyFormatString;
 
 /**
- * This class helps to print test-execution trace messages
- * and filter them when execution mode is not verbose.
- * 

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

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

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

    FrameStateTest
    Bug ID: 4157271

    -

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

    -

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

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

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


    + + Steps to try to reproduce this problem: +

    + Select the different options for the Frame: +

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


    + + Do the above steps for all the different Frame state combinations available.
    + If you observe the proper behavior the test has passed, Press the Pass button.
    + Otherwise the test has failed, Press the Fail button. +

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

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

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

    PrintApplet

    - - - -

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

    PrinterDialogsModalityTest
    Bug ID: 4784285 4785920

    - -

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

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

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

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

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

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

    Using {@code Builder}

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

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

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

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

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

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

    This test case throws ArrayIndexOutOfBoundsException without the fix. */ + @Test public void Test4683492() { Calendar cal = new GregorianCalendar(2002, 3, 29, 10, 0, 0); cal.set(DAY_OF_WEEK, FRIDAY); @@ -1956,13 +1999,14 @@ public void Test4683492() { String expected = "2003/01/31"; String s = df.format(cal.getTime()); if (!expected.equals(s)) { - errln("expected: " + expected + ", got: " + s); + fail("expected: " + expected + ", got: " + s); } } /** * 4080631: Calendar.hashCode is amazingly bad */ + @Test public void Test4080631() { Calendar cal = Calendar.getInstance(); int h1 = cal.hashCode(); @@ -1971,16 +2015,16 @@ public void Test4080631() { Calendar cal2 = (Calendar) cal.clone(); cal.add(MILLISECOND, +1); int h3 = cal.hashCode(); - logln("hash code: h1=" + h1 + ", h2=" + h2 + ", h3=" + h3); + System.out.println("hash code: h1=" + h1 + ", h2=" + h2 + ", h3=" + h3); if (h1 == h2 || h1 == h3 || h2 == h3) { - errln("hash code is poor: hashCode=" + h1); + fail("hash code is poor: hashCode=" + h1); } h2 = cal2.hashCode(); cal.add(MILLISECOND, -1); int h4 = cal.hashCode(); - logln("hash code: h2=" + h2 + ", h4=" + h4); + System.out.println("hash code: h2=" + h2 + ", h4=" + h4); if (cal.equals(cal2) && h2 != h4) { - errln("broken hash code: h2=" + h2 + ", h4=" + h4); + fail("broken hash code: h2=" + h2 + ", h4=" + h4); } int x = cal.getFirstDayOfWeek() + 3; if (x > SATURDAY) { @@ -1988,9 +2032,9 @@ public void Test4080631() { } cal.setFirstDayOfWeek(x); int h5 = cal.hashCode(); - logln("hash code: h4=" + h4 + ", h5=" + h5); + System.out.println("hash code: h4=" + h4 + ", h5=" + h5); if (h4 == h5) { - errln("has code is poor with first day of week param: hashCode=" + h4); + fail("has code is poor with first day of week param: hashCode=" + h4); } } @@ -1998,6 +2042,7 @@ public void Test4080631() { * 4125161: RFE: GregorianCalendar needs more era names (BCE and CE) */ /* + @Test public void Test4125161() throws Exception { Class gc = GregorianCalendar.class; Field f; @@ -2005,86 +2050,89 @@ public void Test4125161() throws Exception { f = gc.getDeclaredField("BCE"); mod = f.getModifiers(); if (!Modifier.isStatic(mod) || !Modifier.isFinal(mod)) { - errln("BCE: wrong modifiers: " + mod); + fail("BCE: wrong modifiers: " + mod); } f = gc.getDeclaredField("CE"); mod = f.getModifiers(); if (!Modifier.isStatic(mod) || !Modifier.isFinal(mod)) { - errln("CE: wrong modifiers: " + mod); + fail("CE: wrong modifiers: " + mod); } if (GregorianCalendar.BCE != GregorianCalendar.BC || GregorianCalendar.CE != GregorianCalendar.AD) { - errln("Wrong BCE and/or CE values"); + fail("Wrong BCE and/or CE values"); } } */ /** * 4167995: GregorianCalendar.setGregorianChange() not to spec */ + @Test public void Test4167995() { Koyomi gc = new Koyomi(TimeZone.getTimeZone("GMT")); - logln("Hybrid: min date"); + System.out.println("Hybrid: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Hybrid: max date"); + System.out.println("Hybrid: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MIN_VALUE)); - logln("Gregorian: min date"); + System.out.println("Gregorian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292275056, MAY, 16, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Gregorian: max date"); + System.out.println("Gregorian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MAX_VALUE)); - logln("Julian: min date"); + System.out.println("Julian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } - logln("Julian: max date"); + System.out.println("Julian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); if (!gc.checkDate(292272993, JANUARY, 4, SUNDAY) || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { - errln(gc.getMessage()); + fail(gc.getMessage()); } } /** * 4340146: Calendar.equals modifies state */ + @Test public void Test4340146() { Koyomi cal = new Koyomi(); cal.clear(); cal.set(2003, OCTOBER, 32); cal.equals(new Koyomi()); if (!cal.checkInternalDate(2003, OCTOBER, 32)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } new Koyomi().equals(cal); if (!cal.checkInternalDate(2003, OCTOBER, 32)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4639407: GregorianCalendar doesn't work in non-lenient due to timezone bounds checking */ + @Test public void Test4639407() { // The following operations in non-lenient mode shouldn't // throw IllegalArgumentException. @@ -2100,6 +2148,7 @@ public void Test4639407() { /** * 4652815: rolling week-of-year back hundreds of weeks changes year */ + @Test public void Test4652815() { Koyomi cal = new Koyomi(Locale.US); testRoll(cal, 2003, SEPTEMBER, 29); @@ -2112,18 +2161,18 @@ private void testRoll(Koyomi cal, int year, int month, int dayOfMonth) { cal.clear(); cal.set(year, month, dayOfMonth); cal.getTime(); // normalize fields - logln("Roll backwards from " + cal.toDateString()); + System.out.println("Roll backwards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { cal.roll(WEEK_OF_YEAR, -i); if (!cal.checkFieldValue(YEAR, year)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } - logln("Roll forewards from " + cal.toDateString()); + System.out.println("Roll forewards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { cal.roll(WEEK_OF_YEAR, +i); if (!cal.checkFieldValue(YEAR, year)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } @@ -2131,47 +2180,50 @@ private void testRoll(Koyomi cal, int year, int month, int dayOfMonth) { /** * 4652830: GregorianCalendar roll behaves unexpectedly for dates in BC era */ + @Test public void Test4652830() { Koyomi cal = new Koyomi(Locale.US); cal.clear(); - logln("BCE 9-2-28 (leap year) roll DAY_OF_MONTH++ twice"); + System.out.println("BCE 9-2-28 (leap year) roll DAY_OF_MONTH++ twice"); cal.set(ERA, GregorianCalendar.BC); cal.set(9, FEBRUARY, 28); if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { - errln(" wrong actual max of DAY_OF_YEAR: got " + fail(" wrong actual max of DAY_OF_YEAR: got " + cal.getActualMaximum(DAY_OF_YEAR) + " expected " + 366); } cal.roll(DAY_OF_MONTH, +1); if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) || !cal.checkDate(9, FEBRUARY, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.roll(DAY_OF_MONTH, +1); if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) || !cal.checkDate(9, FEBRUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4740554: GregorianCalendar.getActualMaximum is inconsistent with normalization */ + @Test public void Test4740554() { - logln("1999/(Feb+12)/1 should be normalized to 2000/Feb/1 for getActualMaximum"); + System.out.println("1999/(Feb+12)/1 should be normalized to 2000/Feb/1 for getActualMaximum"); Koyomi cal = new Koyomi(Locale.US); cal.clear(); cal.set(1999, FEBRUARY + 12, 1); if (!cal.checkActualMaximum(DAY_OF_YEAR, 366)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4936355: GregorianCalendar causes overflow/underflow with time of day calculation */ + @Test public void Test4936355() { Koyomi cal = new Koyomi(TimeZone.getTimeZone("GMT")); cal.clear(); @@ -2213,7 +2265,7 @@ private void checkTimeCalculation(Koyomi cal, int field, int value, long expecte long time2 = cal.getTimeInMillis(); if ((time + expectedDelta) != time2) { String s = value == Integer.MAX_VALUE ? "Integer.MAX_VALUE" : "Integer.MIN_VALUE"; - errln("set(" + Koyomi.getFieldName(field) + ", " + s + ") failed." + " got " + time2 + fail("set(" + Koyomi.getFieldName(field) + ", " + s + ") failed." + " got " + time2 + ", expected " + (time + expectedDelta)); } } @@ -2222,6 +2274,7 @@ private void checkTimeCalculation(Koyomi cal, int field, int value, long expecte * 4722650: Calendar.equals can throw an exception in non-lenient * (piggy-back tests for compareTo() which is new in 1.5) */ + @Test public void Test4722650() { Calendar cal1 = new GregorianCalendar(); cal1.clear(); @@ -2233,26 +2286,26 @@ public void Test4722650() { cal2.set(2003, OCTOBER, 31); try { if (cal1.equals(cal2)) { - errln("lenient and non-lenient shouldn't be equal. (2003/10/31)"); + fail("lenient and non-lenient shouldn't be equal. (2003/10/31)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 and cal2 should represent the same time. (2003/10/31)"); + fail("cal1 and cal2 should represent the same time. (2003/10/31)"); } } catch (IllegalArgumentException e) { - errln("equals threw IllegalArugumentException with non-lenient"); + fail("equals threw IllegalArugumentException with non-lenient"); } cal1.set(2003, OCTOBER, 32); cal2.set(2003, OCTOBER, 32); try { if (cal1.equals(cal2)) { - errln("lenient and non-lenient shouldn't be equal. (2003/10/32)"); + fail("lenient and non-lenient shouldn't be equal. (2003/10/32)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 and cal2 should represent the same time. (2003/10/32)"); + fail("cal1 and cal2 should represent the same time. (2003/10/32)"); } } catch (IllegalArgumentException e) { - errln("equals threw IllegalArugumentException with non-lenient"); + fail("equals threw IllegalArugumentException with non-lenient"); } cal1 = Calendar.getInstance(new Locale("th", "TH")); @@ -2260,48 +2313,49 @@ public void Test4722650() { cal2 = Calendar.getInstance(Locale.US); cal2.setTimeInMillis(0L); if (cal1.equals(cal2)) { - errln("Buddhist.equals(Gregorian) shouldn't be true. (millis=0)"); + fail("Buddhist.equals(Gregorian) shouldn't be true. (millis=0)"); } if (cal1.compareTo(cal2) != 0) { - errln("cal1 (Buddhist) and cal2 (Gregorian) should represent the same time. (millis=0)"); + fail("cal1 (Buddhist) and cal2 (Gregorian) should represent the same time. (millis=0)"); } } /** * 4738710: API: Calendar comparison methods should be improved */ + @Test public void Test4738710() { Calendar cal0 = new GregorianCalendar(2003, SEPTEMBER, 30); Comparable cal1 = new GregorianCalendar(2003, OCTOBER, 1); Calendar cal2 = new GregorianCalendar(2003, OCTOBER, 2); if (!(cal1.compareTo(cal0) > 0)) { - errln("!(cal1 > cal0)"); + fail("!(cal1 > cal0)"); } if (!(cal1.compareTo(cal2) < 0)) { - errln("!(cal1 < cal2)"); + fail("!(cal1 < cal2)"); } if (cal1.compareTo(new GregorianCalendar(2003, OCTOBER, 1)) != 0) { - errln("cal1 != new GregorianCalendar(2003, OCTOBER, 1)"); + fail("cal1 != new GregorianCalendar(2003, OCTOBER, 1)"); } if (cal0.after(cal2)) { - errln("cal0 shouldn't be after cal2"); + fail("cal0 shouldn't be after cal2"); } if (cal2.before(cal0)) { - errln("cal2 shouldn't be before cal0"); + fail("cal2 shouldn't be before cal0"); } if (cal0.after(0)) { - errln("cal0.after() returned true with an Integer."); + fail("cal0.after() returned true with an Integer."); } if (cal0.before(0)) { - errln("cal0.before() returned true with an Integer."); + fail("cal0.before() returned true with an Integer."); } if (cal0.after(null)) { - errln("cal0.after() returned true with null."); + fail("cal0.after() returned true with null."); } if (cal0.before(null)) { - errln("cal0.before() returned true with null."); + fail("cal0.before() returned true with null."); } } @@ -2309,6 +2363,7 @@ public void Test4738710() { * 4633646: Setting WEEK_OF_MONTH to 1 results in incorrect date */ @SuppressWarnings("deprecation") + @Test public void Test4633646() { Koyomi cal = new Koyomi(Locale.US); cal.setTime(new Date(2002 - 1900, 1 - 1, 28)); @@ -2334,15 +2389,15 @@ void sub4633646(Koyomi cal) { cal.set(WEEK_OF_MONTH, 1); if (cal.isLenient()) { if (!cal.checkDate(2001, DECEMBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_MONTH, 6)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } else { try { Date d = cal.getTime(); - errln("didn't throw IllegalArgumentException in non-lenient"); + fail("didn't throw IllegalArgumentException in non-lenient"); } catch (IllegalArgumentException e) { } } @@ -2352,6 +2407,7 @@ void sub4633646(Koyomi cal) { * 4846659: Calendar: Both set() and roll() don't work for AM_PM time field * (Partially fixed only roll as of 1.5) */ + @Test public void Test4846659() { Koyomi cal = new Koyomi(); cal.clear(); @@ -2360,7 +2416,7 @@ public void Test4846659() { // Test roll() cal.roll(AM_PM, +1); // should turn to PM if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { - errln("roll: AM_PM didn't change to PM"); + fail("roll: AM_PM didn't change to PM"); } cal.clear(); @@ -2369,7 +2425,7 @@ public void Test4846659() { // Test set() cal.set(AM_PM, PM); // should turn to PM if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { - errln("set: AM_PM didn't change to PM"); + fail("set: AM_PM didn't change to PM"); } cal.clear(); @@ -2378,13 +2434,14 @@ public void Test4846659() { cal.set(AM_PM, PM); cal.set(HOUR, 9); if (!cal.checkFieldValue(HOUR_OF_DAY, 9 + 12)) { - errln("set: both AM_PM and HOUT didn't change to PM"); + fail("set: both AM_PM and HOUT didn't change to PM"); } } /** * 4822110: GregorianCalendar.get() returns an incorrect date after setFirstDayOfWeek() */ + @Test public void Test4822110() { Koyomi cal = new Koyomi(Locale.US); // June 2003 @@ -2401,17 +2458,18 @@ public void Test4822110() { cal.setFirstDayOfWeek(MONDAY); // Now 6/2 to 6/8 should be the 2nd week of June. Sunday of // that week is 6/8. - logln("1: " + cal.get(WEEK_OF_MONTH) + ", " + cal.get(DAY_OF_MONTH)); + System.out.println("1: " + cal.get(WEEK_OF_MONTH) + ", " + cal.get(DAY_OF_MONTH)); cal.set(DAY_OF_WEEK, SUNDAY); - logln("1st Sunday of June 2003 with FirstDayOfWeek=MONDAY"); + System.out.println("1st Sunday of June 2003 with FirstDayOfWeek=MONDAY"); if (!cal.checkDate(2003, JUNE, 8)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /** * 4973919: Inconsistent GregorianCalendar hashCode before and after serialization */ + @Test public void Test4966499() throws Exception { GregorianCalendar date1 = new GregorianCalendar(2004, JANUARY, 7); @@ -2428,10 +2486,10 @@ public void Test4966499() throws Exception { GregorianCalendar date2 = (GregorianCalendar) ois.readObject(); if (!date1.equals(date2)) { - errln("date1.equals(date2) != true"); + fail("date1.equals(date2) != true"); } if (date1.hashCode() != date2.hashCode()) { - errln("inconsistent hashCode() value (before=0x" + fail("inconsistent hashCode() value (before=0x" + Integer.toHexString(date1.hashCode()) + ", after=0x" + Integer.toHexString(date2.hashCode()) + ")"); } @@ -2440,54 +2498,56 @@ public void Test4966499() throws Exception { /** * 4980088: GregorianCalendar.getActualMaximum doesn't throw exception */ + @Test public void Test4980088() { GregorianCalendar cal = new GregorianCalendar(); try { int x = cal.getMaximum(100); - errln("getMaximum(100) didn't throw an exception."); + fail("getMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getLeastMaximum(100); - errln("getLeastMaximum(100) didn't throw an exception."); + fail("getLeastMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getLeastMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getLeastMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getActualMaximum(100); - errln("getActualMaximum(100) didn't throw an exception."); + fail("getActualMaximum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getActualMaximum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getActualMaximum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getMinimum(100); - errln("getMinimum(100) didn't throw an exception."); + fail("getMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getGreatestMinimum(100); - errln("getGreatestMinimum(100) didn't throw an exception."); + fail("getGreatestMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getGreatestMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getGreatestMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } try { int x = cal.getActualMinimum(100); - errln("getActualMinimum(100) didn't throw an exception."); + fail("getActualMinimum(100) didn't throw an exception."); } catch (IndexOutOfBoundsException e) { - logln("getActualMinimum: " + e.getClass().getName() + ": " + e.getMessage()); + System.out.println("getActualMinimum: " + e.getClass().getName() + ": " + e.getMessage()); } } /** * 4965624: GregorianCalendar.isLeapYear(1000) returns incorrect value */ + @Test public void Test4965624() { // 5013094: This test case needs to use "GMT" to specify // Gregorian cutover dates. @@ -2509,7 +2569,7 @@ public void Test4965624() { GregorianCalendar cal = new GregorianCalendar(); cal.setGregorianChange(d); if (cal.isLeapYear(1000) != expected) { - errln("isLeapYear(1000) returned " + cal.isLeapYear(1000) + fail("isLeapYear(1000) returned " + cal.isLeapYear(1000) + " with cutover date (Julian) " + d); } }); @@ -2532,16 +2592,17 @@ static Date getGregorianDate(int year, int month, int dayOfMonth) { /** * 5006864: Define the minimum value of DAY_OF_WEEK_IN_MONTH as 1 */ + @Test public void Test5006864() { GregorianCalendar cal = new GregorianCalendar(); int min = cal.getMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { - errln("GregorianCalendar.getMinimum(DAY_OF_WEEK_IN_MONTH) returned " + fail("GregorianCalendar.getMinimum(DAY_OF_WEEK_IN_MONTH) returned " + min + ", expected 1."); } min = cal.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { - errln("GregorianCalendar.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH) returned " + fail("GregorianCalendar.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH) returned " + min + ", expected 1."); } } diff --git a/test/jdk/java/util/Calendar/CalendarTest.java b/test/jdk/java/util/Calendar/CalendarTest.java index 432d31b8d54..91a7ad813d3 100644 --- a/test/jdk/java/util/Calendar/CalendarTest.java +++ b/test/jdk/java/util/Calendar/CalendarTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,7 +27,7 @@ * @summary test for Calendar * @library /java/text/testlib * @modules java.base/java.util:+open - * @run main CalendarTest + * @run junit CalendarTest * @key randomness */ @@ -48,18 +48,19 @@ import static java.util.Calendar.*; -public class CalendarTest extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class CalendarTest { static final int ONE_DAY = 24 * 60 * 60 * 1000; static final int EPOCH_JULIAN = 2440588; - public static void main(String argv[]) throws Exception { - new CalendarTest().run(argv); - } - /** * Test the behavior of the GregorianCalendar around the changeover. */ + @Test public void TestGregorianChangeover() { TimeZone savedZone = TimeZone.getDefault(); /* @@ -97,10 +98,10 @@ public void TestGregorianChangeover() { int dom = cal.get(DATE); int dow = cal.get(DAY_OF_WEEK); - logln("Changeover " + (i >= 0 ? "+" : "") + i + System.out.println("Changeover " + (i >= 0 ? "+" : "") + i + " days: " + y + "/" + mon + "/" + dom + " dow=" + dow); if (y != 1582 || mon != MON[j] || dom != DOM[j] || dow != DOW[j]) { - errln(" Fail: Above line is wrong"); + fail(" Fail: Above line is wrong"); } } } finally { @@ -114,6 +115,7 @@ public void TestGregorianChangeover() { * (first day of week, minimal days in first week). */ @SuppressWarnings("deprecation") + @Test public void TestMapping() { TimeZone saveZone = TimeZone.getDefault(); int[] DATA = { @@ -160,9 +162,9 @@ public void TestMapping() { + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; if (delta != 0 || year != year2 || month != month2 || dom != dom2) { - errln(s + " FAIL"); + fail(s + " FAIL"); } else { - logln(s); + System.out.println(s); } // Test Julian computation @@ -184,9 +186,9 @@ public void TestMapping() { + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; if (delta != 0 || year != year2 || month != month2 || dom != dom2) { - errln(s + " FAIL"); + fail(s + " FAIL"); } else { - logln(s); + System.out.println(s); } } @@ -212,16 +214,17 @@ private void auxMapping(Calendar cal, int y, int m, int d) { int month2 = cal.get(MONTH); int dom2 = cal.get(DAY_OF_MONTH); if (y != year2 || m != month2 || dom2 != d) { - errln("Round-trip failure: " + y + "-" + (m + 1) + "-" + d + " =>ms=> " + fail("Round-trip failure: " + y + "-" + (m + 1) + "-" + d + " =>ms=> " + year2 + "-" + (month2 + 1) + "-" + dom2); } } @SuppressWarnings("deprecation") + @Test public void TestGenericAPI() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -235,7 +238,7 @@ public void TestGenericAPI() { Calendar cal = Calendar.getInstance((SimpleTimeZone) zone.clone()); if (!zone.equals(cal.getTimeZone())) { - errln("FAIL: Calendar.getTimeZone failed"); + fail("FAIL: Calendar.getTimeZone failed"); } Calendar cal2 = Calendar.getInstance(cal.getTimeZone()); @@ -244,27 +247,27 @@ public void TestGenericAPI() { cal2.setTime(when); if (!(cal.equals(cal2))) { - errln("FAIL: Calendar.operator== failed"); + fail("FAIL: Calendar.operator== failed"); } // if ((*cal != *cal2)) errln("FAIL: Calendar.operator!= failed"); if (!cal.equals(cal2) || cal.before(cal2) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } cal2.setTime(new Date(when.getTime() + 1000)); if (cal.equals(cal2) || cal2.before(cal) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } cal.roll(SECOND, true); if (!cal.equals(cal2) || cal.before(cal2) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } // Roll back to January @@ -272,20 +275,20 @@ public void TestGenericAPI() { if (cal.equals(cal2) || cal2.before(cal) || cal.after(cal2)) { - errln("FAIL: equals/before/after failed"); + fail("FAIL: equals/before/after failed"); } // C++ only /* TimeZone z = cal.orphanTimeZone(); if (z.getID(str) != tzid || z.getRawOffset() != tzoffset) - errln("FAIL: orphanTimeZone failed"); + fail("FAIL: orphanTimeZone failed"); */ for (int i = 0; i < 2; ++i) { boolean lenient = (i > 0); cal.setLenient(lenient); if (lenient != cal.isLenient()) { - errln("FAIL: setLenient/isLenient failed"); + fail("FAIL: setLenient/isLenient failed"); } // Later: Check for lenient behavior } @@ -294,26 +297,26 @@ public void TestGenericAPI() { for (i = SUNDAY; i <= SATURDAY; ++i) { cal.setFirstDayOfWeek(i); if (cal.getFirstDayOfWeek() != i) { - errln("FAIL: set/getFirstDayOfWeek failed"); + fail("FAIL: set/getFirstDayOfWeek failed"); } } for (i = 0; i <= 7; ++i) { cal.setMinimalDaysInFirstWeek(i); if (cal.getMinimalDaysInFirstWeek() != i) { - errln("FAIL: set/getFirstDayOfWeek failed"); + fail("FAIL: set/getFirstDayOfWeek failed"); } } for (i = 0; i < FIELD_COUNT; ++i) { if (cal.getMinimum(i) != cal.getGreatestMinimum(i)) { - errln("FAIL: getMinimum doesn't match getGreatestMinimum for field " + i); + fail("FAIL: getMinimum doesn't match getGreatestMinimum for field " + i); } if (cal.getLeastMaximum(i) > cal.getMaximum(i)) { - errln("FAIL: getLeastMaximum larger than getMaximum for field " + i); + fail("FAIL: getLeastMaximum larger than getMaximum for field " + i); } if (cal.getMinimum(i) >= cal.getMaximum(i)) { - errln("FAIL: getMinimum not less than getMaximum for field " + i); + fail("FAIL: getMinimum not less than getMaximum for field " + i); } } @@ -321,22 +324,22 @@ public void TestGenericAPI() { cal.clear(); cal.set(1984, 5, 24); if (cal.getTime().getTime() != new Date(84, 5, 24).getTime()) { - errln("FAIL: Calendar.set(3 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(84, 5, 24)); + fail("FAIL: Calendar.set(3 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(84, 5, 24)); } cal.clear(); cal.set(1985, 3, 2, 11, 49); if (cal.getTime().getTime() != new Date(85, 3, 2, 11, 49).getTime()) { - errln("FAIL: Calendar.set(5 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(85, 3, 2, 11, 49)); + fail("FAIL: Calendar.set(5 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(85, 3, 2, 11, 49)); } cal.clear(); cal.set(1995, 9, 12, 1, 39, 55); if (cal.getTime().getTime() != new Date(95, 9, 12, 1, 39, 55).getTime()) { - errln("FAIL: Calendar.set(6 args) failed"); - logln(" Got: " + cal.getTime() + " Expected: " + new Date(95, 9, 12, 1, 39, 55)); + fail("FAIL: Calendar.set(6 args) failed"); + System.out.println(" Got: " + cal.getTime() + " Expected: " + new Date(95, 9, 12, 1, 39, 55)); } cal.getTime(); @@ -349,17 +352,17 @@ public void TestGenericAPI() { case MINUTE: case SECOND: if (!cal.isSet(i)) { - errln("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); + fail("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); } break; default: if (cal.isSet(i)) { - errln("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); + fail("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); } } cal.clear(i); if (cal.isSet(i)) { - errln("FAIL: Calendar.clear/isSet failed"); + fail("FAIL: Calendar.clear/isSet failed"); } } @@ -368,7 +371,7 @@ public void TestGenericAPI() { Locale[] loc = Calendar.getAvailableLocales(); long count = loc.length; if (count < 1 || loc == null) { - errln("FAIL: getAvailableLocales failed"); + fail("FAIL: getAvailableLocales failed"); } else { for (i = 0; i < count; ++i) { cal = Calendar.getInstance(loc[i]); @@ -399,13 +402,13 @@ public void TestGenericAPI() { gc = new GregorianCalendar(1998, 10, 14, 21, 43); if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43).getTime()) { - errln("FAIL: new GregorianCalendar(ymdhm) failed"); + fail("FAIL: new GregorianCalendar(ymdhm) failed"); } // delete gc; gc = new GregorianCalendar(1998, 10, 14, 21, 43, 55); if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43, 55).getTime()) { - errln("FAIL: new GregorianCalendar(ymdhms) failed"); + fail("FAIL: new GregorianCalendar(ymdhms) failed"); } // C++ only: @@ -417,6 +420,7 @@ public void TestGenericAPI() { } // Verify Roger Webster's bug + @Test public void TestRog() { GregorianCalendar gc = new GregorianCalendar(); @@ -432,12 +436,13 @@ public void TestRog() { if (gc.get(YEAR) != year || gc.get(MONTH) != month || gc.get(DATE) != (date + i)) { - errln("FAIL: Date " + gc.getTime() + " wrong"); + fail("FAIL: Date " + gc.getTime() + " wrong"); } } } // Verify DAY_OF_WEEK + @Test public void TestDOW943() { dowTest(false); dowTest(true); @@ -453,18 +458,19 @@ void dowTest(boolean lenient) { int min = cal.getMinimum(DAY_OF_WEEK); int max = cal.getMaximum(DAY_OF_WEEK); if (dow < min || dow > max) { - errln("FAIL: Day of week " + dow + " out of range"); + fail("FAIL: Day of week " + dow + " out of range"); } if (dow != SUNDAY) { - errln("FAIL2: Day of week should be SUNDAY; is " + dow + ": " + cal.getTime()); + fail("FAIL2: Day of week should be SUNDAY; is " + dow + ": " + cal.getTime()); } if (min != SUNDAY || max != SATURDAY) { - errln("FAIL: Min/max bad"); + fail("FAIL: Min/max bad"); } } // Verify that the clone method produces distinct objects with no // unintentionally shared fields. + @Test public void TestClonesUnique908() { Calendar c = Calendar.getInstance(); Calendar d = (Calendar) c.clone(); @@ -472,31 +478,33 @@ public void TestClonesUnique908() { d.set(MILLISECOND, 456); if (c.get(MILLISECOND) != 123 || d.get(MILLISECOND) != 456) { - errln("FAIL: Clones share fields"); + fail("FAIL: Clones share fields"); } } // Verify effect of Gregorian cutoff value @SuppressWarnings("deprecation") + @Test public void TestGregorianChange768() { boolean b; GregorianCalendar c = new GregorianCalendar(); - logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); - logln(" (should be FALSE)"); + System.out.println("With cutoff " + c.getGregorianChange()); + System.out.println(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); + System.out.println(" (should be FALSE)"); if (b != false) { - errln("FAIL"); + fail("FAIL"); } c.setGregorianChange(new Date(0, 0, 1)); // Jan 1 1900 - logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); - logln(" (should be TRUE)"); + System.out.println("With cutoff " + c.getGregorianChange()); + System.out.println(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); + System.out.println(" (should be TRUE)"); if (b != true) { - errln("FAIL"); + fail("FAIL"); } } // Test the correct behavior of the disambiguation algorithm. + @Test public void TestDisambiguation765() throws Exception { Locale savedLocale = Locale.getDefault(); try { @@ -562,7 +570,7 @@ public void TestDisambiguation765() throws Exception { c.set(WEEK_OF_MONTH, 1); verify765("1997 Tuesday in week 0 of June = ", c, 1997, JUNE, 3); } catch (IllegalArgumentException ex) { - errln("FAIL: Exception seen: " + ex.getMessage()); + fail("FAIL: Exception seen: " + ex.getMessage()); // ex.printStackTrace(log); } @@ -596,9 +604,9 @@ void verify765(String msg, Calendar c, int year, int month, int day) { if (c.get(YEAR) == year && c.get(MONTH) == month && c.get(DATE) == day) { - logln("PASS: " + msg + c.getTime()); + System.out.println("PASS: " + msg + c.getTime()); } else { - errln("FAIL: " + msg + c.getTime() + fail("FAIL: " + msg + c.getTime() + "; expected " + year + "/" + (month + 1) + "/" + day); } @@ -607,17 +615,18 @@ void verify765(String msg, Calendar c, int year, int month, int day) { // Called when e expected to be non-null void verify765(String msg, IllegalArgumentException e) { if (e == null) { - errln("FAIL: No IllegalArgumentException for " + msg); + fail("FAIL: No IllegalArgumentException for " + msg); } else { - logln("PASS: " + msg + "IllegalArgument as expected"); + System.out.println("PASS: " + msg + "IllegalArgument as expected"); } } // Test the behavior of GMT vs. local time + @Test public void TestGMTvsLocal4064654() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -645,7 +654,7 @@ void test4064654(int yr, int mo, int dt, int hr, int mn, int sc) { gmtcal.set(MILLISECOND, 0); date = gmtcal.getTime(); - logln("date = " + date); + System.out.println("date = " + date); Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); @@ -658,7 +667,7 @@ void test4064654(int yr, int mo, int dt, int hr, int mn, int sc) { cal.get(DAY_OF_WEEK), cal.get(MILLISECOND)); - logln("offset for " + date + "= " + (offset / 1000 / 60 / 60.0) + "hr"); + System.out.println("offset for " + date + "= " + (offset / 1000 / 60 / 60.0) + "hr"); int utc = ((cal.get(HOUR_OF_DAY) * 60 + cal.get(MINUTE)) * 60 @@ -668,7 +677,7 @@ void test4064654(int yr, int mo, int dt, int hr, int mn, int sc) { int expected = ((hr * 60 + mn) * 60 + sc) * 1000; if (utc != expected) { - errln("FAIL: Discrepancy of " + fail("FAIL: Discrepancy of " + (utc - expected) + " millis = " + ((utc - expected) / 1000 / 60 / 60.0) + " hr"); } @@ -676,6 +685,7 @@ void test4064654(int yr, int mo, int dt, int hr, int mn, int sc) { // Verify that add and set work regardless of the order in which // they are called. + @Test public void TestAddSetOrder621() { @SuppressWarnings("deprecation") Date d = new Date(97, 4, 14, 13, 23, 45); @@ -699,13 +709,14 @@ public void TestAddSetOrder621() { String s2 = cal.getTime().toString(); if (s.equals(s2)) { - logln("Pass: " + s + " == " + s2); + System.out.println("Pass: " + s + " == " + s2); } else { - errln("FAIL: " + s + " != " + s2); + fail("FAIL: " + s + " != " + s2); } } // Verify that add works. + @Test public void TestAdd520() { int y = 1997, m = FEBRUARY, d = 1; GregorianCalendar temp = new GregorianCalendar(y, m, d); @@ -737,19 +748,20 @@ void check520(Calendar c, int y, int m, int d) { if (c.get(YEAR) != y || c.get(MONTH) != m || c.get(DATE) != d) { - errln("FAILURE: Expected YEAR/MONTH/DATE of " + fail("FAILURE: Expected YEAR/MONTH/DATE of " + y + "/" + (m + 1) + "/" + d + "; got " + c.get(YEAR) + "/" + (c.get(MONTH) + 1) + "/" + c.get(DATE)); } else { - logln("Confirmed: " + System.out.println("Confirmed: " + y + "/" + (m + 1) + "/" + d); } } // Verify that setting fields works. This test fails when an exception is thrown. + @Test public void TestFieldSet4781() { try { GregorianCalendar g = new GregorianCalendar(); @@ -763,16 +775,17 @@ public void TestFieldSet4781() { // The following line will result in IllegalArgumentException because // it thinks the YEAR is set and it is NOT. if (g2.equals(g)) { - logln("Same"); + System.out.println("Same"); } else { - logln("Different"); + System.out.println("Different"); } } catch (IllegalArgumentException e) { - errln("Unexpected exception seen: " + e); + fail("Unexpected exception seen: " + e); } } // Test serialization of a Calendar object + @Test public void TestSerialize337() { Calendar cal = Calendar.getInstance(); @@ -800,15 +813,15 @@ public void TestSerialize337() { File fl = new File(FILENAME); fl.delete(); } catch (IOException e) { - errln("FAIL: Exception received:"); + fail("FAIL: Exception received:"); // e.printStackTrace(log); } catch (ClassNotFoundException e) { - errln("FAIL: Exception received:"); + fail("FAIL: Exception received:"); // e.printStackTrace(log); } if (!ok) { - errln("Serialization of Calendar object failed."); + fail("Serialization of Calendar object failed."); } } static final String PREFIX = "abc"; @@ -816,6 +829,7 @@ public void TestSerialize337() { static final String FILENAME = "tmp337.bin"; // Try to zero out the seconds field + @Test public void TestSecondsZero121() { Calendar cal = new GregorianCalendar(); // Initialize with current date/time @@ -825,11 +839,12 @@ public void TestSecondsZero121() { Date d = cal.getTime(); String s = d.toString(); if (s.indexOf(":00 ") < 0) { - errln("Expected to see :00 in " + s); + fail("Expected to see :00 in " + s); } } // Try various sequences of add, set, and get method calls. + @Test public void TestAddSetGet0610() { // // Error case 1: @@ -840,13 +855,13 @@ public void TestAddSetGet0610() { { Calendar calendar = new GregorianCalendar(); calendar.set(1993, JANUARY, 4); - logln("1A) " + value(calendar)); + System.out.println("1A) " + value(calendar)); calendar.add(DATE, 1); String v = value(calendar); - logln("1B) " + v); - logln("--) 1993/0/5"); + System.out.println("1B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -858,13 +873,13 @@ public void TestAddSetGet0610() { // { Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); - logln("2A) " + value(calendar)); + System.out.println("2A) " + value(calendar)); calendar.add(DATE, 1); String v = value(calendar); - logln("2B) " + v); - logln("--) 1993/0/5"); + System.out.println("2B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -877,14 +892,14 @@ public void TestAddSetGet0610() { // { Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); - logln("3A) " + value(calendar)); + System.out.println("3A) " + value(calendar)); calendar.getTime(); calendar.add(DATE, 1); String v = value(calendar); - logln("3B) " + v); - logln("--) 1993/0/5"); + System.out.println("3B) " + v); + System.out.println("--) 1993/0/5"); if (!v.equals(EXPECTED_0610)) { - errln("Expected " + EXPECTED_0610 + fail("Expected " + EXPECTED_0610 + "; saw " + v); } } @@ -897,6 +912,7 @@ static String value(Calendar calendar) { static String EXPECTED_0610 = "1993/0/5"; // Test that certain fields on a certain date are as expected. + @Test public void TestFields060() { int year = 1997; int month = OCTOBER; //october @@ -908,7 +924,7 @@ public void TestFields060() { int field = EXPECTED_FIELDS[i++]; int expected = EXPECTED_FIELDS[i++]; if (calendar.get(field) != expected) { - errln("Expected field " + field + " to have value " + expected + fail("Expected field " + field + " to have value " + expected + "; received " + calendar.get(field) + " instead"); } } @@ -942,6 +958,7 @@ public void TestFields060() { // Verify that the fields are as expected (mostly zero) at the epoch start. // Note that we adjust for the default timezone to get most things to zero. + @Test public void TestEpochStartFields() { String[][] lt = { {"en", "US", "US/Pacific"}, /* First day = 1, Minimum day = 1 */ @@ -988,14 +1005,14 @@ public void TestEpochStartFields() { boolean err = false; for (int i = 0; i < calendarFieldNames.length; ++i) { if ((val = c.get(i)) != EPOCH_FIELDS[i]) { - errln("Wrong value: " + val + fail("Wrong value: " + val + " for field(" + calendarFieldNames[i] + "), expected: " + EPOCH_FIELDS[i]); err = true; } } if (err) { - errln("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + fail("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + "\n\tLocale=" + l + "\n\tCalendar=" + c); } } @@ -1007,6 +1024,7 @@ public void TestEpochStartFields() { // Verify that as you add days to the calendar (e.g., 24 day periods), // the day of the week shifts in the expected pattern. + @Test public void TestDOWProgression() { Calendar cal = new GregorianCalendar(1972, OCTOBER, 26); @@ -1020,66 +1038,68 @@ void marchByDelta(Calendar cal, int delta) { int DOW, newDOW = initialDOW; do { DOW = newDOW; - logln("DOW = " + DOW + " " + cur.getTime()); + System.out.println("DOW = " + DOW + " " + cur.getTime()); cur.add(DAY_OF_WEEK, delta); newDOW = cur.get(DAY_OF_WEEK); int expectedDOW = 1 + (DOW + delta - 1) % 7; if (newDOW != expectedDOW) { - errln("Day of week should be " + expectedDOW + fail("Day of week should be " + expectedDOW + " instead of " + newDOW + " on " + cur.getTime()); return; } } while (newDOW != initialDOW); } + @Test public void TestActualMinMax() { Calendar cal = new GregorianCalendar(1967, MARCH, 10); cal.setFirstDayOfWeek(SUNDAY); cal.setMinimalDaysInFirstWeek(3); if (cal.getActualMinimum(DAY_OF_MONTH) != 1) { - errln("Actual minimum date for 3/10/1967 should have been 1; got " + fail("Actual minimum date for 3/10/1967 should have been 1; got " + cal.getActualMinimum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_MONTH) != 31) { - errln("Actual maximum date for 3/10/1967 should have been 31; got " + fail("Actual maximum date for 3/10/1967 should have been 31; got " + cal.getActualMaximum(DAY_OF_MONTH)); } cal.set(MONTH, FEBRUARY); if (cal.getActualMaximum(DAY_OF_MONTH) != 28) { - errln("Actual maximum date for 2/10/1967 should have been 28; got " + fail("Actual maximum date for 2/10/1967 should have been 28; got " + cal.getActualMaximum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_YEAR) != 365) { - errln("Number of days in 1967 should have been 365; got " + fail("Number of days in 1967 should have been 365; got " + cal.getActualMaximum(DAY_OF_YEAR)); } cal.set(YEAR, 1968); if (cal.getActualMaximum(DAY_OF_MONTH) != 29) { - errln("Actual maximum date for 2/10/1968 should have been 29; got " + fail("Actual maximum date for 2/10/1968 should have been 29; got " + cal.getActualMaximum(DAY_OF_MONTH)); } if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { - errln("Number of days in 1968 should have been 366; got " + fail("Number of days in 1968 should have been 366; got " + cal.getActualMaximum(DAY_OF_YEAR)); } // Using week settings of SUNDAY/3 (see above) if (cal.getActualMaximum(WEEK_OF_YEAR) != 52) { - errln("Number of weeks in 1968 should have been 52; got " + fail("Number of weeks in 1968 should have been 52; got " + cal.getActualMaximum(WEEK_OF_YEAR)); } cal.set(YEAR, 1976); // Using week settings of SUNDAY/3 (see above) if (cal.getActualMaximum(WEEK_OF_YEAR) != 53) { - errln("Number of weeks in 1976 should have been 53; got " + fail("Number of weeks in 1976 should have been 53; got " + cal.getActualMaximum(WEEK_OF_YEAR)); } } + @Test public void TestRoll() { Calendar cal = new GregorianCalendar(1997, JANUARY, 31); @@ -1089,7 +1109,7 @@ public void TestRoll() { Calendar cal2 = (Calendar) cal.clone(); cal2.roll(MONTH, i); if (cal2.get(DAY_OF_MONTH) != dayValues[i]) { - errln("Rolling the month in 1/31/1997 up by " + i + " should have yielded " + fail("Rolling the month in 1/31/1997 up by " + i + " should have yielded " + ((i + 1) % 12) + "/" + dayValues[i] + "/1997, but actually yielded " + ((i + 1) % 12) + "/" + cal2.get(DAY_OF_MONTH) + "/1997."); } @@ -1105,7 +1125,7 @@ public void TestRoll() { cal2.roll(YEAR, i); if (cal2.get(DAY_OF_MONTH) != dayValues2[i] || cal2.get(MONTH) != monthValues[i]) { - errln("Rolling the year in 2/29/1996 up by " + i + " should have yielded " + fail("Rolling the year in 2/29/1996 up by " + i + " should have yielded " + (monthValues[i] + 1) + "/" + dayValues2[i] + "/" + (1996 + i) + ", but actually yielded " + (cal2.get(MONTH) + 1) + "/" @@ -1118,17 +1138,17 @@ public void TestRoll() { cal.roll(HOUR_OF_DAY, -2); int f = cal.get(HOUR_OF_DAY); if (f != 22) { - errln("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); + fail("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); } cal.roll(HOUR_OF_DAY, 5); f = cal.get(HOUR_OF_DAY); if (f != 3) { - errln("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); + fail("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); } cal.roll(HOUR_OF_DAY, 21); f = cal.get(HOUR_OF_DAY); if (f != 0) { - errln("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); + fail("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); } // Test rolling hour @@ -1136,23 +1156,24 @@ public void TestRoll() { cal.roll(HOUR, -2); f = cal.get(HOUR); if (f != 10) { - errln("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); + fail("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); } cal.roll(HOUR, 5); f = cal.get(HOUR); if (f != 3) { - errln("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); + fail("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); } cal.roll(HOUR, 9); f = cal.get(HOUR); if (f != 0) { - errln("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); + fail("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); } } /* * Confirm that multiple calls to Calendar.set() works correctly. */ + @Test public void Test4374886() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -1171,7 +1192,7 @@ public void Test4374886() { || cal.get(MONTH) != JANUARY || cal.get(DATE) != 22 || cal.get(DAY_OF_WEEK) != MONDAY) { - errln("Failed : got " + cal.getTime() + ", expected Mon Jan 22, 2001"); + fail("Failed : got " + cal.getTime() + ", expected Mon Jan 22, 2001"); } } finally { Locale.setDefault(savedLocale); @@ -1179,6 +1200,7 @@ public void Test4374886() { } } + @Test public void TestClonedSharedZones() throws NoSuchFieldException, IllegalAccessException { Field zone = Calendar.class.getDeclaredField("zone"); zone.setAccessible(true); @@ -1191,13 +1213,13 @@ public void TestClonedSharedZones() throws NoSuchFieldException, IllegalAccessEx // c1 should have a shared zone if (!sharedZone.getBoolean(c1)) { - errln("Failed : c1.sharedZone == false"); + fail("Failed : c1.sharedZone == false"); } else { // c2 should have a shared zone too if (!sharedZone.getBoolean(c2)) { - errln("Failed : c2.sharedZone == false"); + fail("Failed : c2.sharedZone == false"); } else if (zone.get(c1) != zone.get(c2)) { - errln("Failed : c1.zone != c2.zone"); + fail("Failed : c1.zone != c2.zone"); } } } diff --git a/test/jdk/java/util/Calendar/FieldStateTest.java b/test/jdk/java/util/Calendar/FieldStateTest.java index 9fe5e7fc472..6b4632c13e1 100644 --- a/test/jdk/java/util/Calendar/FieldStateTest.java +++ b/test/jdk/java/util/Calendar/FieldStateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,9 +24,7 @@ /* * @test * @bug 4860664 4916815 4867075 - * @library /java/text/testlib - * @build Koyomi - * @run main FieldStateTest + * @run junit/othervm FieldStateTest * @summary Unit tests for internal fields states. */ @@ -36,31 +34,30 @@ import static java.util.Calendar.*; -public class FieldStateTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - Locale reservedLocale = Locale.getDefault(); - TimeZone reservedTimeZone = TimeZone.getDefault(); - try { - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - Locale.setDefault(Locale.US); +import static org.junit.jupiter.api.Assertions.fail; - new FieldStateTest().run(args); - } finally { - // restore the reserved locale and time zone - Locale.setDefault(reservedLocale); - TimeZone.setDefault(reservedTimeZone); - } +public class FieldStateTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } + + @Test public void TestFieldState() { Koyomi cal = new Koyomi(); - logln("Right after instantialtion:"); + System.out.println("Right after instantialtion:"); if (!cal.checkAllSet()) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set date to 2003/10/31 after the instantiation:"); + System.out.println("Set date to 2003/10/31 after the instantiation:"); cal.set(2003, OCTOBER, 31); // let cal calculate the time cal.getTime(); @@ -70,18 +67,18 @@ public void TestFieldState() { // the fields have "computed". But we can't distinguish them // outside the package. if (!cal.checkAllSet()) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // Make sure that the correct date was produced. if (!cal.checkInternalDate(2003, OCTOBER, 31, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Change to Monday of the week, which is 2003/10/27:"); + System.out.println("Change to Monday of the week, which is 2003/10/27:"); cal.set(DAY_OF_WEEK, MONDAY); cal.getTime(); if (!cal.checkDate(2003, OCTOBER, 27)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // The same operation didn't work after calling clear() before @@ -89,28 +86,28 @@ public void TestFieldState() { // operations. After the instantiation, all the fields are set // to "computed". But after calling clear(), the state becomes // "unset". - logln("Set to 2003/10/31 after clear():"); + System.out.println("Set to 2003/10/31 after clear():"); cal.clear(); cal.set(2003, OCTOBER, 31); cal.getTime(); cal.set(DAY_OF_WEEK, MONDAY); if (!cal.checkDate(2003, OCTOBER, 27, MONDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10/31 after clear(), then to the 51st week of year (12/19):"); + System.out.println("Set to 2003/10/31 after clear(), then to the 51st week of year (12/19):"); cal.clear(); cal.set(2003, OCTOBER, 31); cal.getTime(); cal.set(WEEK_OF_YEAR, 51); if (!cal.checkFieldValue(WEEK_OF_YEAR, 51)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkDate(2003, DECEMBER, 19, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10 Mon of 4th week (10/20: 43rd week of year, 293rd day):"); + System.out.println("Set to 2003/10 Mon of 4th week (10/20: 43rd week of year, 293rd day):"); cal.clear(); cal.set(YEAR, 2003); cal.set(MONTH, OCTOBER); @@ -118,32 +115,32 @@ public void TestFieldState() { cal.set(WEEK_OF_MONTH, 4); cal.getTime(); if (!cal.checkFieldValue(DAY_OF_MONTH, 20)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(DAY_OF_YEAR, 293)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_YEAR, 43)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set to 2003/10 Mon of 43rd week of year (10/20: 4th week of month, 293rd day):"); + System.out.println("Set to 2003/10 Mon of 43rd week of year (10/20: 4th week of month, 293rd day):"); cal.clear(); cal.set(YEAR, 2003); cal.set(DAY_OF_WEEK, MONDAY); cal.set(WEEK_OF_YEAR, 43); cal.getTime(); if (!cal.checkDate(2003, OCTOBER, 20, MONDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_MONTH, 4)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(DAY_OF_YEAR, 293)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln("Set day of week to SUNDAY and date to 2003/10/31. " + System.out.println("Set day of week to SUNDAY and date to 2003/10/31. " + "Then, getTime and set week of year to 43."); @SuppressWarnings("deprecation") @@ -161,15 +158,16 @@ public void TestFieldState() { cal.getTime(); cal.set(WEEK_OF_YEAR, 43); if (!cal.checkDate(2003, OCTOBER, 24, FRIDAY)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } /* * 4916815: REGRESSION: Problem with java.util.Calendar VM 1.4.2-b28 */ + @Test public void Test4916815() { - logln("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. " + System.out.println("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. " + "Set dayofweek to Sunday which should be 2003/9/21."); Koyomi cal = new Koyomi(); cal.clear(); @@ -183,13 +181,14 @@ public void Test4916815() { // Sunday of the week should be 2003/9/21. cal2.set(DAY_OF_WEEK, SUNDAY); if (!cal2.checkDate(2003, SEPTEMBER, 21, SUNDAY)) { - errln(cal2.getMessage()); + fail(cal2.getMessage()); } } /* * 4867075: GregorianCalendar get() calls complete() internally, should getTime() too? */ + @Test public void Test4867075() { Koyomi cal = new Koyomi(Locale.US); cal.clear(); @@ -209,7 +208,7 @@ private void checkDate(Koyomi cal, int dayOfWeek, cal.set(DAY_OF_WEEK, dayOfWeek); cal.getTime(); if (!cal.checkInternalDate(expectedYear, expectedMonth, expectedDayOfMonth, dayOfWeek)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } diff --git a/test/jdk/java/util/Calendar/GregorianCutoverTest.java b/test/jdk/java/util/Calendar/GregorianCutoverTest.java index a9b840a95b1..8b56c3ac62b 100644 --- a/test/jdk/java/util/Calendar/GregorianCutoverTest.java +++ b/test/jdk/java/util/Calendar/GregorianCutoverTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,9 +24,7 @@ /* * @test * @bug 4359204 4928615 4743587 4956232 6459836 6549953 - * @library /java/text/testlib - * @build Koyomi - * @run main GregorianCutoverTest + * @run junit/othervm GregorianCutoverTest * @summary Unit tests related to the Gregorian cutover support. */ @@ -36,25 +34,25 @@ import static java.util.GregorianCalendar.*; -public class GregorianCutoverTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - TimeZone tz = TimeZone.getDefault(); - Locale lc = Locale.getDefault(); - try { - TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - Locale.setDefault(Locale.US); +import static org.junit.jupiter.api.Assertions.fail; - new GregorianCutoverTest().run(args); - } finally { - TimeZone.setDefault(tz); - Locale.setDefault(lc); - } +public class GregorianCutoverTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("GMT")); } + /** * 4359204: GregorianCalendar.get(cal.DAY_OF_YEAR) is inconsistent for year 1582 */ + @Test public void Test4359204() { Koyomi cal = new Koyomi(); @@ -100,79 +98,79 @@ public void Test4359204() { checkContinuity(cal, DAY_OF_YEAR); checkContinuity(cal, WEEK_OF_YEAR); - logln("Default cutover"); + System.out.println("Default cutover"); cal = new Koyomi(); cal.set(1582, OCTOBER, 1); - logln(" roll --DAY_OF_MONTH from 1582/10/01"); + System.out.println(" roll --DAY_OF_MONTH from 1582/10/01"); cal.roll(DAY_OF_MONTH, -1); if (!cal.checkDate(1582, OCTOBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll DAY_OF_MONTH+10 from 1582/10/31"); + System.out.println(" roll DAY_OF_MONTH+10 from 1582/10/31"); cal.roll(DAY_OF_MONTH, +10); if (!cal.checkDate(1582, OCTOBER, 20)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll DAY_OF_MONTH-10 from 1582/10/20"); + System.out.println(" roll DAY_OF_MONTH-10 from 1582/10/20"); cal.roll(DAY_OF_MONTH, -10); if (!cal.checkDate(1582, OCTOBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll back one day further"); + System.out.println(" roll back one day further"); cal.roll(DAY_OF_MONTH, +1); if (!cal.checkDate(1582, OCTOBER, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // should handle the gap between 1969/12/22 (Julian) to 1970/1/5 (Gregorian) - logln("Cutover date is 1970/1/5"); + System.out.println("Cutover date is 1970/1/5"); @SuppressWarnings("deprecation") Date d1 = new Date(1970 - 1900, JANUARY, 5); cal.setGregorianChange(d1); cal.set(ERA, AD); cal.set(YEAR, 1970); - logln(" Set DAY_OF_YEAR to the 28th day of 1970"); + System.out.println(" Set DAY_OF_YEAR to the 28th day of 1970"); cal.set(DAY_OF_YEAR, 28); if (!cal.checkDate(1970, FEBRUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } if (!cal.checkFieldValue(WEEK_OF_YEAR, 5)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" 1969/12/22 should be the 356th day of the year."); + System.out.println(" 1969/12/22 should be the 356th day of the year."); cal.set(1969, DECEMBER, 22); if (!cal.checkFieldValue(DAY_OF_YEAR, 356)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" Set DAY_OF_YEAR to autual maximum."); + System.out.println(" Set DAY_OF_YEAR to autual maximum."); int actualMaxDayOfYear = cal.getActualMaximum(DAY_OF_YEAR); if (actualMaxDayOfYear != 356) { - errln("actual maximum of DAY_OF_YEAR: got " + actualMaxDayOfYear + ", expected 356"); + fail("actual maximum of DAY_OF_YEAR: got " + actualMaxDayOfYear + ", expected 356"); } cal.set(DAY_OF_YEAR, actualMaxDayOfYear); if (!cal.checkDate(1969, DECEMBER, 22)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.set(1969, DECEMBER, 22); cal.roll(DAY_OF_YEAR, +1); - logln(" Set to 1969/12/22 and roll DAY_OF_YEAR++"); + System.out.println(" Set to 1969/12/22 and roll DAY_OF_YEAR++"); if (!cal.checkDate(1969, JANUARY, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" 1970/1/5 should be the first day of the year."); + System.out.println(" 1970/1/5 should be the first day of the year."); cal.set(1970, JANUARY, 5); if (!cal.checkFieldValue(DAY_OF_YEAR, 1)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll --DAY_OF_MONTH from 1970/1/5"); + System.out.println(" roll --DAY_OF_MONTH from 1970/1/5"); cal.roll(DAY_OF_MONTH, -1); if (!cal.checkDate(1970, JANUARY, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } - logln(" roll back one day of month"); + System.out.println(" roll back one day of month"); cal.roll(DAY_OF_MONTH, +1); if (!cal.checkDate(1970, JANUARY, 5)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } // Test "missing" dates in non-lenient. @@ -180,22 +178,22 @@ public void Test4359204() { cal.setLenient(false); try { // the next day of 1582/10/4 (Julian) is 1582/10/15 (Gregorian) - logln("1582/10/10 doesn't exit with the default cutover."); + System.out.println("1582/10/10 doesn't exit with the default cutover."); cal.set(1582, OCTOBER, 10); cal.getTime(); - errln(" Didn't throw IllegalArgumentException in non-lenient."); + fail(" Didn't throw IllegalArgumentException in non-lenient."); } catch (IllegalArgumentException e) { } } private void checkContinuity(Koyomi cal, int field) { cal.getTime(); - logln(Koyomi.getFieldName(field) + " starting on " + cal.toDateString()); + System.out.println(Koyomi.getFieldName(field) + " starting on " + cal.toDateString()); int max = cal.getActualMaximum(field); for (int i = 1; i <= max; i++) { - logln(i + " " + cal.toDateString()); + System.out.println(i + " " + cal.toDateString()); if (!cal.checkFieldValue(field, i)) { - errln(" " + cal.toDateString() + ":\t" + cal.getMessage()); + fail(" " + cal.toDateString() + ":\t" + cal.getMessage()); } cal.add(field, +1); } @@ -204,92 +202,95 @@ private void checkContinuity(Koyomi cal, int field) { /** * 4928615: GregorianCalendar returns wrong dates after setGregorianChange */ + @Test public void Test4928615() { Koyomi cal = new Koyomi(); - logln("Today is 2003/10/1 Gregorian."); + System.out.println("Today is 2003/10/1 Gregorian."); @SuppressWarnings("deprecation") Date x = new Date(2003 - 1900, 10 - 1, 1); cal.setTime(x); - logln(" Changing the cutover date to yesterday..."); + System.out.println(" Changing the cutover date to yesterday..."); cal.setGregorianChange(new Date(x.getTime() - (24 * 3600 * 1000))); if (!cal.checkDate(2003, OCTOBER, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } - logln(" Changing the cutover date to tomorrow..."); + System.out.println(" Changing the cutover date to tomorrow..."); cal.setGregorianChange(new Date(x.getTime() + (24 * 3600 * 1000))); if (!cal.checkDate(2003, SEPTEMBER, 18)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } } /** * 4743587: GregorianCalendar.getLeastMaximum() returns wrong values */ + @Test public void Test4743587() { Koyomi cal = new Koyomi(); Koyomi cal2 = (Koyomi) cal.clone(); - logln("getLeastMaximum should handle cutover year.\n" + System.out.println("getLeastMaximum should handle cutover year.\n" + " default cutover date"); if (!cal.checkLeastMaximum(DAY_OF_YEAR, 365 - 10)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(WEEK_OF_YEAR, 52 - ((10 + 6) / 7))) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } // Corrected for 4956232 if (!cal.checkLeastMaximum(DAY_OF_MONTH, 28)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(WEEK_OF_MONTH, 3)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(DAY_OF_WEEK_IN_MONTH, 3)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } // make sure that getLeastMaximum calls didn't affect the date if (!cal.equals(cal2)) { - errln(" getLeastMaximum calls modified the object."); + fail(" getLeastMaximum calls modified the object."); } if (!cal.checkGreatestMinimum(DAY_OF_MONTH, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } - logln(" changing the date to 1582/10/20 for actual min/max tests"); + System.out.println(" changing the date to 1582/10/20 for actual min/max tests"); cal.set(1582, OCTOBER, 20); if (!cal.checkActualMinimum(DAY_OF_MONTH, 1)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 31)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } cal = new Koyomi(); - logln("Change the cutover date to 1970/1/5."); + System.out.println("Change the cutover date to 1970/1/5."); @SuppressWarnings("deprecation") Date d = new Date(1970 - 1900, 0, 5); cal.setGregorianChange(d); if (!cal.checkLeastMaximum(DAY_OF_YEAR, 356)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkLeastMaximum(DAY_OF_MONTH, 22)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkGreatestMinimum(DAY_OF_MONTH, 5)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } cal.set(1970, JANUARY, 10); if (!cal.checkActualMinimum(DAY_OF_MONTH, 5)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } if (!cal.checkActualMaximum(DAY_OF_MONTH, 31)) { - errln(" " + cal.getMessage()); + fail(" " + cal.getMessage()); } } /** * 6459836: (cal) GregorianCalendar set method provides wrong result */ + @Test public void Test6459836() { int hour = 13865672; Koyomi gc1 = new Koyomi(); @@ -297,19 +298,20 @@ public void Test6459836() { gc1.set(1, JANUARY, 1, 0, 0, 0); gc1.set(HOUR_OF_DAY, hour); if (!gc1.checkDate(1582, OCTOBER, 4)) { - errln("test case 1: " + gc1.getMessage()); + fail("test case 1: " + gc1.getMessage()); } gc1.clear(); gc1.set(1, JANUARY, 1, 0, 0, 0); gc1.set(HOUR_OF_DAY, hour + 24); if (!gc1.checkDate(1582, OCTOBER, 15)) { - errln("test case 2: " + gc1.getMessage()); + fail("test case 2: " + gc1.getMessage()); } } /** * 6549953 (cal) WEEK_OF_YEAR and DAY_OF_YEAR calculation problems around Gregorian cutover */ + @Test public void Test6549953() { Koyomi cal = new Koyomi(); @@ -319,13 +321,13 @@ public void Test6549953() { cal.checkFieldValue(WEEK_OF_YEAR, 42); cal.checkFieldValue(DAY_OF_WEEK, FRIDAY); if (!cal.checkDate(1582, OCTOBER, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } cal.clear(); cal.set(1582, OCTOBER, 1); cal.set(DAY_OF_YEAR, 292); if (!cal.checkDate(1582, OCTOBER, 29)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } diff --git a/test/jdk/java/util/Calendar/JulianTest.java b/test/jdk/java/util/Calendar/JulianTest.java index bd7105bce89..4311dab1e3b 100644 --- a/test/jdk/java/util/Calendar/JulianTest.java +++ b/test/jdk/java/util/Calendar/JulianTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,20 +25,21 @@ * @test * @bug 5029449 * @summary Tests for the Julian calendar system (before the Gregorian cutover) - * @library /java/text/testlib + * @run junit JulianTest */ import static java.util.GregorianCalendar.*; -public class JulianTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new JulianTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class JulianTest { /* * 5029449: Regression: GregorianCalendar produces wrong Julian calendar dates in BC 1 */ + @Test public void Test5029449() { Koyomi cal = new Koyomi(); cal.clear(); @@ -46,7 +47,7 @@ public void Test5029449() { // Date should be BC 1/12/31 if (!cal.checkFieldValue(ERA, BC) || !cal.checkDate(1, DECEMBER, 31)) { - errln(cal.getMessage()); + fail(cal.getMessage()); } } } diff --git a/test/jdk/java/util/Calendar/NonLenientTest.java b/test/jdk/java/util/Calendar/NonLenientTest.java index 357cf0e95c0..58b22215bf2 100644 --- a/test/jdk/java/util/Calendar/NonLenientTest.java +++ b/test/jdk/java/util/Calendar/NonLenientTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,7 +25,7 @@ * @test * @bug 4147269 4266783 4726030 * @summary Make sure that validation is adequate in non-lenient mode. - * @library /java/text/testlib + * @run junit/othervm NonLenientTest */ import java.util.Date; @@ -35,22 +35,22 @@ import static java.util.Calendar.*; -public class NonLenientTest extends IntlTest { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - Locale reservedLocale = Locale.getDefault(); - TimeZone reservedTimeZone = TimeZone.getDefault(); - try { - Locale.setDefault(Locale.US); - TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); - new NonLenientTest().run(args); - } finally { - // restore the reserved locale and time zone - Locale.setDefault(reservedLocale); - TimeZone.setDefault(reservedTimeZone); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class NonLenientTest { + + // Change JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); } + + @Test public void TestValidationInNonLenient() { Koyomi cal = getNonLenient(); @@ -122,6 +122,7 @@ public void TestValidationInNonLenient() { /** * 4266783: java.util.GregorianCalendar: incorrect validation in non-lenient */ + @Test public void Test4266783() { Koyomi cal = getNonLenient(); // 2003/1 has up to 5 weeks. @@ -135,6 +136,7 @@ public void Test4266783() { /** * 4726030: GregorianCalendar doesn't check invalid dates in non-lenient */ + @Test public void Test4726030() { Koyomi cal = getNonLenient(); // Default year is 1970 in GregorianCalendar which isn't a leap year. @@ -146,6 +148,7 @@ public void Test4726030() { /** * 4147269: java.util.GregorianCalendar.computeTime() works wrong when lenient is false */ + @Test public void Test4147269() { Koyomi calendar = getNonLenient(); Date date = (new GregorianCalendar(1996, 0, 3)).getTime(); @@ -157,7 +160,7 @@ public void Test4147269() { calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + Koyomi.getFieldName(field) + fail("Test failed with field " + Koyomi.getFieldName(field) + "\n\tdate before: " + date + "\n\tdate after: " + calendar.getTime() + "\n\tvalue: " + value + " (max = " + max + ")"); @@ -172,7 +175,7 @@ public void Test4147269() { calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + Koyomi.getFieldName(field) + fail("Test failed with field " + Koyomi.getFieldName(field) + "\n\tdate before: " + date + "\n\tdate after: " + calendar.getTime() + "\n\tvalue: " + value + " (min = " + min + ")"); @@ -187,7 +190,7 @@ void validate(Koyomi cal, String desc) { try { cal.complete(); - errln(desc + " should throw IllegalArgumentException in non-lenient."); + fail(desc + " should throw IllegalArgumentException in non-lenient."); } catch (IllegalArgumentException e) { } @@ -198,14 +201,14 @@ void validate(Koyomi cal, String desc) { int[] afterFields = cal.getFields(); for (int i = 0; i < FIELD_COUNT; i++) { if (cal.isSet(i) && originalFields[i] != afterFields[i]) { - errln(" complete() modified fields[" + Koyomi.getFieldName(i) + "] got " + fail(" complete() modified fields[" + Koyomi.getFieldName(i) + "] got " + afterFields[i] + ", expected " + originalFields[i]); } } // In non-lenient, set state of fields shouldn't be modified. int afterSetFields = cal.getSetStateFields(); if (setFields != afterSetFields) { - errln(" complate() modified set states: before 0x" + toHex(setFields) + fail(" complate() modified set states: before 0x" + toHex(setFields) + ", after 0x" + toHex(afterSetFields)); } } diff --git a/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java b/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java index 34363bf711d..5383d0d1240 100644 --- a/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java +++ b/test/jdk/java/util/Calendar/SupplementalJapaneseEraTestRun.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,10 +34,15 @@ import java.util.List; import java.util.Locale; import java.util.TimeZone; -import static java.util.Calendar.*; +import java.util.stream.Stream; + +import static java.util.Calendar.DAY_OF_YEAR; +import static java.util.Calendar.ERA; +import static java.util.Calendar.FEBRUARY; +import static java.util.Calendar.LONG; +import static java.util.Calendar.YEAR; import jdk.test.lib.process.ProcessTools; -import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.Utils; import org.testng.annotations.DataProvider; @@ -91,19 +96,18 @@ public void InvalidPropertyValuesTest(String prop) } private static void testRun(String property, List javaParam) - throws Throwable{ - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASS_PATH) - .addToolArg("-Djdk.calendar.japanese.supplemental.era=" + property) - .addToolArg("SupplementalJapaneseEraTest"); - for (String para: javaParam) { - launcher.addToolArg(para); - } - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + throws Throwable { + List params = List.of( + "-ea", "-esa", + "-cp", Utils.TEST_CLASS_PATH, + "-Djdk.calendar.japanese.supplemental.era=" + property, + "SupplementalJapaneseEraTest"); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(params.stream(), javaParam.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); + System.out.println(property + ":pass"); if (exitCode != 0) { System.out.println(property + ":fail"); diff --git a/test/jdk/java/util/Calendar/bug4028518.java b/test/jdk/java/util/Calendar/bug4028518.java index 982b93adc86..c3548ab18f0 100644 --- a/test/jdk/java/util/Calendar/bug4028518.java +++ b/test/jdk/java/util/Calendar/bug4028518.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,33 +24,30 @@ /* * @test * @bug 4028518 - * @summary Make sure cloned GregorianCalendar is unchanged by modifying its original. + * @summary Ensure cloned GregorianCalendar is unchanged when modifying its original. + * @run junit bug4028518 */ -import java.util.GregorianCalendar ; -import static java.util.Calendar.*; +import java.util.GregorianCalendar; + +import static java.util.Calendar.DAY_OF_MONTH; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertNotEquals; public class bug4028518 { - public static void main(String[] args) - { + /* + * Ensure modifying the original GregorianCalendar does not + * modify the cloned one as well + */ + @Test + public void clonedShouldNotChangeOriginalTest() { GregorianCalendar cal1 = new GregorianCalendar() ; GregorianCalendar cal2 = (GregorianCalendar) cal1.clone() ; - - printdate(cal1, "cal1: ") ; - printdate(cal2, "cal2 - cloned(): ") ; cal1.add(DAY_OF_MONTH, 1) ; - printdate(cal1, "cal1 after adding 1 day: ") ; - printdate(cal2, "cal2 should be unmodified: ") ; - if (cal1.get(DAY_OF_MONTH) == cal2.get(DAY_OF_MONTH)) { - throw new RuntimeException("cloned GregorianCalendar modified"); - } - } - - private static void printdate(GregorianCalendar cal, String string) - { - System.out.println(string + (cal.get(MONTH) + 1) - + "/" + cal.get(DAY_OF_MONTH) - + "/" + cal.get(YEAR)) ; + assertNotEquals(cal1.get(DAY_OF_MONTH), cal2.get(DAY_OF_MONTH), + "Cloned calendar should not have same value as original"); } } diff --git a/test/jdk/java/util/Calendar/bug4100311.java b/test/jdk/java/util/Calendar/bug4100311.java index ef0f36ecbd2..6fa885a3901 100644 --- a/test/jdk/java/util/Calendar/bug4100311.java +++ b/test/jdk/java/util/Calendar/bug4100311.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,24 +24,29 @@ /* * @test * @bug 4100311 - * @summary Make sure set(DAY_OF_YEAR, 1) works. + * @summary Ensure set(DAY_OF_YEAR, 1) works. + * @run junit bug4100311 */ import java.util.Calendar; import java.util.GregorianCalendar; import java.util.Date; -public class bug4100311 -{ +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class bug4100311 { + + // GregorianCalendar should be able to date to january 1st properly @SuppressWarnings("deprecation") - public static void main(String args[]) - { + @Test + public void dayOfYearIsOneTest() { GregorianCalendar cal = new GregorianCalendar(); cal.set(Calendar.YEAR, 1997); cal.set(Calendar.DAY_OF_YEAR, 1); - Date d = cal.getTime(); // Should be Jan 1 - if (d.getMonth() != 0 || d.getDate() != 1) { - throw new RuntimeException("Date isn't Jan 1"); - } + Date d = cal.getTime(); + assertEquals(0, d.getMonth(), "Date: "+d+" isn't January 1st"); + assertEquals(1, d.getDate(),"Date: "+d+" isn't January 1st"); } } diff --git a/test/jdk/java/util/Calendar/bug4243802.java b/test/jdk/java/util/Calendar/bug4243802.java index 1f3b910c1b3..499b7e45772 100644 --- a/test/jdk/java/util/Calendar/bug4243802.java +++ b/test/jdk/java/util/Calendar/bug4243802.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,69 +25,86 @@ * @test * @bug 4243802 * @summary confirm that Calendar.setTimeInMillis() and - * getTimeInMillis() can be called from a user program. (They used to - * be protected methods.) - * @library /java/text/testlib + * getTimeInMillis() can be called from a user program. (They used to + * be protected methods.) + * @run junit bug4243802 */ -import java.util.*; +import java.util.Calendar; +import java.util.Locale; +import java.util.TimeZone; -public class bug4243802 extends IntlTest { +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new bug4243802().run(args); +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class bug4243802 { + + // Save JVM default Locale and TimeZone + private static final TimeZone savedTz = TimeZone.getDefault(); + private static final Locale savedLocale = Locale.getDefault(); + + // Set custom JVM default Locale and TimeZone + @BeforeAll + static void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); + } + + // Restore JVM default Locale and TimeZone + @AfterAll + static void tearDownAll() { + Locale.setDefault(savedLocale); + TimeZone.setDefault(savedTz); } - /** - * 4243802: RFE: need way to set the date of a calendar without a Date object + /* + * Test getTimeInMillis() and setTimeInMillis(). Compare a Calendar + * set with a traditional date to one set using setTimeInMillis(), + * where both Calendars should be of equal times. */ - public void Test4243802() { - TimeZone saveZone = TimeZone.getDefault(); - Locale saveLocale = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles")); + @Test + public void setCalendarWithoutDateTest() { + Calendar cal1 = Calendar.getInstance(); + Calendar cal2 = Calendar.getInstance(); + cal1.clear(); + cal2.clear(); + cal1.set(2001, Calendar.JANUARY, 25, 1, 23, 45); + // Build the second calendar using the getTimeInMillis of the first + cal2.setTimeInMillis(cal1.getTimeInMillis()); - Calendar cal1 = Calendar.getInstance(); - Calendar cal2 = Calendar.getInstance(); + assertEquals(2001, cal2.get(Calendar.YEAR), getErrMsg(cal1)); + assertEquals(Calendar.JANUARY, cal2.get(Calendar.MONTH), getErrMsg(cal1)); + assertEquals(25, cal2.get(Calendar.DAY_OF_MONTH), getErrMsg(cal1)); + assertEquals(1, cal2.get(Calendar.HOUR_OF_DAY), getErrMsg(cal1)); + assertEquals(23, cal2.get(Calendar.MINUTE), getErrMsg(cal1)); + assertEquals(45, cal2.get(Calendar.SECOND), getErrMsg(cal1)); + assertEquals(0, cal2.get(Calendar.MILLISECOND), getErrMsg(cal1)); + } - cal1.clear(); - cal2.clear(); - cal1.set(2001, Calendar.JANUARY, 25, 1, 23, 45); - cal2.setTimeInMillis(cal1.getTimeInMillis()); - if ((cal2.get(Calendar.YEAR) != 2001) || - (cal2.get(Calendar.MONTH) != Calendar.JANUARY) || - (cal2.get(Calendar.DAY_OF_MONTH) != 25) || - (cal2.get(Calendar.HOUR_OF_DAY) != 1) || - (cal2.get(Calendar.MINUTE) != 23) || - (cal2.get(Calendar.SECOND) != 45) || - (cal2.get(Calendar.MILLISECOND) != 0)) { - errln("Failed: expected 1/25/2001 1:23:45.000" + - ", got " + (cal2.get(Calendar.MONTH)+1) + "/" + - cal2.get(Calendar.DAY_OF_MONTH) +"/" + - cal2.get(Calendar.YEAR) + " " + - cal2.get(Calendar.HOUR_OF_DAY) + ":" + - cal2.get(Calendar.MINUTE) + ":" + - cal2.get(Calendar.SECOND) + "." + - toMillis(cal2.get(Calendar.MILLISECOND))); - } - logln("Passed."); - } - finally { - Locale.setDefault(saveLocale); - TimeZone.setDefault(saveZone); - } + // Utility to build a long error message + private static String getErrMsg(Calendar cal) { + return "Failed: expected 1/25/2001 1:23:45.000" + + ", got " + (cal.get(Calendar.MONTH)+1) + "/" + + cal.get(Calendar.DAY_OF_MONTH) +"/" + + cal.get(Calendar.YEAR) + " " + + cal.get(Calendar.HOUR_OF_DAY) + ":" + + cal.get(Calendar.MINUTE) + ":" + + cal.get(Calendar.SECOND) + "." + + toMillis(cal.get(Calendar.MILLISECOND)); } - private String toMillis(int m) { - StringBuffer sb = new StringBuffer(); + // Utility to convert value to format of expected milisecond value + private static String toMillis(int m) { + StringBuilder sb = new StringBuilder(); if (m < 100) { sb.append('0'); } if (m < 10) { sb.append('0'); } - sb.append(m); - return sb.toString(); + return sb.append(m).toString(); } } diff --git a/test/jdk/java/util/Calendar/bug4316678.java b/test/jdk/java/util/Calendar/bug4316678.java index 8ae6bbc294f..f6bd4b87cae 100644 --- a/test/jdk/java/util/Calendar/bug4316678.java +++ b/test/jdk/java/util/Calendar/bug4316678.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,49 +21,64 @@ * questions. */ -import java.io.*; -import java.util.*; -import java.text.*; - -/** +/* * @test * @bug 4316678 - * @summary test that Calendar's Serializasion works correctly. - * @library /java/text/testlib + * @summary test that Calendar's Serialization works correctly. + * @run junit bug4316678 */ -public class bug4316678 extends IntlTest { - public static void main(String[] args) throws Exception { - new bug4316678().run(args); - } +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.TimeZone; - public void Test4316678() throws Exception { - GregorianCalendar gc1; - GregorianCalendar gc2; - TimeZone saveZone = TimeZone.getDefault(); +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; - try { - TimeZone.setDefault(TimeZone.getTimeZone("PST")); +import static org.junit.jupiter.api.Assertions.assertEquals; - gc1 = new GregorianCalendar(2000, Calendar.OCTOBER, 10); - try (ObjectOutputStream out - = new ObjectOutputStream(new FileOutputStream("bug4316678.ser"))) { - out.writeObject(gc1); - } +public class bug4316678 { - try (ObjectInputStream in - = new ObjectInputStream(new FileInputStream("bug4316678.ser"))) { - gc2 = (GregorianCalendar)in.readObject(); - } + private static final String serializedData = "bug4316678.ser"; + + // Save JVM default TimeZone + private static final TimeZone savedTz = TimeZone.getDefault(); + + // Set custom JVM default TimeZone + @BeforeAll + static void initAll() { + TimeZone.setDefault(TimeZone.getTimeZone("PST")); + } - gc1.set(Calendar.DATE, 16); - gc2.set(Calendar.DATE, 16); - if (!gc1.getTime().equals(gc2.getTime())) { - errln("Invalid Time :" + gc2.getTime() + - ", expected :" + gc1.getTime()); - } - } finally { - TimeZone.setDefault(saveZone); + // Restore JVM default Locale and TimeZone + @AfterAll + static void tearDownAll() { + TimeZone.setDefault(savedTz); + } + + // Test that a serialized GregorianCalendar has the expected values + @Test + public void serializationTest() throws IOException, ClassNotFoundException { + GregorianCalendar gc1 = new GregorianCalendar(2000, Calendar.OCTOBER, 10); + GregorianCalendar gc2; + try (ObjectOutputStream out + = new ObjectOutputStream(new FileOutputStream(serializedData))) { + out.writeObject(gc1); } + + try (ObjectInputStream in = new ObjectInputStream(new FileInputStream(serializedData))) { + gc2 = (GregorianCalendar)in.readObject(); + } + + gc1.set(Calendar.DATE, 16); + gc2.set(Calendar.DATE, 16); + assertEquals(gc2.getTime(), gc1.getTime(), + "Times should be equal after serialization"); } } diff --git a/test/jdk/java/util/Calendar/bug4372743.java b/test/jdk/java/util/Calendar/bug4372743.java index 6d380e523e2..193ad53d813 100644 --- a/test/jdk/java/util/Calendar/bug4372743.java +++ b/test/jdk/java/util/Calendar/bug4372743.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,21 +25,107 @@ * @test * @bug 4372743 * @summary test that checks transitions of ERA and YEAR which are caused by add(MONTH). - * @library /java/text/testlib + * @run junit bug4372743 */ import java.util.GregorianCalendar; import java.util.TimeZone; +import java.util.stream.Stream; -import static java.util.GregorianCalendar.*; +import static java.util.GregorianCalendar.AD; +import static java.util.GregorianCalendar.APRIL; +import static java.util.GregorianCalendar.AUGUST; +import static java.util.GregorianCalendar.BC; +import static java.util.GregorianCalendar.DECEMBER; +import static java.util.GregorianCalendar.ERA; +import static java.util.GregorianCalendar.FEBRUARY; +import static java.util.GregorianCalendar.JANUARY; +import static java.util.GregorianCalendar.JULY; +import static java.util.GregorianCalendar.JUNE; +import static java.util.GregorianCalendar.MARCH; +import static java.util.GregorianCalendar.MAY; +import static java.util.GregorianCalendar.MONTH; +import static java.util.GregorianCalendar.NOVEMBER; +import static java.util.GregorianCalendar.OCTOBER; +import static java.util.GregorianCalendar.SEPTEMBER; +import static java.util.GregorianCalendar.YEAR; -public class bug4372743 extends IntlTest { +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; - public static void main(String[] args) throws Exception { - new bug4372743().run(args); +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class bug4372743 { + + // Save JVM default timezone + private static final TimeZone savedTz = TimeZone.getDefault(); + + // Set custom JVM default timezone + @BeforeAll + static void initAll() { + TimeZone.setDefault(TimeZone.getTimeZone("PST")); + } + + // Restore JVM default timezone + @AfterAll + static void tearDownAll() { + TimeZone.setDefault(savedTz); } - private int[][] data = { + /* + * Set GregorianCalendar to (March 3, A.D. 2) and test adding + * to the month field. Ensure that the added field is as expected. + */ + @ParameterizedTest + @MethodSource("A_D_Values") + public void A_D_Test(GregorianCalendar gc, int monthValue) { + for (int i = 0; i < tableSize; i+=(-monthValue)) { + check(gc, i); + gc.add(MONTH, monthValue); + } + } + + // Given in format: (A.D.) GregorianCalendar, amount to add + private static Stream A_D_Values() { + return Stream.of( + Arguments.of(new GregorianCalendar(2, MARCH, 3), -1), + Arguments.of(new GregorianCalendar(2, MARCH, 3), -7)); + } + + /* + * Set GregorianCalendar to (March 10, 2 B.C.) and test adding + * to the month field. Ensure that the added field is as expected. + */ + @ParameterizedTest + @MethodSource("B_C_Values") + public void B_C_Test(GregorianCalendar gc, int monthValue) { + gc.add(YEAR, -3); + for (int i = tableSize - 1; i >= 0; i-=monthValue) { + check(gc, i); + gc.add(MONTH, monthValue); + } + } + + // Given in format: (B.C.) GregorianCalendar, amount to add + private static Stream B_C_Values() { + return Stream.of( + Arguments.of(new GregorianCalendar(2, OCTOBER, 10), 1), + Arguments.of(new GregorianCalendar(2, OCTOBER, 10), 8)); + } + + // Check golden data array with actual value + private void check(GregorianCalendar gc, int index) { + assertEquals(data[index][ERA], gc.get(ERA), "Invalid era"); + assertEquals(data[index][YEAR], gc.get(YEAR), "Invalid year"); + assertEquals(data[index][MONTH], gc.get(MONTH), "Invalid month"); + } + + // Expected ERA, YEAR, and MONTH combinations + private final int[][] data = { {AD, 2, MARCH}, {AD, 2, FEBRUARY}, {AD, 2, JANUARY}, @@ -70,61 +156,5 @@ public static void main(String[] args) throws Exception { {BC, 2, DECEMBER}, {BC, 2, NOVEMBER}, {BC, 2, OCTOBER}}; - private int tablesize = data.length; - - private void check(GregorianCalendar gc, int index) { - if (gc.get(ERA) != data[index][ERA]) { - errln("Invalid era :" + gc.get(ERA) - + ", expected :" + data[index][ERA]); - } - if (gc.get(YEAR) != data[index][YEAR]) { - errln("Invalid year :" + gc.get(YEAR) - + ", expected :" + data[index][YEAR]); - } - if (gc.get(MONTH) != data[index][MONTH]) { - errln("Invalid month :" + gc.get(MONTH) - + ", expected :" + data[index][MONTH]); - } - } - - public void Test4372743() { - GregorianCalendar gc; - TimeZone saveZone = TimeZone.getDefault(); - - try { - TimeZone.setDefault(TimeZone.getTimeZone("PST")); - - /* Set March 3, A.D. 2 */ - gc = new GregorianCalendar(2, MARCH, 3); - for (int i = 0; i < tablesize; i++) { - check(gc, i); - gc.add(MONTH, -1); - } - - /* Again, Set March 3, A.D. 2 */ - gc = new GregorianCalendar(2, MARCH, 3); - for (int i = 0; i < tablesize; i += 7) { - check(gc, i); - gc.add(MONTH, -7); - } - - /* Set March 10, 2 B.C. */ - gc = new GregorianCalendar(2, OCTOBER, 10); - gc.add(YEAR, -3); - for (int i = tablesize - 1; i >= 0; i--) { - check(gc, i); - gc.add(MONTH, 1); - } - - /* Again, Set March 10, 2 B.C. */ - gc = new GregorianCalendar(2, OCTOBER, 10); - gc.add(YEAR, -3); - for (int i = tablesize - 1; i >= 0; i -= 8) { - check(gc, i); - gc.add(MONTH, 8); - } - } finally { - TimeZone.setDefault(saveZone); - } - } + private final int tableSize = data.length; } diff --git a/test/jdk/java/util/Calendar/bug4401223.java b/test/jdk/java/util/Calendar/bug4401223.java index 3123181e1a1..15b420c283b 100644 --- a/test/jdk/java/util/Calendar/bug4401223.java +++ b/test/jdk/java/util/Calendar/bug4401223.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,73 +24,59 @@ /* * @test * @bug 4401223 - * @summary Make sure that GregorianCalendar doesn't cause IllegalArgumentException at some special situations which are related to the Leap Year. - * @library /java/text/testlib + * @summary Make sure that GregorianCalendar doesn't cause + * IllegalArgumentException at some special situations which are + * related to the Leap Year. + * @run junit bug4401223 */ import java.util.Date; import java.util.GregorianCalendar; -import static java.util.GregorianCalendar.*; +import static java.util.GregorianCalendar.DATE; +import static java.util.GregorianCalendar.DAY_OF_YEAR; +import static java.util.GregorianCalendar.DECEMBER; +import static java.util.GregorianCalendar.FEBRUARY; +import static java.util.GregorianCalendar.MONTH; +import static java.util.GregorianCalendar.YEAR; -public class bug4401223 extends IntlTest { +import org.junit.jupiter.api.Test; - public void Test4401223a() { - int status = 0; - String s = null; +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; - try { - @SuppressWarnings("deprecation") - Date date = new Date(2000 - 1900, FEBRUARY, 29); - GregorianCalendar gc = new GregorianCalendar(); +public class bug4401223 { + + // Ensure IAE not thrown for date: 12-29-00 + @SuppressWarnings("deprecation") + @Test + public void checkExceptionTest() { + Date date = new Date(2000 - 1900, FEBRUARY, 29); + GregorianCalendar gc = new GregorianCalendar(); + assertDoesNotThrow(() -> { gc.setTime(date); gc.setLenient(false); gc.set(YEAR, 2001); - s = "02/29/00 & set(YEAR,2001) = " + gc.getTime().toString(); - } catch (Exception ex) { - status++; - s = "Exception occurred for 2/29/00 & set(YEAR,2001): " + ex; - } - if (status > 0) { - errln(s); - } else { - logln(s); - } + }, "Exception occurred for 2/29/00 & set(YEAR,2001)"); } - public void Test4401223b() { - int status = 0; - String s = null; - - try { - @SuppressWarnings("deprecation") - Date date = new Date(2000 - 1900, DECEMBER, 31); - GregorianCalendar gc = new GregorianCalendar(); + // Ensure IAE not thrown for date: 12-31-00. Validate expected values. + @SuppressWarnings("deprecation") + @Test + public void checkExceptionAndValuesTest() { + Date date = new Date(2000 - 1900, DECEMBER, 31); + GregorianCalendar gc = new GregorianCalendar(); + assertDoesNotThrow(() -> { gc.setTime(date); gc.setLenient(false); gc.set(YEAR, 2001); + }, "Exception occurred for 12/31/00 & set(YEAR,2001)"); - if (gc.get(YEAR) != 2001 - || gc.get(MONTH) != DECEMBER - || gc.get(DATE) != 31 - || gc.get(DAY_OF_YEAR) != 365) { - status++; - s = "Wrong Date : 12/31/00 & set(YEAR,2001) ---> " + gc.getTime().toString(); - } else { - s = "12/31/00 & set(YEAR,2001) = " + gc.getTime().toString(); - } - } catch (Exception ex) { - status++; - s = "Exception occurred for 12/31/00 & set(YEAR,2001) : " + ex; - } - if (status > 0) { - errln(s); - } else { - logln(s); - } - } + String errMsg = "Wrong date, got: " + gc.getTime(); - public static void main(String[] args) throws Exception { - new bug4401223().run(args); + assertEquals(2001, gc.get(YEAR), errMsg); + assertEquals(DECEMBER, gc.get(MONTH), errMsg); + assertEquals(31, gc.get(DATE), errMsg); + assertEquals(365, gc.get(DAY_OF_YEAR), errMsg); } } diff --git a/test/jdk/java/util/Calendar/bug4409072.java b/test/jdk/java/util/Calendar/bug4409072.java index af5ef02c349..617550fe1aa 100644 --- a/test/jdk/java/util/Calendar/bug4409072.java +++ b/test/jdk/java/util/Calendar/bug4409072.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,25 +26,26 @@ * @bug 4409072 * @summary tests for set(), add(), and roll() with various week parameters. * @library /java/text/testlib - * @run main bug4409072 + * @run junit bug4409072 */ import java.util.*; import static java.util.Calendar.*; -public class bug4409072 extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new bug4409072().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class bug4409072 { /* Confirm some public methods' behavior in Calendar. * (e.g. add(), roll(), set()) */ + @Test public void Test4409072() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { - logln("Skipping this test because locale is " + locale); + System.out.println("Skipping this test because locale is " + locale); return; } @@ -411,7 +412,7 @@ void testSet() { if (cal.get(WEEK_OF_YEAR) != 22) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=22)" + + fail("Failed : set(WEEK_OF_YEAR=22)" + " *** get(WEEK_OF_YEAR=" + cal.get(WEEK_OF_YEAR) + ")" + ", got " + (month+1)+"/"+date+"/"+year + @@ -420,7 +421,7 @@ void testSet() { ", FirstDOW=" + dow); } else if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=22)" + + fail("Failed : set(WEEK_OF_YEAR=22)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -446,7 +447,7 @@ void testSet() { if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_MONTH=1)" + + fail("Failed : set(WEEK_OF_MONTH=1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -470,7 +471,7 @@ void testSet() { if (cal.get(WEEK_OF_YEAR) != 1) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=1)" + + fail("Failed : set(WEEK_OF_YEAR=1)" + " *** get(WEEK_OF_YEAR=" + cal.get(WEEK_OF_YEAR) + ")" + ", got " + (month+1)+"/"+date+"/"+year + @@ -479,7 +480,7 @@ void testSet() { ", FirstDOW=" + dow); } else if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : set(WEEK_OF_YEAR=1)" + + fail("Failed : set(WEEK_OF_YEAR=1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -490,7 +491,7 @@ void testSet() { } if (noerror) { - logln("Passed : set() test"); + System.out.println("Passed : set() test"); } } @@ -525,7 +526,7 @@ void testAdd() { if ((year != 2006) || (month != 0) || (date != 25)) { noerror = false; - errln("Failed : add(WEEK_OF_YEAR+1)" + + fail("Failed : add(WEEK_OF_YEAR+1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 1/25/2006" + ", MinFirstDOW=" + minDow + @@ -542,7 +543,7 @@ void testAdd() { date = cal.get(DATE); if ((oldWOY - newWOY) != 3) { - errln("Failed : add(WEEK_OF_YEAR-1)" + + fail("Failed : add(WEEK_OF_YEAR-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 11/16/2005" + ", MinFirstDOW=" + minDow + @@ -550,7 +551,7 @@ void testAdd() { ", WEEK_OF_YEAR=" + newWOY + " should be " + (oldWOY-3)); } else if ((year != 2005) || (month != 10) || (date != 16)) { - errln("Failed : add(-1)" + + fail("Failed : add(-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected 11/16/2005" + ", MinFirstDOW=" + minDow + @@ -560,7 +561,7 @@ void testAdd() { } if (noerror) { - logln("Passed : add() test"); + System.out.println("Passed : add() test"); } } @@ -622,7 +623,7 @@ void testRoll() { if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_MONTH-1)" + + fail("Failed : roll(WEEK_OF_MONTH-1)" + " got " + (month+1) + "/" + date + "/" + year + ", expected " + (m+1) + "/" + d + "/" + y + ", MinFirstDOW=" + minDow + @@ -649,7 +650,7 @@ void testRoll() { if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_YEAR+1)" + + fail("Failed : roll(WEEK_OF_YEAR+1)" + " got " + (month+1) + "/" + date + "/" + year + ", expected " + (m+1) + "/" + d + "/" + y + ", MinFirstDOW=" + minDow + @@ -670,7 +671,7 @@ void testRoll() { if ((year != y) || (month != m) || (date != d)) { noerror = false; - errln("Failed : roll(WEEK_OF_YEAR-1)" + + fail("Failed : roll(WEEK_OF_YEAR-1)" + " got " + (month+1)+"/"+date+"/"+year + ", expected " + (m+1)+"/"+d+"/"+y + ", MinFirstDOW=" + minDow + @@ -680,7 +681,7 @@ void testRoll() { } if (noerror) { - logln("Passed : roll() test"); + System.out.println("Passed : roll() test"); } } } diff --git a/test/jdk/java/util/Calendar/bug4514831.java b/test/jdk/java/util/Calendar/bug4514831.java index f0c34a8aa2a..886c6a0915d 100644 --- a/test/jdk/java/util/Calendar/bug4514831.java +++ b/test/jdk/java/util/Calendar/bug4514831.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,77 +24,99 @@ /* * @test * @bug 4514831 - * @summary Confirm that GregorianCalendar.roll() works properly during transition from Daylight Saving Time to Standard Time. + * @summary Confirm that GregorianCalendar.roll() works properly during + * transition from Daylight Saving Time to Standard Time. + * @run junit bug4514831 */ import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; -import static java.util.GregorianCalendar.*; +import static java.util.GregorianCalendar.DAY_OF_MONTH; +import static java.util.GregorianCalendar.DAY_OF_WEEK; +import static java.util.GregorianCalendar.DAY_OF_WEEK_IN_MONTH; +import static java.util.GregorianCalendar.DAY_OF_YEAR; +import static java.util.GregorianCalendar.OCTOBER; +import static java.util.GregorianCalendar.THURSDAY; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; -public class bug4514831 { - - public static void main(String[] args) { - Locale savedLocale = Locale.getDefault(); - TimeZone savedTimeZone = TimeZone.getDefault(); - boolean err = false; +import static org.junit.jupiter.api.Assertions.assertEquals; - String golden_data1 = "27-28 28-29 29-30 30-31 31-1 1-2 2-3 "; - String golden_data2 = "27-28 28-29 29-30 30-31 31-25 25-26 26-27 "; - String golden_data3 = "1-8 8-15 15-22 22-29 29-1 1-8 8-15 "; +public class bug4514831 { + // Data of 7 rolls in the form of a string for the respective field + private static final String expectedDayOfYearData = "27-28 28-29 29-30 30-31 31-1 1-2 2-3 "; + private static final String expectedDayOfWeekData = "27-28 28-29 29-30 30-31 31-25 25-26 26-27 "; + private static final String expectedDayOfWeekInMonthData = "1-8 8-15 15-22 22-29 29-1 1-8 8-15 "; + private static final TimeZone savedTz = TimeZone.getDefault(); + private static final Locale savedLocale = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); + // Save JVM default Locale and TimeZone + @BeforeAll + void initAll() { + Locale.setDefault(Locale.US); + TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); + } - String test_roll = ""; - GregorianCalendar c_roll = new GregorianCalendar(2001, OCTOBER, 27); - for (int i = 0; i < 7; i++) { - test_roll += c_roll.get(DAY_OF_MONTH) + "-"; - c_roll.roll(DAY_OF_YEAR, true); - test_roll += c_roll.get(DAY_OF_MONTH) + " "; - } - if (!test_roll.equals(golden_data1)) { - err = true; - System.err.println("Wrong roll(DAY_OF_YEAR) transition: got " - + test_roll + "expected " + golden_data1); - } + // Restore JVM default Locale and TimeZone + @AfterAll + void tearDownAll() { + Locale.setDefault(savedLocale); + TimeZone.setDefault(savedTz); + } - test_roll = ""; - c_roll = new GregorianCalendar(2001, OCTOBER, 27); - c_roll.setFirstDayOfWeek(THURSDAY); - for (int i = 0; i < 7; i++) { - test_roll += c_roll.get(DAY_OF_MONTH) + "-"; - c_roll.roll(DAY_OF_WEEK, true); - test_roll += c_roll.get(DAY_OF_MONTH) + " "; - } - if (!test_roll.equals(golden_data2)) { - err = true; - System.err.println("Wrong roll(DAY_OF_WEEK) transition: got " - + test_roll + "expected " + golden_data2); - } + /* + * Test some roll values during transition (DAY_OF_YEAR field). Uses + * the boolean roll method. Roll multiple times and attach the returned + * values to a long string which is then compared to the expected data. + */ + public void rollDayOfYearTest() { + StringBuilder actualRollData = new StringBuilder(); + GregorianCalendar cal = new GregorianCalendar(2001, OCTOBER, 27); + for (int i = 0; i < 7; i++) { + actualRollData.append(cal.get(DAY_OF_MONTH)).append("-"); + cal.roll(DAY_OF_YEAR, true); + actualRollData.append(cal.get(DAY_OF_MONTH)).append(" "); + } + assertEquals(expectedDayOfYearData, actualRollData.toString(), + "Wrong roll(DAY_OF_YEAR) transition"); + } - test_roll = ""; - c_roll = new GregorianCalendar(2001, OCTOBER, 1); - for (int i = 0; i < 7; i++) { - test_roll += c_roll.get(DAY_OF_MONTH) + "-"; - c_roll.roll(DAY_OF_WEEK_IN_MONTH, true); - test_roll += c_roll.get(DAY_OF_MONTH) + " "; - } - if (!test_roll.equals(golden_data3)) { - err = true; - System.err.println("Wrong roll(DAY_OF_WEEK_IN_MONTH) transition: got " - + test_roll + "expected " + golden_data3); - } - } finally { - Locale.setDefault(savedLocale); - TimeZone.setDefault(savedTimeZone); + /* + * Test some roll values during transition (DAY_OF_WEEK field). Uses + * the boolean roll method. Roll multiple times and attach the returned + * values to a long string which is then compared to the expected data. + */ + public void rollDayOfWeekTest() { + StringBuilder actualRollData = new StringBuilder(); + GregorianCalendar cal = new GregorianCalendar(2001, OCTOBER, 27); + cal.setFirstDayOfWeek(THURSDAY); + for (int i = 0; i < 7; i++) { + actualRollData.append(cal.get(DAY_OF_MONTH)).append("-"); + cal.roll(DAY_OF_WEEK, true); + actualRollData.append(cal.get(DAY_OF_MONTH)).append(" "); } + assertEquals(expectedDayOfWeekData, actualRollData.toString(), + "Wrong roll(DAY_OF_WEEK) transition"); + } - if (err) { - throw new RuntimeException("Wrong roll() transition"); + /* + * Test some roll values during transition (DAY_OF_WEEK_IN_MONTH field). Uses + * the boolean roll method. Roll multiple times and attach the returned + * values to a long string which is then compared to the expected data. + */ + public void rollDayOfWeekInMonthTest() { + StringBuilder actualRollData = new StringBuilder(); + GregorianCalendar cal = new GregorianCalendar(2001, OCTOBER, 1); + for (int i = 0; i < 7; i++) { + actualRollData.append(cal.get(DAY_OF_MONTH)).append("-"); + cal.roll(DAY_OF_WEEK_IN_MONTH, true); + actualRollData.append(cal.get(DAY_OF_MONTH)).append(" "); } + assertEquals(expectedDayOfWeekInMonthData, actualRollData.toString(), + "Wrong roll(DAY_OF_WEEK_IN_MONTH) transition"); } } diff --git a/test/jdk/java/util/Date/DateRegression.java b/test/jdk/java/util/Date/DateRegression.java index 70d8a5bf706..8fe89d9d59b 100644 --- a/test/jdk/java/util/Date/DateRegression.java +++ b/test/jdk/java/util/Date/DateRegression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,21 +24,22 @@ /* * @test * @bug 4023247 4027685 4032037 4072029 4073003 4118010 4120606 4133833 4136916 6274757 6314387 - * @library /java/text/testlib + * @run junit DateRegression */ import java.util.*; -@SuppressWarnings("deprecation") -public class DateRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new DateRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +@SuppressWarnings("deprecation") +public class DateRegression { /** * @bug 4023247 */ + @Test public void Test4023247() { Date d1 = new Date(0); Date d2 = new Date(0); @@ -58,46 +59,49 @@ public void Test4023247() { d2.setSeconds(0); if (d1.hashCode() != d2.hashCode()) - errln("Fail: Date hashCode misbehaves"); + fail("Fail: Date hashCode misbehaves"); } /** * @bug 4027685 */ + @Test public void Test4027685() { // Should be 01/16/97 00:00:00 Date nite = new Date("16-JAN-97 12:00 AM"); // Should be 01/16/97 12:00:00 Date noon = new Date("16-JAN-97 12:00 PM"); - logln("Midnight = " + nite + ", Noon = " + noon); + System.out.println("Midnight = " + nite + ", Noon = " + noon); if (!nite.equals(new Date(97, Calendar.JANUARY, 16, 0, 0)) || !noon.equals(new Date(97, Calendar.JANUARY, 16, 12, 0))) - errln("Fail: Nite/Noon confused"); + fail("Fail: Nite/Noon confused"); } /** * @bug 4032037 */ + @Test public void Test4032037() { Date ref = new Date(97, 1, 10); Date d = new Date(Date.parse("2/10/97")); - logln("Date.parse(2/10/97) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date.parse(2/10/97) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date(Date.parse("10 feb 1997")); - logln("Date.parse(10 feb 1997) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date.parse(10 feb 1997) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date("2/10/97"); - logln("Date(2/10/97) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date(2/10/97) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); d = new Date("10 feb 1997"); - logln("Date(10 feb 1997) => " + d); - if (!d.equals(ref)) errln("Fail: Want " + ref + " Got " + d); + System.out.println("Date(10 feb 1997) => " + d); + if (!d.equals(ref)) fail("Fail: Want " + ref + " Got " + d); } /** * @bug 4072029 */ + @Test public void Test4072029() { TimeZone saveZone = TimeZone.getDefault(); @@ -110,7 +114,7 @@ public void Test4072029() { if (!s.equals(s2) || Math.abs(now.getTime() - now2.getTime()) > 60000 /*one min*/) { - errln("Fail: Roundtrip toString/parse"); + fail("Fail: Roundtrip toString/parse"); } } finally { @@ -121,16 +125,17 @@ public void Test4072029() { /** * @bug 4073003 */ + @Test public void Test4073003() { Date d = new Date(Date.parse("01/02/1984")); if (!d.equals(new Date(84, 0, 2))) - errln("Fail: Want 1/2/1984 Got " + d); + fail("Fail: Want 1/2/1984 Got " + d); d = new Date(Date.parse("02/03/2012")); if (!d.equals(new Date(112, 1, 3))) - errln("Fail: Want 2/3/2012 Got " + d); + fail("Fail: Want 2/3/2012 Got " + d); d = new Date(Date.parse("03/04/15")); if (!d.equals(new Date(115, 2, 4))) - errln("Fail: Want 3/4/2015 Got " + d); + fail("Fail: Want 3/4/2015 Got " + d); } /** @@ -140,26 +145,28 @@ public void Test4073003() { * NOTE: This turned out to be a user error (passing in 2000 instead * of 2000-1900 to the Date constructor). */ + @Test public void Test4118010() { Date d=new java.util.Date(2000-1900, Calendar.FEBRUARY, 29); int m=d.getMonth(); int date=d.getDate(); if (m != Calendar.FEBRUARY || date != 29) - errln("Fail: Want Feb 29, got " + d); + fail("Fail: Want Feb 29, got " + d); } /** * @bug 4120606 * Date objects share state after cloning. */ + @Test public void Test4120606() { Date d = new Date(98, Calendar.JUNE, 24); d.setMonth(Calendar.MAY); Date e = (Date)d.clone(); d.setMonth(Calendar.FEBRUARY); if (e.getMonth() != Calendar.MAY) { - errln("Cloned Date objects share state"); + fail("Cloned Date objects share state"); } } @@ -168,11 +175,12 @@ public void Test4120606() { * Date constructor crashes with parameters out of range, when it should * normalize. */ + @Test public void Test4133833() { Date date = new java.util.Date(12,15,19); Date exp = new Date(1913-1900, Calendar.APRIL, 19); if (!date.equals(exp)) - errln("Fail: Want " + exp + + fail("Fail: Want " + exp + "; got " + date); } @@ -181,15 +189,17 @@ public void Test4133833() { * Date.toString() throws exception in 1.2b4-E * CANNOT REPRODUCE this bug */ + @Test public void Test4136916() { Date time = new Date(); - logln(time.toString()); + System.out.println(time.toString()); } /** * @bug 6274757 * Date getTime and toString interaction for some time values */ + @Test public void Test6274757() { TimeZone savedTz = TimeZone.getDefault(); try { @@ -199,11 +209,11 @@ public void Test6274757() { Calendar jdkCal = Calendar.getInstance(jdkGMT); jdkCal.clear(); jdkCal.set(1582, Calendar.OCTOBER, 15); - logln("JDK time: " + jdkCal.getTime().getTime() ); - logln("JDK time (str): " + jdkCal.getTime() ); - logln("Day of month: " + jdkCal.get(Calendar.DAY_OF_MONTH)); + System.out.println("JDK time: " + jdkCal.getTime().getTime() ); + System.out.println("JDK time (str): " + jdkCal.getTime() ); + System.out.println("Day of month: " + jdkCal.get(Calendar.DAY_OF_MONTH)); Date co = jdkCal.getTime(); - logln("Change over (Oct 15 1582) = " + co + " (" + + System.out.println("Change over (Oct 15 1582) = " + co + " (" + co.getTime() + ")"); long a = jdkCal.getTime().getTime(); Date c = jdkCal.getTime(); @@ -211,9 +221,9 @@ public void Test6274757() { long b = c.getTime(); if (a != b) { - errln("ERROR: " + a + " != " + b); + fail("ERROR: " + a + " != " + b); } else { - logln(a + " = " + b); + System.out.println(a + " = " + b); } } finally { TimeZone.setDefault(savedTz); @@ -224,16 +234,17 @@ public void Test6274757() { * @bug 6314387 * JCK6.0: api/java_util/Date/index.html#misc fails, mustang */ + @Test public void Test6314387() { Date d = new Date(Long.MAX_VALUE); int y = d.getYear(); if (y != 292277094) { - errln("yesr: got " + y + ", expected 292277094"); + fail("yesr: got " + y + ", expected 292277094"); } d = new Date(Long.MIN_VALUE); y = d.getYear(); if (y != 292267155) { - errln("yesr: got " + y + ", expected 292267155"); + fail("yesr: got " + y + ", expected 292267155"); } } } diff --git a/test/jdk/java/util/Date/DateTest.java b/test/jdk/java/util/Date/DateTest.java index 98392760ba3..6740cb16faa 100644 --- a/test/jdk/java/util/Date/DateTest.java +++ b/test/jdk/java/util/Date/DateTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,23 +25,24 @@ * @test * @bug 4143459 * @summary test Date - * @library /java/text/testlib + * @run junit DateTest */ import java.text.*; import java.util.*; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + @SuppressWarnings("deprecation") -public class DateTest extends IntlTest +public class DateTest { - public static void main(String[] args) throws Exception { - new DateTest().run(args); - } - /** * @bug 4143459 * Warning: Use TestDefaultZone() for complete testing of this bug. */ + @Test public void TestDefaultZoneLite() { // Note: This test is redundant with TestDefaultZone(). It was added by // request to provide a short&sweet test for this bug. It does not test @@ -57,7 +58,7 @@ public void TestDefaultZoneLite() { d.setHours(6); TimeZone.setDefault(TimeZone.getTimeZone("PST")); if (d.getHours() != 22) { - errln("Fail: Date.setHours()/getHours() ignoring default zone"); + fail("Fail: Date.setHours()/getHours() ignoring default zone"); } } finally { TimeZone.setDefault(save); } @@ -66,6 +67,7 @@ public void TestDefaultZoneLite() { /** * @bug 4143459 */ + @Test public void TestDefaultZone() { // Various problems can creep up, with the current implementation of Date, // when the default zone is changed. @@ -87,7 +89,7 @@ public void TestDefaultZone() { // sub-object (most Date objects), and a Date object with a Calendar // sub-object. We make two passes to cover the two cases. for (int pass=0; pass<2; ++pass) { - logln(pass == 0 ? "Normal Date object" : "Date with Calendar sub-object"); + System.out.println(pass == 0 ? "Normal Date object" : "Date with Calendar sub-object"); TimeZone.setDefault(GMT); d = new Date(refstr); @@ -96,7 +98,7 @@ public void TestDefaultZone() { d.setYear(d.getYear()); } if (d.getTime() != ref.getTime()) { - errln("FAIL: new Date(\"" + refstr + "\") x GMT -> " + d + + fail("FAIL: new Date(\"" + refstr + "\") x GMT -> " + d + " " + d.getTime() + " ms"); } @@ -104,7 +106,7 @@ public void TestDefaultZone() { d.getDay(), d.getHours(), d.getTimezoneOffset() }; for (int i=0; i PER_LOOP_LIMIT) - logln("WARNING: Date constructor/getYear slower than " + + System.out.println("WARNING: Date constructor/getYear slower than " + PER_LOOP_LIMIT + " ms"); } static double PER_LOOP_LIMIT = 3.0; @@ -150,6 +153,7 @@ public void TestPerformance592() /** * Verify that the Date(String) constructor works. */ + @Test public void TestParseOfGMT() { Date OUT = null; @@ -164,7 +168,7 @@ public void TestParseOfGMT() // logln("PASS"); } else { - errln( "Expected: " + + fail( "Expected: " + new Date( expectedVal ) + ": " + expectedVal + @@ -178,56 +182,58 @@ public void TestParseOfGMT() // Check out Date's behavior with large negative year values; bug 664 // As of the fix to bug 4056585, Date should work correctly with // large negative years. + @Test public void TestDateNegativeYears() { Date d1= new Date(80,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); d1= new Date(-80,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); boolean e = false; try { d1= new Date(-800000,-1,2); - logln(d1.toString()); + System.out.println(d1.toString()); } catch (IllegalArgumentException ex) { e = true; } - if (e) errln("FAIL: Saw exception for year -800000"); - else logln("Pass: No exception for year -800000"); + if (e) fail("FAIL: Saw exception for year -800000"); + else System.out.println("Pass: No exception for year -800000"); } // Verify the behavior of Date + @Test public void TestDate480() { TimeZone save = TimeZone.getDefault(); try { TimeZone.setDefault(TimeZone.getTimeZone("PST")); Date d1=new java.util.Date(97,8,13,10,8,13); - logln("d = "+d1); + System.out.println("d = "+d1); Date d2=new java.util.Date(97,8,13,30,8,13); // 20 hours later - logln("d+20h = "+d2); + System.out.println("d+20h = "+d2); double delta = (d2.getTime() - d1.getTime()) / 3600000; - logln("delta = " + delta + "h"); + System.out.println("delta = " + delta + "h"); - if (delta != 20.0) errln("Expected delta of 20; got " + delta); + if (delta != 20.0) fail("Expected delta of 20; got " + delta); Calendar cal = Calendar.getInstance(); cal.clear(); cal.set(1997,8,13,10,8,13); Date t1 = cal.getTime(); - logln("d = "+t1); + System.out.println("d = "+t1); cal.clear(); cal.set(1997,8,13,30,8,13); // 20 hours later Date t2 = cal.getTime(); - logln("d+20h = "+t2); + System.out.println("d+20h = "+t2); double delta2 = (t2.getTime() - t1.getTime()) / 3600000; - logln("delta = " + delta2 + "h"); + System.out.println("delta = " + delta2 + "h"); - if (delta != 20.0) errln("Expected delta of 20; got " + delta2); + if (delta != 20.0) fail("Expected delta of 20; got " + delta2); } finally { TimeZone.setDefault(save); diff --git a/test/jdk/java/util/Date/TimestampTest.java b/test/jdk/java/util/Date/TimestampTest.java index 950f0a5fb91..06bcab22dad 100644 --- a/test/jdk/java/util/Date/TimestampTest.java +++ b/test/jdk/java/util/Date/TimestampTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,23 +26,24 @@ * @bug 5008227 * @summary Make sure that changes to the Date class don't break java.sql.Timestamp. * @modules java.sql - * @library /java/text/testlib + * @run junit TimestampTest */ import java.util.*; import java.sql.Timestamp; -public class TimestampTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TimestampTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TimestampTest { /** * 5008227: java.sql.Timestamp.after() is not returning correct result * * Test before(), after(), equals(), compareTo() and getTime(). */ + @Test public void Test5008227() { long t = System.currentTimeMillis(); Timestamp ts1 = new Timestamp(t), ts2 = new Timestamp(t); @@ -88,28 +89,28 @@ private void compareTimestamps(Timestamp ts1, Timestamp ts2, int expected) { boolean expectedResult = expected > 0; boolean result = ts1.after(ts2); if (result != expectedResult) { - errln("ts1.after(ts2) returned " + result + fail("ts1.after(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } expectedResult = expected < 0; result = ts1.before(ts2); if (result != expectedResult) { - errln("ts1.before(ts2) returned " + result + fail("ts1.before(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } expectedResult = expected == 0; result = ts1.equals(ts2); if (result != expectedResult) { - errln("ts1.equals(ts2) returned " + result + fail("ts1.equals(ts2) returned " + result + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } int x = ts1.compareTo(ts2); int y = (x > 0) ? 1 : (x < 0) ? -1 : 0; if (y != expected) { - errln("ts1.compareTo(ts2) returned " + x + ", expected " + fail("ts1.compareTo(ts2) returned " + x + ", expected " + relation(expected, "") + "0" + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } @@ -122,7 +123,7 @@ private void compareTimestamps(Timestamp ts1, Timestamp ts2, int expected) { z = (n1 > n2) ? 1 : (n1 < n2) ? -1 : 0; } if (z != expected) { - errln("ts1.getTime() " + relation(z, "==") + " ts2.getTime(), expected " + fail("ts1.getTime() " + relation(z, "==") + " ts2.getTime(), expected " + relation(expected, "==") + ". (ts1=" + ts1 + ", ts2=" + ts2 + ")"); } diff --git a/test/jdk/java/util/Locale/Bug8179071.java b/test/jdk/java/util/Locale/AliasesShouldBeRecognizedInCLDR.java similarity index 51% rename from test/jdk/java/util/Locale/Bug8179071.java rename to test/jdk/java/util/Locale/AliasesShouldBeRecognizedInCLDR.java index bb4ae5dfa40..fa41aeea07c 100644 --- a/test/jdk/java/util/Locale/Bug8179071.java +++ b/test/jdk/java/util/Locale/AliasesShouldBeRecognizedInCLDR.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,10 +26,10 @@ * @bug 8179071 8202537 8231273 8251317 * @summary Test that language aliases of CLDR supplemental metadata are handled correctly. * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=CLDR Bug8179071 + * @run junit/othervm -Djava.locale.providers=CLDR AliasesShouldBeRecognizedInCLDR */ -/** +/* * This fix is dependent on a particular version of CLDR data. */ @@ -38,53 +38,61 @@ import java.util.Arrays; import java.util.HashSet; import java.util.Locale; -import java.util.Map; import java.util.Set; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; -public class Bug8179071 { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; - // Deprecated and Legacy tags. - // As of CLDR 38, language aliases for some of the legacy tags have been removed. +public class AliasesShouldBeRecognizedInCLDR { + + /* + * Deprecated and Legacy tags. + * As of CLDR 38, language aliases for some legacy tags have been removed. + */ private static final Set LegacyAliases = Set.of( "zh-guoyu", "zh-min-nan", "i-klingon", "i-tsu", "sgn-CH-DE", "mo", "i-tay", "scc", "i-hak", "sgn-BE-FR", "i-lux", "tl", "zh-hakka", "i-ami", "aa-SAAHO", "zh-xiang", "i-pwn", "sgn-BE-NL", "jw", "sh", "i-bnn"); - // expected month format data for locales after language aliases replacement. - private static final Map shortJanuaryNames = Map.of( "pa-PK", "\u0a1c\u0a28", - "uz-AF" , "yan", - "sr-ME", "\u0458\u0430\u043d", - "scc", "\u0458\u0430\u043d", - "sh", "jan", - "ha-Latn-NE", "Jan", - "i-lux", "Jan."); - - private static void test(String tag, String expected) { + // Ensure the display name for the given tag's January is correct + @ParameterizedTest + @MethodSource("shortJanuaryNames") + public void janDisplayNameTest(String tag, String expected) { Locale target = Locale.forLanguageTag(tag); Month day = Month.JANUARY; TextStyle style = TextStyle.SHORT; String actual = day.getDisplayName(style, target); - if (!actual.equals(expected)) { - throw new RuntimeException("failed for locale " + tag + " actual output " + actual +" does not match with " + expected); - } + assertEquals(expected, actual); } - /** - * getAvailableLocales() should not contain any deprecated or Legacy language tags - */ - private static void checkInvalidTags() { - Set invalidTags = new HashSet<>(); - Arrays.asList(Locale.getAvailableLocales()).stream() - .map(loc -> loc.toLanguageTag()) - .forEach( tag -> {if(LegacyAliases.contains(tag)) {invalidTags.add(tag);}}); - if (!invalidTags.isEmpty()) { - throw new RuntimeException("failed: Deprecated and Legacy tags found " + invalidTags + " in AvailableLocales "); - } + // Expected month format data for locales after language aliases replacement. + private static Stream shortJanuaryNames() { + return Stream.of( + Arguments.of("pa-PK", "\u0a1c\u0a28"), + Arguments.of("uz-AF", "yan"), + Arguments.of("sr-ME", "\u0458\u0430\u043d"), + Arguments.of("scc", "\u0458\u0430\u043d"), + Arguments.of("sh", "jan"), + Arguments.of("ha-Latn-NE", "Jan"), + Arguments.of("i-lux", "Jan.") + ); } - public static void main(String[] args) { - shortJanuaryNames.forEach(Bug8179071::test); - checkInvalidTags(); + // getAvailableLocales() should not contain any deprecated or Legacy language tags + @Test + public void invalidTagsTest() { + Set invalidTags = new HashSet<>(); + Arrays.stream(Locale.getAvailableLocales()) + .map(Locale::toLanguageTag) + .forEach(tag -> {if(LegacyAliases.contains(tag)) {invalidTags.add(tag);}}); + assertTrue(invalidTags.isEmpty(), + "Deprecated and Legacy tags found " + invalidTags + " in AvailableLocales "); } } diff --git a/test/jdk/java/util/Locale/Bug8035133.java b/test/jdk/java/util/Locale/Bug8035133.java deleted file mode 100644 index 8d86ca02498..00000000000 --- a/test/jdk/java/util/Locale/Bug8035133.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 8035133 - * @summary Checks that the tags matching the range with quality weight q=0 - * e.g. en;q=0 must be elimited and must not be the part of output - */ - -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Locale; - - -public class Bug8035133 { - - private static boolean err = false; - - public static void main(String[] args) { - - // checking Locale.lookup with de-ch;q=0 - checkLookup("en;q=0.1, *-ch;q=0.5, de-ch;q=0", - "de-ch, en, fr-ch", "fr-CH"); - - /* checking Locale.lookup with *;q=0 '*' should be ignored - * in lookup - */ - checkLookup("en;q=0.1, *-ch;q=0.5, *;q=0", - "de-ch, en, fr-ch", "de-CH"); - - // checking Locale.filter with fr-ch;q=0 in BASIC_FILTERING - checkFilter("en;q=0.1, fr-ch;q=0.0, de-ch;q=0.5", - "de-ch, en, fr-ch", "de-CH, en"); - - // checking Locale.filter with *;q=0 in BASIC_FILTERING - checkFilter("de-ch;q=0.6, *;q=0", "de-ch, fr-ch", ""); - - // checking Locale.filter with *;q=0 in BASIC_FILTERING - checkFilter("de-ch;q=0.6, de;q=0", "de-ch", ""); - - // checking Locale.filter with *;q=0.6, en;q=0 in BASIC_FILTERING - checkFilter("*;q=0.6, en;q=0", "de-ch, hi-in, en", "de-CH, hi-IN"); - - // checking Locale.filter with de-ch;q=0 in EXTENDED_FILTERING - checkFilter("en;q=0.1, *-ch;q=0.5, de-ch;q=0", - "de-ch, en, fr-ch", "fr-CH, en"); - - /* checking Locale.filter with *-ch;q=0 in EXTENDED_FILTERING which - * must make filter to return "" empty or no match - */ - checkFilter("de-ch;q=0.5, *-ch;q=0", "de-ch, fr-ch", ""); - - /* checking Locale.filter with *;q=0 in EXTENDED_FILTERING which - * must make filter to return "" empty or no match - */ - checkFilter("*-ch;q=0.5, *;q=0", "de-ch, fr-ch", ""); - - /* checking Locale.filter with *;q=0.6, *-Latn;q=0 in - * EXTENDED_FILTERING - */ - checkFilter("*;q=0.6, *-Latn;q=0", "de-ch, hi-in, en-Latn", - "de-CH, hi-IN"); - - if (err) { - throw new RuntimeException("[LocaleMatcher method(s) failed]"); - } - - } - - private static void checkLookup(String ranges, String tags, - String expectedLocale) { - - List priorityList = Locale.LanguageRange - .parse(ranges); - List localeList = generateLocales(tags); - Locale loc = Locale.lookup(priorityList, localeList); - String actualLocale - = loc.toLanguageTag(); - - if (!actualLocale.equals(expectedLocale)) { - System.err.println("Locale.lookup failed with ranges: " + ranges - + " Expected: " + expectedLocale - + " Actual: " + actualLocale); - err = true; - } - - } - - private static void checkFilter(String ranges, String tags, - String expectedLocales) { - - List priorityList = Locale.LanguageRange - .parse(ranges); - List localeList = generateLocales(tags); - String actualLocales = getLocalesAsString( - Locale.filter(priorityList, localeList)); - - if (!actualLocales.equals(expectedLocales)) { - System.err.println("Locale.filter failed with ranges: " + ranges - + " Expected: " + expectedLocales - + " Actual: " + actualLocales); - err = true; - } - - } - - private static List generateLocales(String tags) { - if (tags == null) { - return null; - } - - List localeList = new ArrayList<>(); - if (tags.equals("")) { - return localeList; - } - String[] t = tags.split(", "); - for (String tag : t) { - localeList.add(Locale.forLanguageTag(tag)); - } - return localeList; - } - - private static String getLocalesAsString(List locales) { - StringBuilder sb = new StringBuilder(); - - Iterator itr = locales.iterator(); - if (itr.hasNext()) { - sb.append(itr.next().toLanguageTag()); - } - while (itr.hasNext()) { - sb.append(", "); - sb.append(itr.next().toLanguageTag()); - } - - return sb.toString().trim(); - } - -} diff --git a/test/jdk/java/util/Locale/CaseCheckVariant.java b/test/jdk/java/util/Locale/CaseCheckVariant.java new file mode 100644 index 00000000000..6b621e244ee --- /dev/null +++ b/test/jdk/java/util/Locale/CaseCheckVariant.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4210525 + * @summary Locale variant should not be case folded + * @run junit CaseCheckVariant + */ + +import java.util.Locale; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class CaseCheckVariant { + + static final String LANG = "en"; + static final String COUNTRY = "US"; + + /** + * When a locale is created with a given variant, ensure + * that the variant is not case normalized. + */ + @ParameterizedTest + @MethodSource("variants") + public void variantCaseTest(String variant) { + Locale aLocale = new Locale(LANG, COUNTRY, variant); + String localeVariant = aLocale.getVariant(); + assertEquals(localeVariant, variant); + } + + private static Stream variants() { + return Stream.of( + "socal", + "Norcal" + ); + } +} diff --git a/test/jdk/java/util/Locale/Bug8154797.java b/test/jdk/java/util/Locale/CompareProviderFormats.java similarity index 68% rename from test/jdk/java/util/Locale/Bug8154797.java rename to test/jdk/java/util/Locale/CompareProviderFormats.java index 95599f25df8..6bb27c8620e 100644 --- a/test/jdk/java/util/Locale/Bug8154797.java +++ b/test/jdk/java/util/Locale/CompareProviderFormats.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,43 +28,65 @@ * java.base/sun.util.resources * jdk.localedata * @summary Test for checking HourFormat and GmtFormat resources are retrieved from - * COMPAT and CLDR Providers. + * COMPAT and CLDR Providers. + * @run junit CompareProviderFormats */ import java.util.HashMap; import java.util.Locale; import java.util.Map; import java.util.ResourceBundle; +import java.util.stream.Stream; + import sun.util.locale.provider.LocaleProviderAdapter.Type; import sun.util.locale.provider.LocaleProviderAdapter; -public class Bug8154797 { +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.MethodSource; + +public class CompareProviderFormats { static Map expectedResourcesMap = new HashMap<>(); static final String GMT_RESOURCE_KEY = "timezone.gmtFormat"; static final String HMT_RESOURCE_KEY = "timezone.hourFormat"; static final String GMT = "Gmt"; static final String HMT = "Hmt"; - static void generateExpectedValues() { + /** + * Fill the expectedResourcesMap with the desired key / values + */ + @BeforeAll + static void populateResourcesMap() { expectedResourcesMap.put("FR" + GMT, "UTC{0}"); expectedResourcesMap.put("FR" + HMT, "+HH:mm;\u2212HH:mm"); expectedResourcesMap.put("FI" + HMT, "+H.mm;-H.mm"); expectedResourcesMap.put("FI" + GMT, "UTC{0}"); - /* For root locale, en_US, de_DE, hi_IN, ja_JP,Root locale resources - * should be returned. + /* For root locale, en_US, de_DE, hi_IN, ja_JP, Root locale resources + * should be returned. */ - expectedResourcesMap.put(GMT, "GMT{0}"); //Root locale resource - expectedResourcesMap.put(HMT, "+HH:mm;-HH:mm"); //Root locale resource + expectedResourcesMap.put(GMT, "GMT{0}"); // Root locale resource + expectedResourcesMap.put(HMT, "+HH:mm;-HH:mm"); // Root locale resource + } + + /** + * For each locale, ensure that the returned resources for gmt and hmt match + * the expected resources for both COMPAT and CLDR + */ + @ParameterizedTest + @MethodSource("localeProvider") + public void compareResourcesTest(Locale loc) { + compareResources(loc); } - static void compareResources(Locale loc) { + private void compareResources(Locale loc) { String mapKeyHourFormat = HMT, mapKeyGmtFormat = GMT; ResourceBundle compatBundle, cldrBundle; compatBundle = LocaleProviderAdapter.forJRE().getLocaleResources(loc) .getJavaTimeFormatData(); cldrBundle = LocaleProviderAdapter.forType(Type.CLDR) .getLocaleResources(loc).getJavaTimeFormatData(); - if (loc.getCountry() == "FR" || loc.getCountry() == "FI") { + + if (loc.getCountry().equals("FR") || loc.getCountry().equals("FI")) { mapKeyHourFormat = loc.getCountry() + HMT; mapKeyGmtFormat = loc.getCountry() + GMT; } @@ -77,23 +99,17 @@ static void compareResources(Locale loc) { .equals(cldrBundle.getString(GMT_RESOURCE_KEY)) && expectedResourcesMap.get(mapKeyHourFormat) .equals(cldrBundle.getString(HMT_RESOURCE_KEY)))) { - throw new RuntimeException("Retrieved resource does not match with " + " expected string for Locale " + compatBundle.getLocale()); - } - } - public static void main(String args[]) { - Bug8154797.generateExpectedValues(); - Locale[] locArr = {new Locale("hi", "IN"), Locale.UK, new Locale("fi", "FI"), - Locale.ROOT, Locale.GERMAN, Locale.JAPANESE, - Locale.ENGLISH, Locale.FRANCE}; - for (Locale loc : locArr) { - Bug8154797.compareResources(loc); - } + private static Stream localeProvider() { + return Stream.of( + new Locale("hi", "IN"), + Locale.UK, new Locale("fi", "FI"), + Locale.ROOT, Locale.GERMAN, Locale.JAPANESE, + Locale.ENGLISH, Locale.FRANCE + ); } - } - diff --git a/test/jdk/java/util/Locale/FilteringModeTest.java b/test/jdk/java/util/Locale/FilteringModeTest.java index 949a3ad4e54..185f4aff08a 100644 --- a/test/jdk/java/util/Locale/FilteringModeTest.java +++ b/test/jdk/java/util/Locale/FilteringModeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,67 +25,61 @@ * @test * @bug 8210443 * @summary Check values() and valueOf(String name) of Locale.FilteringMode. - * @run main FilteringModeTest + * @run junit FilteringModeTest */ import java.util.Arrays; import java.util.List; import java.util.Locale.FilteringMode; import java.util.stream.Collectors; +import java.util.stream.Stream; + +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; public class FilteringModeTest { - private static boolean err = false; - private static List modeNames = List.of("AUTOSELECT_FILTERING", - "EXTENDED_FILTERING", - "IGNORE_EXTENDED_RANGES", - "MAP_EXTENDED_RANGES", - "REJECT_EXTENDED_RANGES"); - public static void main(String[] args) throws Exception { - testValues(); - testValueOf(); + private static final List expectedModeNames = List.of( + "AUTOSELECT_FILTERING", + "EXTENDED_FILTERING", + "IGNORE_EXTENDED_RANGES", + "MAP_EXTENDED_RANGES", + "REJECT_EXTENDED_RANGES" + ); - if (err) { - throw new RuntimeException("Failed."); - } + // Ensure valueOf() exceptions are thrown + @Test + public void valueOfExceptionsTest() { + assertThrows(IllegalArgumentException.class, + () -> FilteringMode.valueOf("").name()); + assertThrows(NullPointerException.class, + () -> FilteringMode.valueOf(null).name()); } - private static void testValueOf() { - try { - FilteringMode.valueOf("").name(); - err = true; - System.err.println("IAE should be thrown for valueOf(\"\")."); - } catch (IllegalArgumentException ex) { - } - - try { - FilteringMode.valueOf(null).name(); - err = true; - System.err.println("NPE should be thrown for valueOf(null)."); - } catch (NullPointerException ex) { - } + // Ensure valueOf() returns expected results + @ParameterizedTest + @MethodSource("modes") + public void valueOfTest(String expectedName) { + String name = FilteringMode.valueOf(expectedName).name(); + assertEquals(expectedName, name); + } - modeNames.forEach((expectedName) -> { - String name = FilteringMode.valueOf(expectedName).name(); - if (!expectedName.equals(name)) { - err = true; - System.err.println("FilteringMode.valueOf(" + expectedName - + ") returned unexpected value. Expected: " - + expectedName + ", got: " + name); - } - }); + private static Stream modes() { + return expectedModeNames.stream(); } - private static void testValues() { + // Ensure values() returns expected results + @Test + public void valuesTest() { FilteringMode[] modeArray = FilteringMode.values(); - List modeNames2 = Arrays.stream(modeArray) + List actualNames = Arrays.stream(modeArray) .map(mode -> mode.name()) .collect(Collectors.toList()); - - if (!modeNames.equals(modeNames2)) { - err = true; - System.err.println("FilteringMode.values() returned unexpected value. Expected:" - + modeNames + " Got:" + modeNames2); - } + assertEquals(expectedModeNames, actualNames); } } diff --git a/test/jdk/java/util/Locale/Bug8004240.java b/test/jdk/java/util/Locale/GetAdapterPreference.java similarity index 66% rename from test/jdk/java/util/Locale/Bug8004240.java rename to test/jdk/java/util/Locale/GetAdapterPreference.java index 6725c792cb7..fd21ac5fa60 100644 --- a/test/jdk/java/util/Locale/Bug8004240.java +++ b/test/jdk/java/util/Locale/GetAdapterPreference.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,25 +26,27 @@ * @bug 8004240 * @summary Verify that getAdapterPreference returns an unmodifiable list. * @modules java.base/sun.util.locale.provider - * @compile -XDignore.symbol.file Bug8004240.java - * @run main Bug8004240 + * @compile -XDignore.symbol.file GetAdapterPreference.java + * @run junit GetAdapterPreference */ import java.util.List; import sun.util.locale.provider.LocaleProviderAdapter; -public class Bug8004240 { +import org.junit.jupiter.api.Test; - public static void main(String[] args) { - List types = LocaleProviderAdapter.getAdapterPreference(); +import static org.junit.jupiter.api.Assertions.assertThrows; - try { - types.set(0, null); - } catch (UnsupportedOperationException e) { - // success - return; - } +public class GetAdapterPreference { - throw new RuntimeException("LocaleProviderAdapter.getAdapterPrefence() returned a modifiable list."); + /** + * Test that the list returned from getAdapterPreference() + * cannot be modified. + */ + @Test + public void immutableTest() { + List types = LocaleProviderAdapter.getAdapterPreference(); + assertThrows(UnsupportedOperationException.class, () -> types.set(0, null), + "Trying to modify list returned from LocaleProviderAdapter.getAdapterPreference() did not throw UOE"); } } diff --git a/test/jdk/java/util/Locale/GetInstanceCheck.java b/test/jdk/java/util/Locale/GetInstanceCheck.java new file mode 100644 index 00000000000..80dfb7d5d7b --- /dev/null +++ b/test/jdk/java/util/Locale/GetInstanceCheck.java @@ -0,0 +1,126 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 6312358 + * @summary Verify that an NPE is thrown by invoking Locale.getInstance() with + * any argument being null. + * @modules java.base/java.util:open + * @run junit GetInstanceCheck + */ + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.Locale; +import java.util.stream.Stream; + +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.fail; + +public class GetInstanceCheck { + + static Method getInstanceMethod; + static final String NAME = "getInstance"; + + /** + * Initialize the non-public Locale.getInstance() method. + */ + @BeforeAll + static void initializeMethod() { + try { + // Locale.getInstance is not directly accessible. + getInstanceMethod = Locale.class.getDeclaredMethod( + NAME, String.class, String.class, String.class + ); + getInstanceMethod.setAccessible(true); + } catch (java.lang.NoSuchMethodException exc) { + // The test should fail if we can not test the desired method + fail(String.format("Tried to get the method '%s' which was not found," + + " further testing is not possible, failing test", NAME)); + } + } + + /** + * Exists as sanity check that Locale.getInstance() will not throw + * an NPE if no arguments are null. + */ + @ParameterizedTest + @MethodSource("passingArguments") + public void noNPETest(String language, String country, String variant) + throws IllegalAccessException { + try { + getInstanceMethod.invoke(null, language, country, variant); + } catch (InvocationTargetException exc) { + // Determine underlying exception + Throwable cause = exc.getCause(); + if (exc.getCause() instanceof NullPointerException) { + fail(String.format("%s should not be thrown when no args are null", cause)); + } else { + fail(String.format("%s unexpectedly thrown, when no exception should be thrown", cause)); + } + } + } + + /** + * Make sure the Locale.getInstance() method throws an NPE + * if any given argument is null. + */ + @ParameterizedTest + @MethodSource("failingArguments") + public void throwNPETest(String language, String country, String variant) + throws IllegalAccessException { + try { + getInstanceMethod.invoke(null, language, country, variant); + fail("Should NPE with any argument set to null"); + } catch (InvocationTargetException exc) { + // Determine underlying exception + Throwable cause = exc.getCause(); + if (cause instanceof NullPointerException) { + System.out.println("NPE successfully thrown"); + } else { + fail(cause + " is thrown, when NPE should have been thrown"); + } + } + } + + private static Stream passingArguments() { + return Stream.of( + Arguments.of("null", "GB", ""), + Arguments.of("en", "null", ""), + Arguments.of("en", "GB", "null") + ); + } + + private static Stream failingArguments() { + return Stream.of( + Arguments.of(null, "GB", ""), + Arguments.of("en", null, ""), + Arguments.of("en", "GB", null) + ); + } +} diff --git a/test/jdk/java/util/Locale/Bug4518797.java b/test/jdk/java/util/Locale/HashCodeShouldBeThreadSafe.java similarity index 90% rename from test/jdk/java/util/Locale/Bug4518797.java rename to test/jdk/java/util/Locale/HashCodeShouldBeThreadSafe.java index f25b64fbedb..4b165b1bec7 100644 --- a/test/jdk/java/util/Locale/Bug4518797.java +++ b/test/jdk/java/util/Locale/HashCodeShouldBeThreadSafe.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,14 +24,18 @@ * @test * @bug 4518797 * @summary Make sure that hashCode() and read/writeObject() are thread-safe. - * @run main Bug4518797 10 + * @run main HashCodeShouldBeThreadSafe 10 */ -import java.util.*; -import java.io.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.Locale; -// Usage: java Bug4518797 [duration] -public class Bug4518797 { +// Usage: java HashCodeShouldBeThreadSafe [duration] +public class HashCodeShouldBeThreadSafe { static volatile boolean runrun = true; static volatile String message = null; diff --git a/test/jdk/java/util/Locale/HashCodeTest.java b/test/jdk/java/util/Locale/HashCodeTest.java index a911515274f..d6601f81a6d 100644 --- a/test/jdk/java/util/Locale/HashCodeTest.java +++ b/test/jdk/java/util/Locale/HashCodeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,28 +20,35 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 4944561 * @summary Test hashCode() to have less than 10% of hash code conflicts. * @modules jdk.localedata + * @run junit HashCodeTest */ import java.util.HashMap; import java.util.Locale; import java.util.Map; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertFalse; + public class HashCodeTest { - public static void main(String[] args) { + // Ensure Locale.hashCode() has less than 10% conflicts + @Test + public void hashConflictsTest() { Locale[] locales = Locale.getAvailableLocales(); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; Map map = new HashMap<>(locales.length); int conflicts = 0; - for (int i = 0; i < locales.length; i++) { - Locale loc = locales[i]; + for (Locale loc : locales) { int hc = loc.hashCode(); min = Math.min(hc, min); max = Math.max(hc, max); @@ -55,9 +62,7 @@ public static void main(String[] args) { } System.out.println(locales.length + " locales: conflicts=" + conflicts + ", min=" + min + ", max=" + max + ", diff=" + (max - min)); - if (conflicts >= (locales.length / 10)) { - throw new RuntimeException("too many conflicts: " + conflicts - + " per " + locales.length + " locales"); - } + assertFalse(conflicts >= (locales.length / 10), + String.format("%s conflicts per %s locales", conflicts, locales.length)); } } diff --git a/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java b/test/jdk/java/util/Locale/LanguageSubtagRegistryTest.java index cb3d4dde914..d143e025dd5 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 + * 8327631 8332424 8334418 8344589 * @summary Checks the IANA language subtag registry data update - * (LSR Revision: 2024-06-14) with Locale and Locale.LanguageRange + * (LSR Revision: 2024-11-19) with Locale and Locale.LanguageRange * class methods. * @run main LanguageSubtagRegistryTest */ diff --git a/test/jdk/java/util/Locale/Bug4184873Test.java b/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java similarity index 67% rename from test/jdk/java/util/Locale/Bug4184873Test.java rename to test/jdk/java/util/Locale/LegacyCodesClassInvariant.java index 05e758284df..8eb11639c87 100644 --- a/test/jdk/java/util/Locale/Bug4184873Test.java +++ b/test/jdk/java/util/Locale/LegacyCodesClassInvariant.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,13 +20,14 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* - @test - @summary test that locale invariants are preserved across serialization - @library /java/text/testlib - @run main Bug4184873Test - @bug 4184873 -*/ + * @test + * @bug 4184873 + * @summary test that locale invariants are preserved across serialization. + * @run junit LegacyCodesClassInvariant + */ + /* * This file is available under and governed by the GNU General Public * License version 2 only, as published by the Free Software Foundation. @@ -61,21 +62,21 @@ * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. */ -import java.util.*; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.ObjectInputStream; +import java.util.Locale; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.fail; /** * A Locale can never contain the following language codes: he, yi or id. */ -public class Bug4184873Test extends IntlTest { - public static void main(String[] args) throws Exception { - if (args.length == 1 && args[0].equals("prepTest")) { - prepTest(); - } else { - new Bug4184873Test().run(args); - } - } - +public class LegacyCodesClassInvariant { + @Test public void testIt() throws Exception { verify("he"); verify("yi"); @@ -88,49 +89,22 @@ private void verify(String lang) { if (in != null) { final Locale loc = (Locale)in.readObject(); final Locale expected = new Locale(lang, "XX"); - if (!(expected.equals(loc))) { - errln("Locale didn't maintain invariants for: "+lang); - errln(" got: "+loc); - errln(" excpeted: "+expected); - } else { - logln("Locale "+lang+" worked"); - } + assertEquals(expected, loc, + "Locale didn't maintain invariants for: "+lang); in.close(); } } catch (Exception e) { - errln(e.toString()); + fail(e.toString()); } } private ObjectInputStream getStream(String lang) { try { - final File f = new File(System.getProperty("test.src", "."), "Bug4184873_"+lang); + final File f = new File(System.getProperty("test.src", "."), "LegacyCodesClassInvariant_"+lang); return new ObjectInputStream(new FileInputStream(f)); } catch (Exception e) { - errln(e.toString()); + fail(e.toString()); return null; } } - - /** - * Create serialized output files of the test locales. After they are created, these test - * files should be corrupted (by hand) to contain invalid locale name values. - */ - private static void prepTest() { - outputLocale("he"); - outputLocale("yi"); - outputLocale("id"); - } - - private static void outputLocale(String lang) { - try { - ObjectOutputStream out = new ObjectOutputStream( - new FileOutputStream("Bug4184873_"+lang)); - out.writeObject(new Locale(lang, "XX")); - out.close(); - } catch (Exception e) { - System.out.println(e); - } - } - } diff --git a/test/jdk/java/util/Locale/Bug4184873_he b/test/jdk/java/util/Locale/LegacyCodesClassInvariant_he similarity index 100% rename from test/jdk/java/util/Locale/Bug4184873_he rename to test/jdk/java/util/Locale/LegacyCodesClassInvariant_he diff --git a/test/jdk/java/util/Locale/Bug4184873_id b/test/jdk/java/util/Locale/LegacyCodesClassInvariant_id similarity index 100% rename from test/jdk/java/util/Locale/Bug4184873_id rename to test/jdk/java/util/Locale/LegacyCodesClassInvariant_id diff --git a/test/jdk/java/util/Locale/Bug4184873_yi b/test/jdk/java/util/Locale/LegacyCodesClassInvariant_yi similarity index 100% rename from test/jdk/java/util/Locale/Bug4184873_yi rename to test/jdk/java/util/Locale/LegacyCodesClassInvariant_yi diff --git a/test/jdk/java/util/Locale/LocaleConstructors.java b/test/jdk/java/util/Locale/LocaleConstructors.java new file mode 100644 index 00000000000..0ef4c6eb287 --- /dev/null +++ b/test/jdk/java/util/Locale/LocaleConstructors.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4316602 + * @author joconner + * @summary Verify all Locale constructors and of() methods + * @run junit LocaleConstructors + */ + +import java.util.Locale; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +/** + * This class tests to ensure that the language, language/country, and + * language/country/variant Locale constructors + of() method are all allowed. + */ +public class LocaleConstructors { + + static final String LANG = "en"; + static final String COUNTRY = "US"; + static final String VAR = "socal"; + + // Test Locale constructor and .of() allow (language) argument(s) + @Test + public void langTest() { + Locale otherLocale = new Locale(LANG); + assertEquals(otherLocale.toString(), LANG); + } + + // Test Locale constructor and .of() allow (language, constructor) argument(s) + @Test + public void langCountryTest() { + Locale otherLocale = new Locale(LANG, COUNTRY); + assertEquals(otherLocale.toString(), String.format("%s_%s", + LANG, COUNTRY)); + } + + // Test Locale constructor and .of() allow + // (language, constructor, variant) argument(s) + @Test + public void langCountryVariantTest() { + Locale otherLocale = new Locale(LANG, COUNTRY, VAR); + assertEquals(otherLocale.toString(), String.format("%s_%s_%s", + LANG, COUNTRY, VAR)); + } +} diff --git a/test/jdk/java/util/Locale/LocaleEnhanceTest.java b/test/jdk/java/util/Locale/LocaleEnhanceTest.java index 29c8d29ebd8..54c45031cbf 100644 --- a/test/jdk/java/util/Locale/LocaleEnhanceTest.java +++ b/test/jdk/java/util/Locale/LocaleEnhanceTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -41,24 +41,20 @@ import java.util.Locale.Builder; import java.util.Set; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + /** * @test * @bug 6875847 6992272 7002320 7015500 7023613 7032820 7033504 7004603 * 7044019 8008577 8176853 8255086 8263202 * @summary test API changes to Locale - * @library /java/text/testlib * @modules jdk.localedata * @compile LocaleEnhanceTest.java - * @run main/othervm -Djava.locale.providers=JRE,SPI -esa LocaleEnhanceTest + * @run junit/othervm -Djava.locale.providers=JRE,SPI -esa LocaleEnhanceTest */ -public class LocaleEnhanceTest extends IntlTest { - - public static void main(String[] args) throws Exception { - List argList = new ArrayList(); - argList.addAll(Arrays.asList(args)); - argList.add("-nothrow"); - new LocaleEnhanceTest().run(argList.toArray(new String[argList.size()])); - } +public class LocaleEnhanceTest { public LocaleEnhanceTest() { } @@ -83,6 +79,7 @@ public LocaleEnhanceTest() { * Ensure that Builder builds locales that have the expected * tag and java6 ID. Note the odd cases for the ID. */ + @Test public void testCreateLocaleCanonicalValid() { String[] valids = { "en-Latn-US-NewYork", "en_US_NewYork_#Latn", @@ -131,7 +128,7 @@ public void testCreateLocaleCanonicalValid() { assertEquals(msg + "id", id, l.toString()); } catch (IllegalArgumentException e) { - errln(msg + e.getMessage()); + fail(msg + e.getMessage()); } } } @@ -146,6 +143,7 @@ public void testCreateLocaleCanonicalValid() { * Note that 'New' and 'York' are invalid BCP47 variant subtags * because they are too short. */ + @Test public void testCreateLocaleMultipleVariants() { String[] valids = { @@ -188,7 +186,7 @@ public void testCreateLocaleMultipleVariants() { assertEquals(msg + "id", id, l.toString()); } catch (IllegalArgumentException e) { - errln(msg + e.getMessage()); + fail(msg + e.getMessage()); } } } @@ -197,6 +195,7 @@ public void testCreateLocaleMultipleVariants() { * Ensure that all these invalid formats are not recognized by * forLanguageTag. */ + @Test public void testCreateLocaleCanonicalInvalidSeparator() { String[] invalids = { // trailing separator @@ -240,6 +239,7 @@ public void testCreateLocaleCanonicalInvalidSeparator() { * Ensure that all current locale ids parse. Use DateFormat as a proxy * for all current locale ids. */ + @Test public void testCurrentLocales() { Locale[] locales = java.text.DateFormat.getAvailableLocales(); Builder builder = new Builder(); @@ -266,6 +266,7 @@ public void testCurrentLocales() { /** * Ensure that all icu locale ids parse. */ + @Test public void testIcuLocales() throws Exception { BufferedReader br = new BufferedReader( new InputStreamReader( @@ -282,6 +283,7 @@ public void testIcuLocales() throws Exception { /// Compatibility tests /// + @Test public void testConstructor() { // all the old weirdness still holds, no new weirdness String[][] tests = { @@ -320,6 +322,7 @@ public void testConstructor() { /// Locale API tests. /// + @Test public void testGetScript() { // forLanguageTag normalizes case Locale locale = Locale.forLanguageTag("und-latn"); @@ -334,6 +337,7 @@ public void testGetScript() { assertEquals("script is empty string", "", locale.getScript()); } + @Test public void testGetExtension() { // forLanguageTag does NOT normalize to hyphen Locale locale = Locale.forLanguageTag("und-a-some_ex-tension"); @@ -354,6 +358,7 @@ public void testGetExtension() { assertEquals("x", "y-z-blork", locale.getExtension('x')); } + @Test public void testGetExtensionKeys() { Locale locale = Locale.forLanguageTag("und-a-xx-yy-b-zz-ww"); Set result = locale.getExtensionKeys(); @@ -363,7 +368,7 @@ public void testGetExtensionKeys() { // result is not mutable try { result.add('x'); - errln("expected exception on add to extension key set"); + fail("expected exception on add to extension key set"); } catch (UnsupportedOperationException e) { // ok @@ -374,6 +379,7 @@ public void testGetExtensionKeys() { assertTrue("empty result", locale.getExtensionKeys().isEmpty()); } + @Test public void testGetUnicodeLocaleAttributes() { Locale locale = Locale.forLanguageTag("en-US-u-abc-def"); Set attributes = locale.getUnicodeLocaleAttributes(); @@ -386,6 +392,7 @@ public void testGetUnicodeLocaleAttributes() { assertTrue("empty attributes", attributes.isEmpty()); } + @Test public void testGetUnicodeLocaleType() { Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai"); assertEquals("collation", "japanese", locale.getUnicodeLocaleType("co")); @@ -413,6 +420,7 @@ public void testGetUnicodeLocaleType() { new ExpectNPE() { public void call() { Locale.forLanguageTag("").getUnicodeLocaleType(null); }}; } + @Test public void testGetUnicodeLocaleKeys() { Locale locale = Locale.forLanguageTag("und-u-co-japanese-nu-thai"); Set result = locale.getUnicodeLocaleKeys(); @@ -422,13 +430,14 @@ public void testGetUnicodeLocaleKeys() { // result is not modifiable try { result.add("frobozz"); - errln("expected exception when add to locale key set"); + fail("expected exception when add to locale key set"); } catch (UnsupportedOperationException e) { // ok } } + @Test public void testPrivateUseExtension() { Locale locale = Locale.forLanguageTag("x-y-x-blork-"); assertEquals("blork", "y-x-blork", locale.getExtension(Locale.PRIVATE_USE_EXTENSION)); @@ -437,6 +446,7 @@ public void testPrivateUseExtension() { assertEquals("no privateuse", null, locale.getExtension(Locale.PRIVATE_USE_EXTENSION)); } + @Test public void testToLanguageTag() { // lots of normalization to test here // test locales created using the constructor @@ -502,6 +512,7 @@ public void testToLanguageTag() { } + @Test public void testForLanguageTag() { // forLanguageTag implements the 'Language-Tag' production of // BCP47, so it handles private use and legacy language tags, @@ -589,7 +600,7 @@ public void testForLanguageTag() { assertEquals(msg, test[2], locale.toLanguageTag()); } catch (IllegalArgumentException e) { - errln(msg + " caught exception: " + e); + fail(msg + " caught exception: " + e); } } @@ -607,6 +618,7 @@ public void testForLanguageTag() { assertEquals("Duplicated Unicode locake key followed by an extension", "1234", locale.getExtension('c')); } + @Test public void testGetDisplayScript() { Locale latnLocale = Locale.forLanguageTag("und-latn"); Locale hansLocale = Locale.forLanguageTag("und-hans"); @@ -624,6 +636,7 @@ public void testGetDisplayScript() { Locale.setDefault(oldLocale); } + @Test public void testGetDisplayScriptWithLocale() { Locale latnLocale = Locale.forLanguageTag("und-latn"); Locale hansLocale = Locale.forLanguageTag("und-hans"); @@ -635,6 +648,7 @@ public void testGetDisplayScriptWithLocale() { assertEquals("hans DE", "Vereinfachte Chinesische Schrift", hansLocale.getDisplayScript(Locale.GERMANY)); } + @Test public void testGetDisplayName() { final Locale[] testLocales = { Locale.ROOT, @@ -688,6 +702,7 @@ public void testGetDisplayName() { /// Builder tests /// + @Test public void testBuilderSetLocale() { Builder builder = new Builder(); Builder lenientBuilder = new Builder(); @@ -730,6 +745,7 @@ public void call() { }; } + @Test public void testBuilderSetLanguageTag() { String source = "eN-LaTn-Us-NewYork-A-Xx-B-Yy-X-1-2-3"; String target = "en-Latn-US-NewYork-a-xx-b-yy-x-1-2-3"; @@ -747,6 +763,7 @@ public void testBuilderSetLanguageTag() { new BuilderILE() { public void call() { b.setLanguageTag("und-u-nu-thai-NU-chinese-xx-1234"); }}; } + @Test public void testBuilderSetLanguage() { // language is normalized to lower case String source = "eN"; @@ -792,6 +809,7 @@ public void testBuilderSetLanguage() { assertEquals("eng", "eng", result); } + @Test public void testBuilderSetScript() { // script is normalized to title case String source = "lAtN"; @@ -828,6 +846,7 @@ public void testBuilderSetScript() { assertEquals("4alpha", "Wxyz", builder.setScript("wxyz").build().getScript()); } + @Test public void testBuilderSetRegion() { // region is normalized to upper case String source = "uS"; @@ -865,6 +884,7 @@ public void testBuilderSetRegion() { assertEquals("3digit", "000", builder.setRegion("000").build().getCountry()); } + @Test public void testBuilderSetVariant() { // Variant case is not normalized in lenient variant mode String source = "NewYork"; @@ -917,6 +937,7 @@ public void testBuilderSetVariant() { new BuilderILE("abcde-fg") { public void call() { b.setVariant(arg); }}; } + @Test public void testBuilderSetExtension() { // upper case characters are normalized to lower case final char sourceKey = 'a'; @@ -1007,6 +1028,7 @@ public void testBuilderSetExtension() { assertEquals("duplicate keys", "und-u-nu-thai-xx-1234", result); } + @Test public void testBuilderAddUnicodeLocaleAttribute() { Builder builder = new Builder(); Locale locale = builder @@ -1038,6 +1060,7 @@ public void testBuilderAddUnicodeLocaleAttribute() { new BuilderILE("invalid attribute") { public void call() { b.addUnicodeLocaleAttribute("ca"); }}; } + @Test public void testBuildersetUnicodeLocaleKeyword() { // Note: most behavior is tested in testBuilderSetExtension Builder builder = new Builder(); @@ -1081,6 +1104,7 @@ public void testBuildersetUnicodeLocaleKeyword() { new BuilderILE("ab", "abcdefghi") { public void call() { b.setUnicodeLocaleKeyword("ab", arg); }}; } + @Test public void testBuilderPrivateUseExtension() { // normalizes hyphens to underscore, case to lower String source = "c-B-a"; @@ -1096,6 +1120,7 @@ public void testBuilderPrivateUseExtension() { new BuilderILE("a--b") { public void call() { b.setExtension(Locale.PRIVATE_USE_EXTENSION, arg); }}; } + @Test public void testBuilderClear() { String monster = "en-latn-US-NewYork-a-bb-cc-u-co-japanese-x-z-y-x-x"; Builder builder = new Builder(); @@ -1108,14 +1133,17 @@ public void testBuilderClear() { assertEquals("clear", "und", result); } + @Test public void testBuilderRemoveUnicodeAttribute() { // tested in testBuilderAddUnicodeAttribute } + @Test public void testBuilderBuild() { // tested in other test methods } + @Test public void testSerialize() { final Locale[] testLocales = { Locale.ROOT, @@ -1161,11 +1189,12 @@ public void testSerialize() { assertEquals("roundtrip " + locale, locale, o); } catch (Exception e) { - errln(locale + " encountered exception:" + e.getLocalizedMessage()); + fail(locale + " encountered exception:" + e.getLocalizedMessage()); } } } + @Test public void testDeserialize6() { final String TESTFILEPREFIX = "java6locale_"; @@ -1184,10 +1213,10 @@ public void testDeserialize6() { } if (dataDir == null) { - errln("'dataDir' is null. serialized.data.dir Property value is "+dataDirName); + fail("'dataDir' is null. serialized.data.dir Property value is "+dataDirName); return; } else if (!dataDir.isDirectory()) { - errln("'dataDir' is not a directory. dataDir: "+dataDir.toString()); + fail("'dataDir' is not a directory. dataDir: "+dataDir.toString()); return; } @@ -1219,11 +1248,12 @@ public void testDeserialize6() { Object o = ois.readObject(); assertEquals("Deserialize Java 6 Locale " + locale, o, locale); } catch (Exception e) { - errln("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage()); + fail("Exception while reading " + testfile.getAbsolutePath() + " - " + e.getMessage()); } } } + @Test public void testBug7002320() { // forLanguageTag() and Builder.setLanguageTag(String) // should add a location extension for following two cases. @@ -1267,6 +1297,7 @@ public void testBug7002320() { } } + @Test public void testBug7023613() { String[][] testdata = { {"en-Latn", "en__#Latn"}, @@ -1286,6 +1317,7 @@ public void testBug7023613() { /* * 7033504: (lc) incompatible behavior change for ja_JP_JP and th_TH_TH locales */ + @Test public void testBug7033504() { checkCalendar(new Locale("ja", "JP", "jp"), "java.util.GregorianCalendar"); checkCalendar(new Locale("ja", "jp", "jp"), "java.util.GregorianCalendar"); @@ -1318,13 +1350,13 @@ private void checkDigit(Locale loc, Character expected) { private void assertTrue(String msg, boolean v) { if (!v) { - errln(msg + ": expected true"); + fail(msg + ": expected true"); } } private void assertFalse(String msg, boolean v) { if (v) { - errln(msg + ": expected false"); + fail(msg + ": expected false"); } } @@ -1336,7 +1368,7 @@ private void assertEquals(String msg, Object e, Object v) { if (v != null) { v = "'" + v + "'"; } - errln(msg + ": expected " + e + " but got " + v); + fail(msg + ": expected " + e + " but got " + v); } } @@ -1345,19 +1377,19 @@ private void assertNotEquals(String msg, Object e, Object v) { if (e != null) { e = "'" + e + "'"; } - errln(msg + ": expected not equal " + e); + fail(msg + ": expected not equal " + e); } } private void assertNull(String msg, Object o) { if (o != null) { - errln(msg + ": expected null but got '" + o + "'"); + fail(msg + ": expected null but got '" + o + "'"); } } private void assertNotNull(String msg, Object o) { if (o == null) { - errln(msg + ": expected non null"); + fail(msg + ": expected non null"); } } @@ -1383,7 +1415,7 @@ public void run() { if (failMsg != null) { String msg = message(); msg = msg == null ? "" : msg + " "; - errln(msg + failMsg); + fail(msg + failMsg); } } diff --git a/test/jdk/java/util/Locale/Bug7069824.java b/test/jdk/java/util/Locale/LocaleMatchingTest.java similarity index 98% rename from test/jdk/java/util/Locale/Bug7069824.java rename to test/jdk/java/util/Locale/LocaleMatchingTest.java index 0eb1f21c275..ffe7092c751 100644 --- a/test/jdk/java/util/Locale/Bug7069824.java +++ b/test/jdk/java/util/Locale/LocaleMatchingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,19 @@ * @test * @bug 7069824 8042360 8032842 8175539 8210443 8242010 * @summary Verify implementation for Locale matching. - * @run testng/othervm Bug7069824 + * @run testng/othervm LocaleMatchingTest */ -import java.util.*; -import java.util.Locale.*; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Locale.FilteringMode; +import java.util.Locale.LanguageRange; +import java.util.Map; + import static java.util.Locale.FilteringMode.*; import static java.util.Locale.LanguageRange.*; import static org.testng.Assert.*; @@ -37,7 +45,7 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; -public class Bug7069824 { +public class LocaleMatchingTest { @DataProvider(name = "LRConstructorData") Object[][] LRConstructorData() { diff --git a/test/jdk/java/util/Locale/LocaleProvidersRun.java b/test/jdk/java/util/Locale/LocaleProvidersRun.java index beeb1444e93..947633a8e21 100644 --- a/test/jdk/java/util/Locale/LocaleProvidersRun.java +++ b/test/jdk/java/util/Locale/LocaleProvidersRun.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ * 8150432 8215913 8220227 8228465 8232871 8232860 8236495 8245241 * 8246721 8248695 8257964 8261919 * @summary tests for "java.locale.providers" system property + * @requires vm.flagless * @library /test/lib * @build LocaleProviders * providersrc.spi.src.tznp @@ -39,7 +40,6 @@ import java.util.Locale; -import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.Utils; @@ -178,22 +178,18 @@ public static void main(String[] args) throws Throwable { } private static void testRun(String prefList, String methodName, - String param1, String param2, String param3) throws Throwable{ - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASS_PATH) - .addToolArg("-Djava.util.logging.config.class=LocaleProviders$LogConfig") - .addToolArg("-Djava.locale.providers=" + prefList) - .addToolArg("--add-exports=java.base/sun.util.locale.provider=ALL-UNNAMED") - .addToolArg("LocaleProviders") - .addToolArg(methodName) - .addToolArg(param1) - .addToolArg(param2) - .addToolArg(param3); - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + String param1, String param2, String param3) throws Throwable { + + // Build process (without VM flags) + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + "-ea", "-esa", + "-cp", Utils.TEST_CLASS_PATH, + "-Djava.util.logging.config.class=LocaleProviders$LogConfig", + "-Djava.locale.providers=" + prefList, + "--add-exports=java.base/sun.util.locale.provider=ALL-UNNAMED", + "LocaleProviders", methodName, param1, param2, param3); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Unexpected exit code: " + exitCode); } diff --git a/test/jdk/java/util/Locale/Bug4152725.java b/test/jdk/java/util/Locale/LocaleShouldSetFromCLI.java similarity index 87% rename from test/jdk/java/util/Locale/Bug4152725.java rename to test/jdk/java/util/Locale/LocaleShouldSetFromCLI.java index 54392de239a..18432eecd07 100644 --- a/test/jdk/java/util/Locale/Bug4152725.java +++ b/test/jdk/java/util/Locale/LocaleShouldSetFromCLI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,24 +26,24 @@ * @summary Verify that the default locale can be specified from the * command line. * @run main/othervm -Duser.language=de -Duser.country=DE -Duser.variant=EURO - * Bug4152725 de_DE_EURO + * LocaleShouldSetFromCLI de_DE_EURO * @run main/othervm -Duser.language=ja -Duser.country= -Duser.variant= - * Bug4152725 ja + * LocaleShouldSetFromCLI ja * @run main/othervm -Duser.language=en -Duser.country=SG -Duser.variant= - * Bug4152725 en_SG + * LocaleShouldSetFromCLI en_SG * @run main/othervm -Duser.language= -Duser.country=DE -Duser.variant=EURO - * Bug4152725 _DE_EURO + * LocaleShouldSetFromCLI _DE_EURO * @run main/othervm -Duser.language=ja -Duser.country= -Duser.variant=YOMI - * Bug4152725 ja__YOMI + * LocaleShouldSetFromCLI ja__YOMI * @run main/othervm -Duser.language= -Duser.country= -Duser.variant=EURO - * Bug4152725 __EURO + * LocaleShouldSetFromCLI __EURO * @run main/othervm -Duser.language=de -Duser.region=DE_EURO - * Bug4152725 de_DE_EURO + * LocaleShouldSetFromCLI de_DE_EURO */ import java.util.Locale; -public class Bug4152725 { +public class LocaleShouldSetFromCLI { public static void main(String[] args) { diff --git a/test/jdk/java/util/Locale/LocaleTest.java b/test/jdk/java/util/Locale/LocaleTest.java index 7facfd393ca..f12d899fde2 100644 --- a/test/jdk/java/util/Locale/LocaleTest.java +++ b/test/jdk/java/util/Locale/LocaleTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,10 +27,9 @@ * 4147315 4147317 4147552 4335196 4778440 4940539 5010672 6475525 6544471 6627549 * 6786276 7066203 7085757 8008577 8030696 8170840 8255086 8263202 * @summary test Locales - * @library /java/text/testlib * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=COMPAT,SPI LocaleTest - * @run main/othervm -Djava.locale.providers=COMPAT,SPI -Djava.locale.useOldISOCodes=true LocaleTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI LocaleTest + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI -Djava.locale.useOldISOCodes=true LocaleTest */ /* * This file is available under and governed by the GNU General Public @@ -86,7 +85,11 @@ import java.util.Locale; import java.util.MissingResourceException; -public class LocaleTest extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class LocaleTest { public LocaleTest() { } @@ -191,52 +194,50 @@ public LocaleTest() { { "English (United States)", "French (France)", "Croatian (Croatia)", "Greek (Greece)", "Norwegian (Norway,Nynorsk)", "Italian", "xx (YY)" }, }; - public static void main(String[] args) throws Exception { - new LocaleTest().run(args); - } - + @Test public void TestBasicGetters() { for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { - errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " + fail(" Language code mismatch: " + testLocale.getLanguage() + " versus " + dataTable[LANG][i]); } if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { - errln(" Country code mismatch: " + testLocale.getCountry() + " versus " + fail(" Country code mismatch: " + testLocale.getCountry() + " versus " + dataTable[CTRY][i]); } if (!testLocale.getVariant().equals(dataTable[VAR][i])) { - errln(" Variant code mismatch: " + testLocale.getVariant() + " versus " + fail(" Variant code mismatch: " + testLocale.getVariant() + " versus " + dataTable[VAR][i]); } if (!testLocale.toString().equals(dataTable[NAME][i])) { - errln(" Locale name mismatch: " + testLocale.toString() + " versus " + fail(" Locale name mismatch: " + testLocale.toString() + " versus " + dataTable[NAME][i]); } } - logln("Same thing without variant codes..."); + System.out.println("Same thing without variant codes..."); for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { - errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " + fail(" Language code mismatch: " + testLocale.getLanguage() + " versus " + dataTable[LANG][i]); } if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { - errln(" Country code mismatch: " + testLocale.getCountry() + " versus " + fail(" Country code mismatch: " + testLocale.getCountry() + " versus " + dataTable[CTRY][i]); } if (!testLocale.getVariant().equals("")) { - errln(" Variant code mismatch: " + testLocale.getVariant() + " versus \"\""); + fail(" Variant code mismatch: " + testLocale.getVariant() + " versus \"\""); } } } + @Test public void TestSimpleResourceInfo() { for (int i = 0; i <= MAX_LOCALES; i++) { if (dataTable[LANG][i].equals("xx")) { @@ -244,20 +245,20 @@ public void TestSimpleResourceInfo() { } Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln("Testing " + testLocale + "..."); + System.out.println("Testing " + testLocale + "..."); if (!testLocale.getISO3Language().equals(dataTable[LANG3][i])) { - errln(" ISO-3 language code mismatch: " + testLocale.getISO3Language() + fail(" ISO-3 language code mismatch: " + testLocale.getISO3Language() + " versus " + dataTable[LANG3][i]); } if (!testLocale.getISO3Country().equals(dataTable[CTRY3][i])) { - errln(" ISO-3 country code mismatch: " + testLocale.getISO3Country() + fail(" ISO-3 country code mismatch: " + testLocale.getISO3Country() + " versus " + dataTable[CTRY3][i]); } /* // getLCID() is currently private if (!String.valueOf(testLocale.getLCID()).equals(dataTable[LCID][i])) - errln(" LCID mismatch: " + testLocale.getLCID() + " versus " + fail(" LCID mismatch: " + testLocale.getLCID() + " versus " + dataTable[LCID][i]); */ } @@ -269,6 +270,7 @@ public void TestSimpleResourceInfo() { * between 1.1.5 and 1.1.6, but I included a new test for it anyway) * @bug 4052440 Stop falling back to the default locale. */ + @Test public void TestDisplayNames() { Locale saveDefault = Locale.getDefault(); Locale english = new Locale("en", "US"); @@ -277,29 +279,29 @@ public void TestDisplayNames() { Locale greek = new Locale("el", "GR"); Locale.setDefault(english); - logln("With default = en_US..."); - logln(" In default locale..."); + System.out.println("With default = en_US..."); + System.out.println(" In default locale..."); doTestDisplayNames(null, DLANG_EN, false); - logln(" In locale = en_US..."); + System.out.println(" In locale = en_US..."); doTestDisplayNames(english, DLANG_EN, false); - logln(" In locale = fr_FR..."); + System.out.println(" In locale = fr_FR..."); doTestDisplayNames(french, DLANG_FR, false); - logln(" In locale = hr_HR..."); + System.out.println(" In locale = hr_HR..."); doTestDisplayNames(croatian, DLANG_HR, false); - logln(" In locale = el_GR..."); + System.out.println(" In locale = el_GR..."); doTestDisplayNames(greek, DLANG_EL, false); Locale.setDefault(french); - logln("With default = fr_FR..."); - logln(" In default locale..."); + System.out.println("With default = fr_FR..."); + System.out.println(" In default locale..."); doTestDisplayNames(null, DLANG_FR, true); - logln(" In locale = en_US..."); + System.out.println(" In locale = en_US..."); doTestDisplayNames(english, DLANG_EN, true); - logln(" In locale = fr_FR..."); + System.out.println(" In locale = fr_FR..."); doTestDisplayNames(french, DLANG_FR, true); - logln(" In locale = hr_HR..."); + System.out.println(" In locale = hr_HR..."); doTestDisplayNames(croatian, DLANG_HR, true); - logln(" In locale = el_GR..."); + System.out.println(" In locale = el_GR..."); doTestDisplayNames(greek, DLANG_EL, true); Locale.setDefault(saveDefault); @@ -309,14 +311,14 @@ private void doTestDisplayNames(Locale inLocale, int compareIndex, boolean defau String language = Locale.getDefault().getLanguage(); if (defaultIsFrench && !language.equals("fr")) { - errln("Default locale should be French, but it's really " + language); + fail("Default locale should be French, but it's really " + language); } else if (!defaultIsFrench && !language.equals("en")) { - errln("Default locale should be English, but it's really " + language); + fail("Default locale should be English, but it's really " + language); } for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); - logln(" Testing " + testLocale + "..."); + System.out.println(" Testing " + testLocale + "..."); String testLang; String testCtry; @@ -373,20 +375,21 @@ private void doTestDisplayNames(Locale inLocale, int compareIndex, boolean defau } if (!testLang.equals(expectedLang)) { - errln("Display language mismatch: " + testLang + " versus " + expectedLang); + fail("Display language mismatch: " + testLang + " versus " + expectedLang); } if (!testCtry.equals(expectedCtry)) { - errln("Display country mismatch: " + testCtry + " versus " + expectedCtry); + fail("Display country mismatch: " + testCtry + " versus " + expectedCtry); } if (!testVar.equals(expectedVar)) { - errln("Display variant mismatch: " + testVar + " versus " + expectedVar); + fail("Display variant mismatch: " + testVar + " versus " + expectedVar); } if (!testName.equals(expectedName)) { - errln("Display name mismatch: " + testName + " versus " + expectedName); + fail("Display name mismatch: " + testName + " versus " + expectedName); } } } + @Test public void TestSimpleObjectStuff() { Locale test1 = new Locale("aa", "AA"); Locale test2 = new Locale("aa", "AA"); @@ -394,19 +397,19 @@ public void TestSimpleObjectStuff() { Locale test4 = new Locale("zz", "ZZ"); if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3) { - errln("Some of the test variables point to the same locale!"); + fail("Some of the test variables point to the same locale!"); } if (test3 == null) { - errln("clone() failed to produce a valid object!"); + fail("clone() failed to produce a valid object!"); } if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3)) { - errln("clone() or equals() failed: objects that should compare equal don't"); + fail("clone() or equals() failed: objects that should compare equal don't"); } if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4)) { - errln("equals() failed: objects that shouldn't compare equal do"); + fail("equals() failed: objects that shouldn't compare equal do"); } int hash1 = test1.hashCode(); @@ -414,13 +417,14 @@ public void TestSimpleObjectStuff() { int hash3 = test3.hashCode(); if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3) { - errln("hashCode() failed: objects that should have the same hash code don't"); + fail("hashCode() failed: objects that should have the same hash code don't"); } } /** * @bug 4011756 4011380 */ + @Test public void TestISO3Fallback() { Locale test = new Locale("xx", "YY", ""); boolean gotException = false; @@ -432,7 +436,7 @@ public void TestISO3Fallback() { gotException = true; } if (!gotException) { - errln("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); + fail("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); } gotException = false; @@ -442,13 +446,14 @@ public void TestISO3Fallback() { gotException = true; } if (!gotException) { - errln("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); + fail("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); } } /** * @bug 4106155 4118587 7066203 7085757 */ + @Test public void TestGetLangsAndCountries() { // It didn't seem right to just do an exhaustive test of everything here, so I check // for the following things: @@ -463,7 +468,7 @@ public void TestGetLangsAndCountries() { "he", "id", "iu", "ug", "yi", "za"}; if (test.length != 188) { - errln("Expected getISOLanguages() to return 188 languages; it returned " + test.length); + fail("Expected getISOLanguages() to return 188 languages; it returned " + test.length); } else { for (int i = 0; i < spotCheck1.length; i++) { int j; @@ -473,19 +478,19 @@ public void TestGetLangsAndCountries() { } } if (j == test.length || !test[j].equals(spotCheck1[i])) { - errln("Couldn't find " + spotCheck1[i] + " in language list."); + fail("Couldn't find " + spotCheck1[i] + " in language list."); } } } for (int i = 0; i < test.length; i++) { if (!test[i].equals(test[i].toLowerCase())) { - errln(test[i] + " is not all lower case."); + fail(test[i] + " is not all lower case."); } if (test[i].length() != 2) { - errln(test[i] + " is not two characters long."); + fail(test[i] + " is not two characters long."); } if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { - errln(test[i] + " appears in an out-of-order position in the list."); + fail(test[i] + " appears in an out-of-order position in the list."); } } @@ -494,7 +499,7 @@ public void TestGetLangsAndCountries() { if (test.length != 249) { - errln("Expected getISOCountries to return 249 countries; it returned " + test.length); + fail("Expected getISOCountries to return 249 countries; it returned " + test.length); } else { for (int i = 0; i < spotCheck2.length; i++) { int j; @@ -504,19 +509,19 @@ public void TestGetLangsAndCountries() { } } if (j == test.length || !test[j].equals(spotCheck2[i])) { - errln("Couldn't find " + spotCheck2[i] + " in country list."); + fail("Couldn't find " + spotCheck2[i] + " in country list."); } } } for (int i = 0; i < test.length; i++) { if (!test[i].equals(test[i].toUpperCase())) { - errln(test[i] + " is not all upper case."); + fail(test[i] + " is not all upper case."); } if (test[i].length() != 2) { - errln(test[i] + " is not two characters long."); + fail(test[i] + " is not two characters long."); } if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { - errln(test[i] + " appears in an out-of-order position in the list."); + fail(test[i] + " appears in an out-of-order position in the list."); } } } @@ -531,28 +536,29 @@ void Test4126880() { test[0] = "SUCKER!!!"; test = Locale.getISOCountries(); if (test[0].equals("SUCKER!!!")) { - errln("Changed internal country code list!"); + fail("Changed internal country code list!"); } test = Locale.getISOLanguages(); test[0] = "HAHAHAHA!!!"; test = Locale.getISOLanguages(); if (test[0].equals("HAHAHAHA!!!")) { // Fixed typo - errln("Changes internal language code list!"); + fail("Changes internal language code list!"); } } /** * @bug 4107014 */ + @Test public void TestGetAvailableLocales() { Locale[] locales = Locale.getAvailableLocales(); if (locales == null || locales.length == 0) { - errln("Locale.getAvailableLocales() returned no installed locales!"); + fail("Locale.getAvailableLocales() returned no installed locales!"); } else { - logln("Locale.getAvailableLocales() returned a list of " + locales.length + " locales."); + System.out.println("Locale.getAvailableLocales() returned a list of " + locales.length + " locales."); for (int i = 0; i < locales.length; i++) { - logln(locales[i].toString()); + System.out.println(locales[i].toString()); } } } @@ -560,11 +566,12 @@ public void TestGetAvailableLocales() { /** * @bug 4135316 */ + @Test public void TestBug4135316() { Locale[] locales1 = Locale.getAvailableLocales(); Locale[] locales2 = Locale.getAvailableLocales(); if (locales1 == locales2) { - errln("Locale.getAvailableLocales() doesn't clone its internal storage!"); + fail("Locale.getAvailableLocales() doesn't clone its internal storage!"); } } @@ -573,27 +580,28 @@ public void TestBug4135316() { */ /* test commented out pending API-change approval + @Test public void TestGetLanguagesForCountry() { String[] languages = Locale.getLanguagesForCountry("US"); if (!searchStringArrayFor("en", languages)) - errln("Didn't get en as a language for US"); + fail("Didn't get en as a language for US"); languages = Locale.getLanguagesForCountry("FR"); if (!searchStringArrayFor("fr", languages)) - errln("Didn't get fr as a language for FR"); + fail("Didn't get fr as a language for FR"); languages = Locale.getLanguagesForCountry("CH"); if (!searchStringArrayFor("fr", languages)) - errln("Didn't get fr as a language for CH"); + fail("Didn't get fr as a language for CH"); if (!searchStringArrayFor("it", languages)) - errln("Didn't get it as a language for CH"); + fail("Didn't get it as a language for CH"); if (!searchStringArrayFor("de", languages)) - errln("Didn't get de as a language for CH"); + fail("Didn't get de as a language for CH"); languages = Locale.getLanguagesForCountry("JP"); if (!searchStringArrayFor("ja", languages)) - errln("Didn't get ja as a language for JP"); + fail("Didn't get ja as a language for JP"); } */ @@ -606,6 +614,7 @@ private boolean searchStringArrayFor(String s, String[] array) { /** * @bug 4110613 */ + @Test public void TestSerialization() throws ClassNotFoundException, OptionalDataException, IOException, StreamCorruptedException { ObjectOutputStream ostream; @@ -626,13 +635,14 @@ public void TestSerialization() throws ClassNotFoundException, OptionalDataExcep Locale test2 = (Locale) (istream.readObject()); if (!test1.equals(test2) || test1.hashCode() != test2.hashCode()) { - errln("Locale failed to deserialize correctly."); + fail("Locale failed to deserialize correctly."); } } /** * @bug 4118587 */ + @Test public void TestSimpleDisplayNames() { // This test is different from TestDisplayNames because TestDisplayNames checks // fallback behavior, combination of language and country names to form locale @@ -645,7 +655,7 @@ public void TestSimpleDisplayNames() { for (int i = 0; i < languageCodes.length; i++) { String test = (new Locale(languageCodes[i], "", "")).getDisplayLanguage(Locale.US); if (!test.equals(languageNames[i])) { - errln("Got wrong display name for " + languageCodes[i] + ": Expected \"" + fail("Got wrong display name for " + languageCodes[i] + ": Expected \"" + languageNames[i] + "\", got \"" + test + "\"."); } } @@ -654,6 +664,7 @@ public void TestSimpleDisplayNames() { /** * @bug 4118595 */ + @Test public void TestUninstalledISO3Names() { // This test checks to make sure getISO3Language and getISO3Country work right // even for locales that are not installed. @@ -663,7 +674,7 @@ public void TestUninstalledISO3Names() { for (int i = 0; i < iso2Languages.length; i++) { String test = (new Locale(iso2Languages[i], "", "")).getISO3Language(); if (!test.equals(iso3Languages[i])) { - errln("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + fail("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + iso3Languages[i] + "\", got \"" + test + "\"."); } } @@ -674,7 +685,7 @@ public void TestUninstalledISO3Names() { for (int i = 0; i < iso2Countries.length; i++) { String test = (new Locale("", iso2Countries[i], "")).getISO3Country(); if (!test.equals(iso3Countries[i])) { - errln("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + fail("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + iso3Countries[i] + "\", got \"" + test + "\"."); } } @@ -683,6 +694,7 @@ public void TestUninstalledISO3Names() { /** * @bug 4052404 4778440 8263202 */ + @Test public void TestChangedISO639Codes() { Locale hebrewOld = new Locale("iw", "IL", ""); Locale hebrewNew = new Locale("he", "IL", ""); @@ -693,28 +705,28 @@ public void TestChangedISO639Codes() { if ("true".equalsIgnoreCase(System.getProperty("java.locale.useOldISOCodes"))) { if (!hebrewNew.getLanguage().equals("iw")) { - errln("Got back wrong language code for new Hebrew: expected \"iw\", got \"" + fail("Got back wrong language code for new Hebrew: expected \"iw\", got \"" + hebrewNew.getLanguage() + "\""); } if (!yiddishNew.getLanguage().equals("ji")) { - errln("Got back wrong language code for new Yiddish: expected \"ji\", got \"" + fail("Got back wrong language code for new Yiddish: expected \"ji\", got \"" + yiddishNew.getLanguage() + "\""); } if (!indonesianNew.getLanguage().equals("in")) { - errln("Got back wrong language code for new Indonesian: expected \"in\", got \"" + fail("Got back wrong language code for new Indonesian: expected \"in\", got \"" + indonesianNew.getLanguage() + "\""); } } else { if (!hebrewOld.getLanguage().equals("he")) { - errln("Got back wrong language code for old Hebrew: expected \"he\", got \"" + fail("Got back wrong language code for old Hebrew: expected \"he\", got \"" + hebrewNew.getLanguage() + "\""); } if (!yiddishOld.getLanguage().equals("yi")) { - errln("Got back wrong language code for old Yiddish: expected \"yi\", got \"" + fail("Got back wrong language code for old Yiddish: expected \"yi\", got \"" + yiddishNew.getLanguage() + "\""); } if (!indonesianOld.getLanguage().equals("id")) { - errln("Got back wrong language code for old Indonesian: expected \"id\", got \"" + fail("Got back wrong language code for old Indonesian: expected \"id\", got \"" + indonesianNew.getLanguage() + "\""); } } @@ -738,6 +750,7 @@ public void TestChangedISO639Codes() { * 1999-11-19 joconner * */ + @Test public void TestAtypicalLocales() { Locale[] localesToTest = { new Locale("de", "CA"), new Locale("ja", "ZA"), @@ -783,27 +796,27 @@ public void TestAtypicalLocales() { for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.US); - logln(name); + System.out.println(name); if (!name.equals(englishDisplayNames[i])) { - errln("Lookup in English failed: expected \"" + englishDisplayNames[i] + fail("Lookup in English failed: expected \"" + englishDisplayNames[i] + "\", got \"" + name + "\""); } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(new Locale("es", "ES")); - logln(name); + System.out.println(name); if (!name.equals(spanishDisplayNames[i])) { - errln("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i] + fail("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i] + "\", got \"" + name + "\""); } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.FRANCE); - logln(name); + System.out.println(name); if (!name.equals(frenchDisplayNames[i])) { - errln("Lookup in French failed: expected \"" + frenchDisplayNames[i] + fail("Lookup in French failed: expected \"" + frenchDisplayNames[i] + "\", got \"" + name + "\""); } } @@ -815,6 +828,7 @@ public void TestAtypicalLocales() { /** * @bug 4126371 */ + @Test public void TestNullDefault() { // why on earth anyone would ever try to do this is beyond me, but we should // definitely make sure we don't let them @@ -826,10 +840,10 @@ public void TestNullDefault() { gotException = true; } if (Locale.getDefault() == null) { - errln("Locale.getDefault() allowed us to set default to NULL!"); + fail("Locale.getDefault() allowed us to set default to NULL!"); } if (!gotException) { - errln("Trying to set default locale to NULL didn't throw exception!"); + fail("Trying to set default locale to NULL didn't throw exception!"); } } @@ -838,15 +852,16 @@ public void TestNullDefault() { * This would be better tested by the LocaleDataTest. Will move it when I * get the LocaleDataTest working again. */ + @Test public void TestThaiCurrencyFormat() { DecimalFormat thaiCurrency = (DecimalFormat) NumberFormat.getCurrencyInstance( new Locale("th", "TH")); if (!thaiCurrency.getPositivePrefix().equals("\u0e3f")) { - errln("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + fail("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + thaiCurrency.getPositivePrefix() + "\""); } if (!thaiCurrency.getPositiveSuffix().equals("")) { - errln("Thai currency suffix wrong: expected \"\", got \"" + fail("Thai currency suffix wrong: expected \"\", got \"" + thaiCurrency.getPositiveSuffix() + "\""); } } @@ -864,6 +879,7 @@ public void TestThaiCurrencyFormat() { * DON'T ASSUME: Any specific countries support the Euro. Instead, * iterate through all locales. */ + @Test public void TestEuroSupport() { final String EURO_VARIANT = "EURO"; final String EURO_CURRENCY = "\u20AC"; // Look for this string in formatted Euro currency @@ -877,10 +893,10 @@ public void TestEuroSupport() { String neg = nf.format(-271828.182845); if (pos.indexOf(EURO_CURRENCY) >= 0 && neg.indexOf(EURO_CURRENCY) >= 0) { - logln("Ok: " + loc.toString() + System.out.println("Ok: " + loc.toString() + ": " + pos + " / " + neg); } else { - errln("Fail: " + loc.toString() + fail("Fail: " + loc.toString() + " formats without " + EURO_CURRENCY + ": " + pos + " / " + neg + "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***"); @@ -893,6 +909,7 @@ public void TestEuroSupport() { * @bug 4139504 * toString() doesn't work with language_VARIANT. */ + @Test public void TestToString() { Object[] DATA = { new Locale("xx", "", ""), "xx", @@ -907,7 +924,7 @@ public void TestToString() { Locale loc = (Locale) DATA[i]; String fmt = (String) DATA[i + 1]; if (!loc.toString().equals(fmt)) { - errln("Fail: Locale.toString(" + fmt + ")=>" + loc); + fail("Fail: Locale.toString(" + fmt + ")=>" + loc); } } } @@ -917,6 +934,7 @@ public void TestToString() { * Currency symbol in zh is wrong. We will test this at the NumberFormat * end to test the whole pipe. */ + @Test public void Test4105828() { Locale[] LOC = {Locale.CHINESE, new Locale("zh", "CN", ""), new Locale("zh", "TW", ""), new Locale("zh", "HK", "")}; @@ -924,7 +942,7 @@ public void Test4105828() { NumberFormat fmt = NumberFormat.getPercentInstance(LOC[i]); String result = fmt.format(1); if (!result.equals("100%")) { - errln("Percent for " + LOC[i] + " should be 100%, got " + result); + fail("Percent for " + LOC[i] + " should be 100%, got " + result); } } } @@ -945,6 +963,7 @@ public void Test4105828() { * is that something is wrong with the font mapping subsystem, but we can't * test that here. */ + @Test public void Test4139940() { Locale mylocale = new Locale("hu", "", ""); @SuppressWarnings("deprecation") @@ -954,7 +973,7 @@ public void Test4139940() { // Make sure that o circumflex (\u00F4) is NOT there, and // o double acute (\u0151) IS. if (str.indexOf('\u0151') < 0 || str.indexOf('\u00F4') >= 0) { - errln("Fail: Monday in Hungarian is wrong"); + fail("Fail: Monday in Hungarian is wrong"); } } @@ -962,10 +981,11 @@ public void Test4139940() { * @bug 4143951 * Russian first day of week should be Monday. Confirmed. */ + @Test public void Test4143951() { Calendar cal = Calendar.getInstance(new Locale("ru", "", "")); if (cal.getFirstDayOfWeek() != Calendar.MONDAY) { - errln("Fail: First day of week in Russia should be Monday"); + fail("Fail: First day of week in Russia should be Monday"); } } @@ -974,6 +994,7 @@ public void Test4143951() { * java.util.Locale.getISO3Country() works wrong for non ISO-3166 codes. * Should throw an exception for unknown locales */ + @Test public void Test4147315() { // Try with codes that are the wrong length but happen to match text // at a valid offset in the mapping table @@ -982,7 +1003,7 @@ public void Test4147315() { try { String result = locale.getISO3Country(); - errln("ERROR: getISO3Country() returns: " + result + fail("ERROR: getISO3Country() returns: " + result + " for locale '" + locale + "' rather than exception"); } catch (MissingResourceException e) { } @@ -994,6 +1015,7 @@ public void Test4147315() { * Should throw an exception for unknown locales, except they have three * letter language codes. */ + @Test public void Test4147317() { // Try a three letter language code, and check whether it is // returned as is. @@ -1001,7 +1023,7 @@ public void Test4147317() { String result = locale.getISO3Language(); if (!result.equals("aaa")) { - errln("ERROR: getISO3Language() returns: " + result + fail("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than returning it as is"); } @@ -1012,7 +1034,7 @@ public void Test4147317() { try { result = locale.getISO3Language(); - errln("ERROR: getISO3Language() returns: " + result + fail("ERROR: getISO3Language() returns: " + result + " for locale '" + locale + "' rather than exception"); } catch (MissingResourceException e) { } @@ -1021,6 +1043,7 @@ public void Test4147317() { /* * @bug 4147552 4778440 8030696 */ + @Test public void Test4147552() { Locale[] locales = {new Locale("no", "NO"), new Locale("no", "NO", "B"), new Locale("no", "NO", "NY"), new Locale("nb", "NO"), @@ -1037,11 +1060,11 @@ public void Test4147552() { for (int i = 0; i < locales.length; i++) { Locale loc = locales[i]; if (!loc.getDisplayName(Locale.US).equals(englishDisplayNames[i])) { - errln("English display-name mismatch: expected " + fail("English display-name mismatch: expected " + englishDisplayNames[i] + ", got " + loc.getDisplayName()); } if (!loc.getDisplayName(loc).equals(norwegianDisplayNames[i])) { - errln("Norwegian display-name mismatch: expected " + fail("Norwegian display-name mismatch: expected " + norwegianDisplayNames[i] + ", got " + loc.getDisplayName(loc)); } @@ -1051,11 +1074,12 @@ public void Test4147552() { /* * @bug 8030696 */ + @Test public void Test8030696() { List av = Arrays.asList(Locale.getAvailableLocales()); if (!av.contains(new Locale("nb", "NO")) || !av.contains(new Locale("nn", "NO"))) { - errln("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); + fail("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); } } diff --git a/test/jdk/java/util/Locale/Bug8135061.java b/test/jdk/java/util/Locale/LookupOnValidRangeTest.java similarity index 68% rename from test/jdk/java/util/Locale/Bug8135061.java rename to test/jdk/java/util/Locale/LookupOnValidRangeTest.java index 3bb1fe4877c..b6feb94c322 100644 --- a/test/jdk/java/util/Locale/Bug8135061.java +++ b/test/jdk/java/util/Locale/LookupOnValidRangeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ * @bug 8135061 * @summary Checks that the Locale.lookup executes properly without throwing * any exception for some specific language ranges - * @run main Bug8135061 + * @run junit LookupOnValidRangeTest */ import java.util.Collection; @@ -35,47 +35,46 @@ import java.util.Locale; import java.util.Locale.LanguageRange; -public class Bug8135061 { +import org.junit.jupiter.api.Test; - public static void main(String[] args) { +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; - /* lookup should run without throwing any exception and - * return null as the language range does not match with the language - * tag - */ +public class LookupOnValidRangeTest { + + /** + * Lookup should run without throwing any exception and return null as + * the language range does not match with the language tag. + */ + @Test + public void lookupReturnNullTest() { List ranges = LanguageRange.parse("nv"); Collection locales = Collections.singleton(Locale.ENGLISH); - try { Locale match = Locale.lookup(ranges, locales); - if (match != null) { - throw new RuntimeException("Locale.lookup returned non-null: " - + match); - } + assertNull(match); } catch (Exception ex) { throw new RuntimeException("[Locale.lookup failed on language" + " range: " + ranges + " and language tags " + locales + "]", ex); } + } - /* lookup should run without throwing any exception and - * return "nv" as the matching tag - */ - ranges = LanguageRange.parse("i-navajo"); - locales = Collections.singleton(new Locale("nv")); - + /** + * Lookup should run without throwing any exception and return "nv" + * as the matching tag. + */ + @Test + public void lookupReturnValueTest() { + List ranges = LanguageRange.parse("i-navajo"); + Collection locales = Collections.singleton(new Locale("nv")); try { Locale match = Locale.lookup(ranges, locales); - if (!match.toLanguageTag().equals("nv")) { - throw new RuntimeException("Locale.lookup returned unexpected" - + " result: " + match); - } + assertEquals(match.toLanguageTag(), "nv"); } catch (Exception ex) { throw new RuntimeException("[Locale.lookup failed on language" + " range: " + ranges + " and language tags " + locales + "]", ex); } - } - } diff --git a/test/jdk/java/util/Locale/MatchEmptyWeightCorrectly.java b/test/jdk/java/util/Locale/MatchEmptyWeightCorrectly.java new file mode 100644 index 00000000000..f69873b566c --- /dev/null +++ b/test/jdk/java/util/Locale/MatchEmptyWeightCorrectly.java @@ -0,0 +1,144 @@ +/* + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 8035133 + * @summary Checks that the tags matching the range with quality weight q=0 + * e.g. en;q=0 must be elimited and must not be the part of output + * @run junit MatchEmptyWeightCorrectly + */ + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.Locale; +import java.util.stream.Stream; + +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class MatchEmptyWeightCorrectly { + + // Ensure weights with 'q=0' work as expected during lookup + @ParameterizedTest + @MethodSource("lookupProvider") + public void lookupTest(String ranges, String tags, + String expectedLocale) { + + List priorityList = Locale.LanguageRange + .parse(ranges); + List localeList = generateLocales(tags); + Locale loc = Locale.lookup(priorityList, localeList); + String actualLocale = loc.toLanguageTag(); + assertEquals(expectedLocale, actualLocale); + } + + private static Stream lookupProvider() { + return Stream.of( + // checking Locale.lookup with de-ch;q=0 + Arguments.of("en;q=0.1, *-ch;q=0.5, de-ch;q=0", + "de-ch, en, fr-ch", "fr-CH"), + // checking Locale.lookup with *;q=0 '*' should be ignored in lookup + Arguments.of("en;q=0.1, *-ch;q=0.5, *;q=0", + "de-ch, en, fr-ch", "de-CH") + ); + } + + // Ensure weights with 'q=0' work as expected during filtering + @ParameterizedTest + @MethodSource("filterProvider") + public void filterTest(String ranges, String tags, + String expectedLocales) { + + List priorityList = Locale.LanguageRange + .parse(ranges); + List localeList = generateLocales(tags); + String actualLocales = getLocalesAsString( + Locale.filter(priorityList, localeList)); + assertEquals(expectedLocales, actualLocales); + } + + private static Stream filterProvider() { + return Stream.of( + // checking Locale.filter with fr-ch;q=0 in BASIC_FILTERING + Arguments.of("en;q=0.1, fr-ch;q=0.0, de-ch;q=0.5", + "de-ch, en, fr-ch", "de-CH, en"), + // checking Locale.filter with *;q=0 in BASIC_FILTERING + Arguments.of("de-ch;q=0.6, *;q=0", "de-ch, fr-ch", ""), + // checking Locale.filter with *;q=0 in BASIC_FILTERING + Arguments.of("de-ch;q=0.6, de;q=0", "de-ch", ""), + // checking Locale.filter with *;q=0.6, en;q=0 in BASIC_FILTERING + Arguments.of("*;q=0.6, en;q=0", "de-ch, hi-in, en", "de-CH, hi-IN"), + // checking Locale.filter with de-ch;q=0 in EXTENDED_FILTERING + Arguments.of("en;q=0.1, *-ch;q=0.5, de-ch;q=0", + "de-ch, en, fr-ch", "fr-CH, en"), + /* checking Locale.filter with *-ch;q=0 in EXTENDED_FILTERING which + * must make filter to return "" empty or no match + */ + Arguments.of("de-ch;q=0.5, *-ch;q=0", "de-ch, fr-ch", ""), + /* checking Locale.filter with *;q=0 in EXTENDED_FILTERING which + * must make filter to return "" empty or no match + */ + Arguments.of("*-ch;q=0.5, *;q=0", "de-ch, fr-ch", ""), + /* checking Locale.filter with *;q=0.6, *-Latn;q=0 in + * EXTENDED_FILTERING + */ + Arguments.of("*;q=0.6, *-Latn;q=0", "de-ch, hi-in, en-Latn", + "de-CH, hi-IN") + ); + } + + private static List generateLocales(String tags) { + if (tags == null) { + return null; + } + + List localeList = new ArrayList<>(); + if (tags.equals("")) { + return localeList; + } + String[] t = tags.split(", "); + for (String tag : t) { + localeList.add(Locale.forLanguageTag(tag)); + } + return localeList; + } + + private static String getLocalesAsString(List locales) { + StringBuilder sb = new StringBuilder(); + + Iterator itr = locales.iterator(); + if (itr.hasNext()) { + sb.append(itr.next().toLanguageTag()); + } + while (itr.hasNext()) { + sb.append(", "); + sb.append(itr.next().toLanguageTag()); + } + + return sb.toString().trim(); + } +} diff --git a/test/jdk/java/util/Locale/Bug6989440.java b/test/jdk/java/util/Locale/ProviderPoolMultiThreadAccess.java similarity index 77% rename from test/jdk/java/util/Locale/Bug6989440.java rename to test/jdk/java/util/Locale/ProviderPoolMultiThreadAccess.java index 42b77d58c29..7acca68b1df 100644 --- a/test/jdk/java/util/Locale/Bug6989440.java +++ b/test/jdk/java/util/Locale/ProviderPoolMultiThreadAccess.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,8 +27,8 @@ * @summary Verify ConcurrentModificationException is not thrown with multiple * thread accesses. * @modules java.base/sun.util.locale.provider - * @compile -XDignore.symbol.file=true Bug6989440.java - * @run main Bug6989440 + * @compile -XDignore.symbol.file=true ProviderPoolMultiThreadAccess.java + * @run junit ProviderPoolMultiThreadAccess */ import java.text.spi.DateFormatProvider; import java.util.spi.LocaleNameProvider; @@ -37,11 +37,17 @@ import sun.util.locale.provider.LocaleServiceProviderPool; -public class Bug6989440 { +import org.junit.jupiter.api.Test; + +public class ProviderPoolMultiThreadAccess { static volatile boolean failed; // false static final int THREADS = 50; - public static void main(String[] args) throws Exception { + /* Multiple instances of Locale Service Provider Pool calling + * getAvailableLocales() should not throw ConcurrentModificationException + */ + @Test + public void multiThreadAccessTest() throws Exception { Thread[] threads = new Thread[THREADS]; for (int i=0; i cls; private static int count; - public TestThread(Class providerClass) { - cls = providerClass; - } - public TestThread() { int which = count++ % 3; switch (which) { - case 0 : cls = LocaleNameProvider.class; break; - case 1 : cls = TimeZoneNameProvider.class; break; - case 2 : cls = DateFormatProvider.class; break; - default : throw new AssertionError("Should not reach here"); + case 0 -> cls = LocaleNameProvider.class; + case 1 -> cls = TimeZoneNameProvider.class; + case 2 -> cls = DateFormatProvider.class; + default -> throw new AssertionError("Should not reach here"); } } diff --git a/test/jdk/java/util/Locale/bug6277243.java b/test/jdk/java/util/Locale/RootLocale.java similarity index 71% rename from test/jdk/java/util/Locale/bug6277243.java rename to test/jdk/java/util/Locale/RootLocale.java index 8dec902b7b4..66d5465f8d9 100644 --- a/test/jdk/java/util/Locale/bug6277243.java +++ b/test/jdk/java/util/Locale/RootLocale.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,20 +20,29 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test * @bug 6277243 * @summary Verify that there is Locale.ROOT constant, and it is equal to Locale("", "", "") + * @run junit RootLocale */ import java.util.Locale; -public class bug6277243 { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class RootLocale { - public static void main(String[] args) throws Exception { + /** + * Locale.ROOT should exist and match an empty Locale given as + * Locale("", "", ""). + */ + @Test + public void rootTest() { Locale root = new Locale("", "", ""); - if (!Locale.ROOT.equals(root)) { - throw new RuntimeException("Locale.ROOT is not equal to Locale(\"\", \"\", \"\")"); - } + assertEquals(Locale.ROOT, root, "Locale.ROOT is not equal to Locale(\"\", \"\", \"\")"); } } diff --git a/test/jdk/java/util/Locale/Bug8166994.java b/test/jdk/java/util/Locale/SubsequentRangeParsingTest.java similarity index 59% rename from test/jdk/java/util/Locale/Bug8166994.java rename to test/jdk/java/util/Locale/SubsequentRangeParsingTest.java index 7dea676107a..b160b3a692e 100644 --- a/test/jdk/java/util/Locale/Bug8166994.java +++ b/test/jdk/java/util/Locale/SubsequentRangeParsingTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,48 +20,47 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + /* * @test - * @bug 8166884 + * @bug 8166994 * @summary Checks the subsequent call to parse the same language ranges * which must generate the same list of language ranges * i.e. the priority list containing equivalents, as in the * first call + * @run junit SubsequentRangeParsingTest */ import java.util.Arrays; import java.util.List; import java.util.Locale; import java.util.stream.Collectors; +import java.util.stream.Stream; -public class Bug8166994 { +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; - public static void main(String[] args) { - List list = Arrays.asList("ccq-aa", "ybd-aa", "rki-aa"); - String ranges = "ccq-aa"; - testParseConsistency(list, ranges); +import static org.junit.jupiter.api.Assertions.assertEquals; - // consecutive call to check the language range parse consistency - testParseConsistency(list, ranges); +public class SubsequentRangeParsingTest { - // another case with ranges consisting of multiple equivalents and - // single equivalents - list = Arrays.asList("gfx-xz", "oun-xz", "mwj-xz", "vaj-xz", - "taj-xy", "tsf-xy"); - ranges = "gfx-xz, taj-xy"; - testParseConsistency(list, ranges); + /* + * Checks that consecutive calls to parse the same language ranges + * generate the same list of language ranges. + */ + @ParameterizedTest + @MethodSource("ranges") + public void parseConsistencyTest(List list, String ranges) { // consecutive call to check the language range parse consistency testParseConsistency(list, ranges); - + testParseConsistency(list, ranges); } + // Ensure that parsing the ranges returns the expected list. private static void testParseConsistency(List list, String ranges) { List priorityList = parseRanges(ranges); - if (!list.equals(priorityList)) { - throw new RuntimeException("Failed to parse the language range [" - + ranges + "], Expected: " + list + " Found: " - + priorityList); - } + assertEquals(list, priorityList, "Failed to parse the language range:"); } private static List parseRanges(String s) { @@ -70,5 +69,13 @@ private static List parseRanges(String s) { .collect(Collectors.toList()); } + // Ranges that have multiple equivalents and single equivalents. + private static Stream ranges() { + return Stream.of( + Arguments.of(Arrays.asList("ccq-aa", "ybd-aa", "rki-aa"), + "ccq-aa"), + Arguments.of(Arrays.asList("gfx-xz", "oun-xz", "mwj-xz", + "vaj-xz", "taj-xy", "tsf-xy"), "gfx-xz, taj-xy") + ); + } } - diff --git a/test/jdk/java/util/Locale/ThaiGov.java b/test/jdk/java/util/Locale/ThaiGov.java index 25bf026e5ea..0efe11f87d9 100644 --- a/test/jdk/java/util/Locale/ThaiGov.java +++ b/test/jdk/java/util/Locale/ThaiGov.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,98 +20,70 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -/** + +/* * @test * @bug 4474409 + * @summary Tests some localized methods with Thai locale * @author John O'Conner * @modules jdk.localedata - * @run main/othervm -Djava.locale.providers=COMPAT ThaiGov + * @run junit/othervm -Djava.locale.providers=COMPAT ThaiGov */ -import java.util.*; -import java.text.*; - -public class ThaiGov { +import java.text.DateFormat; +import java.text.NumberFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.Locale; +import java.util.TimeZone; - ThaiGov() { - System.out.println("ThaiGov locale test..."); +import org.junit.jupiter.api.Test; - } - - void numberTest() throws RuntimeException { - final String strExpected = "\u0E51\u0E52\u002C\u0E53\u0E54\u0E55\u002C\u0E56\u0E57\u0E58\u002E\u0E52\u0E53\u0E54"; - final double value = 12345678.234; +import static org.junit.jupiter.api.Assertions.assertEquals; - Locale locTH = new Locale("th", "TH", "TH"); - - // th_TH_TH test - NumberFormat nf = NumberFormat.getInstance(locTH); - String str = nf.format(value); +public class ThaiGov { - if (!strExpected.equals(str)) { - throw new RuntimeException(); - } + private static final double VALUE = 12345678.234; + private static final Locale TH = new Locale("th", "TH", "TH"); + // Test number formatting for thai + @Test + public void numberTest() { + final String strExpected = "\u0E51\u0E52\u002C\u0E53\u0E54\u0E55\u002C\u0E56\u0E57\u0E58\u002E\u0E52\u0E53\u0E54"; + NumberFormat nf = NumberFormat.getInstance(TH); + String str = nf.format(VALUE); + assertEquals(strExpected, str); } - void currencyTest() throws RuntimeException { + // Test currency formatting for Thai + @Test + public void currencyTest() { final String strExpected = "\u0E3F\u0E51\u0E52\u002C\u0E53\u0E54\u0E55\u002C\u0E56\u0E57\u0E58\u002E\u0E52\u0E53"; - final double value = 12345678.234; - - Locale locTH = new Locale("th", "TH", "TH"); - - // th_TH_TH test - NumberFormat nf = NumberFormat.getCurrencyInstance(locTH); - String str = nf.format(value); - - if (!strExpected.equals(str)) { - throw new RuntimeException(); - } - + NumberFormat nf = NumberFormat.getCurrencyInstance(TH); + String str = nf.format(VALUE); + assertEquals(strExpected, str); } - void dateTest() throws RuntimeException { - Locale locTH = new Locale("th", "TH", "TH"); - TimeZone tz = TimeZone.getTimeZone("PST"); - + // Test date formatting for Thai + @Test + public void dateTest() { + TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles"); Calendar calGregorian = Calendar.getInstance(tz, Locale.US); calGregorian.clear(); calGregorian.set(2002, 4, 1, 8, 30); final Date date = calGregorian.getTime(); - Calendar cal = Calendar.getInstance(tz, locTH); + Calendar cal = Calendar.getInstance(tz, TH); cal.clear(); cal.setTime(date); final String strExpected = "\u0E27\u0E31\u0E19\u0E1E\u0E38\u0E18\u0E17\u0E35\u0E48\u0020\u0E51\u0020\u0E1E\u0E24\u0E29\u0E20\u0E32\u0E04\u0E21\u0020\u0E1E\u002E\u0E28\u002E\u0020\u0E52\u0E55\u0E54\u0E55\u002C\u0020\u0E58\u0020\u0E19\u0E32\u0E2C\u0E34\u0E01\u0E32\u0020\u0E53\u0E50\u0020\u0E19\u0E32\u0E17\u0E35\u0020\u0E50\u0E50\u0020\u0E27\u0E34\u0E19\u0E32\u0E17\u0E35"; - Date value = cal.getTime(); + Date value = cal.getTime(); // th_TH_TH test - DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, locTH); + DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, TH); df.setTimeZone(tz); String str = df.format(value); - - if (!strExpected.equals(str)) { - throw new RuntimeException(); - } - + assertEquals(strExpected, str); } - - public static void main(String[] args) { - - ThaiGov app = new ThaiGov(); - System.out.print("Running numberTest..."); - app.numberTest(); - System.out.print("Finished\n"); - System.out.print("Running currencyTest..."); - app.currencyTest(); - System.out.print("Finished\n"); - System.out.print("Running dateTest..."); - app.dateTest(); - System.out.print("Finished\n"); - - System.out.println("PASSED"); - } - - } diff --git a/test/jdk/java/util/Locale/Bug8159420.java b/test/jdk/java/util/Locale/TurkishLangRangeTest.java similarity index 56% rename from test/jdk/java/util/Locale/Bug8159420.java rename to test/jdk/java/util/Locale/TurkishLangRangeTest.java index f09e0f2cbb4..44366bbc0d0 100644 --- a/test/jdk/java/util/Locale/Bug8159420.java +++ b/test/jdk/java/util/Locale/TurkishLangRangeTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,120 +31,91 @@ * e.g. "HI-Deva".toLowerCase() in the Turkish locale returns * "hı-deva", where 'ı' is the LATIN SMALL LETTER DOTLESS I character * which is not allowed in the language ranges/tags. - * @compile -encoding utf-8 Bug8159420.java - * @run main Bug8159420 + * @compile -encoding utf-8 TurkishLangRangeTest.java + * @run junit/othervm -Duser.language=tr -Duser.country=TR TurkishLangRangeTest */ +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Locale.LanguageRange; import java.util.Locale.FilteringMode; import java.util.LinkedHashMap; -import java.util.HashMap; -import java.util.Iterator; -import java.util.ArrayList; +import java.util.stream.Stream; + import static java.util.Locale.FilteringMode.EXTENDED_FILTERING; import static java.util.Locale.FilteringMode.AUTOSELECT_FILTERING; -public class Bug8159420 { - - static boolean err = false; - - public static void main(String[] args) { +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; - Locale origLocale = null; - try { +import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNotNull; +import static org.junit.jupiter.api.Assertions.assertThrows; - origLocale = Locale.getDefault(); - Locale.setDefault(new Locale("tr", "TR")); - testParse(); - testFilter(EXTENDED_FILTERING); - testFilter(AUTOSELECT_FILTERING); - testLookup(); - testMapEquivalents(); +public class TurkishLangRangeTest { - if (err) { - throw new RuntimeException("[LocaleMatcher method(s) in turkish" - + " locale failed]"); - } - - } finally { - Locale.setDefault(origLocale); - } - - } - - /* Before the fix, the testParse() method was throwing - * IllegalArgumentException in Turkish Locale + /* + * Ensure parse() does not throw IllegalArgumentException for the Turkish Locale + * with the given input. */ - private static void testParse() { + @Test + public void parseTest() { String ranges = "HI-Deva, ja-hIrA-JP, RKI"; - try { - LanguageRange.parse(ranges); - } catch (Exception ex) { - System.err.println("[testParse() failed on range string: " - + ranges + "] due to "+ex); - err = true; - } + assertDoesNotThrow(() -> LanguageRange.parse(ranges)); } - /* Before the fix, the testFilter() method was returning empty list in - * Turkish Locale + /* + * Ensure filter() does not return empty list for the Turkish Locale + * with the given input. */ - private static void testFilter(FilteringMode mode) { - + @ParameterizedTest + @MethodSource("modes") + public void filterTest(FilteringMode mode) { String ranges = "hi-IN, itc-Ital"; String tags = "hi-IN, itc-Ital"; List priorityList = LanguageRange.parse(ranges); List tagList = generateLocales(tags); String actualLocales = showLocales(Locale.filter(priorityList, tagList, mode)); String expectedLocales = "hi-IN, itc-Ital"; + assertEquals(expectedLocales, actualLocales); + } - if (!expectedLocales.equals(actualLocales)) { - System.err.println("testFilter(" + mode + ") failed on language ranges:" - + " [" + ranges + "] and language tags: [" + tags + "]"); - err = true; - } + private static Stream modes() { + return Stream.of( + EXTENDED_FILTERING, + AUTOSELECT_FILTERING + ); } - /* Before the fix, the testLookup() method was returning null in Turkish - * Locale + /* + * Ensure lookup() does not return null for the Turkish Locale with + * the given input. */ - private static void testLookup() { - boolean error = false; + @Test + public void lookupTest() { String ranges = "hi-IN, itc-Ital"; String tags = "hi-IN, itc-Ital"; List priorityList = LanguageRange.parse(ranges); List localeList = generateLocales(tags); - Locale actualLocale - = Locale.lookup(priorityList, localeList); - String actualLocaleString = ""; - - if (actualLocale != null) { - actualLocaleString = actualLocale.toLanguageTag(); - } else { - error = true; - } - + Locale actualLocale = Locale.lookup(priorityList, localeList); + assertNotNull(actualLocale); + String actualLocaleString = actualLocale.toLanguageTag(); String expectedLocale = "hi-IN"; - - if (!expectedLocale.equals(actualLocaleString)) { - error = true; - } - - if (error) { - System.err.println("testLookup() failed on language ranges:" - + " [" + ranges + "] and language tags: [" + tags + "]"); - err = true; - } - + assertEquals(expectedLocale, actualLocaleString); } - /* Before the fix, testMapEquivalents() method was returning only "hi-in" - * in Turkish Locale + /* + * Ensure mapEquivalents() does not only return "hi-in" for the Turkish + * Locale with the given input. */ - private static void testMapEquivalents() { - + @Test + public void mapEquivalentsTest() { String ranges = "HI-IN"; List priorityList = LanguageRange.parse(ranges); HashMap> map = new LinkedHashMap<>(); @@ -156,38 +127,29 @@ private static void testMapEquivalents() { List expected = new ArrayList<>(); expected.add(new LanguageRange("hi-in")); expected.add(new LanguageRange("hi-deva-in")); - List got - = LanguageRange.mapEquivalents(priorityList, map); - - if (!areEqual(expected, got)) { - System.err.println("testMapEquivalents() failed"); - err = true; - } - + List got = + LanguageRange.mapEquivalents(priorityList, map); + assertEquals(expected, got, getDifferences(expected, got)); } - private static boolean areEqual(List expected, + private static String getDifferences(List expected, List got) { - - boolean error = false; - if (expected.equals(got)) { - return !error; - } - + StringBuilder diffs = new StringBuilder(); List cloneExpected = new ArrayList<>(expected); cloneExpected.removeAll(got); if (!cloneExpected.isEmpty()) { - error = true; - System.err.println("Found missing range(s): " + cloneExpected); + diffs.append("Found missing range(s): ") + .append(cloneExpected) + .append(System.lineSeparator()); } - - // not creating the 'got' clone as the list will not be used after this - got.removeAll(expected); + List cloneGot = new ArrayList<>(got); + cloneGot.removeAll(expected); if (!got.isEmpty()) { - error = true; - System.err.println("Found extra range(s): " + got); + diffs.append("Got extra range(s): ") + .append(cloneGot) + .append(System.lineSeparator()); } - return !error; + return diffs.toString(); } private static List generateLocales(String tags) { @@ -220,5 +182,4 @@ private static String showLocales(List locales) { return sb.toString().trim(); } - } diff --git a/test/jdk/java/util/Locale/UseOldISOCodesTest.java b/test/jdk/java/util/Locale/UseOldISOCodesTest.java new file mode 100644 index 00000000000..38008e9f662 --- /dev/null +++ b/test/jdk/java/util/Locale/UseOldISOCodesTest.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 2022, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8295232 + * @summary Ensures java.locale.useOldISOCodes is statically initialized + * @library /test/lib + * @run junit UseOldISOCodesTest + */ + +import java.util.Locale; +import jdk.test.lib.process.ProcessTools; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +public class UseOldISOCodesTest { + + // Ensure java.locale.useOldISOCodes is only interpreted at runtime startup + @Test + public void staticInitializationTest() throws Exception { + ProcessTools.executeTestJvm("-Djava.locale.useOldISOCodes=true", "UseOldISOCodesTest$Runner") + .outputTo(System.out) + .errorTo(System.err) + .shouldHaveExitValue(0); + } + + static class Runner { + private static final String obsoleteCode = "iw"; + private static final String newCode = "he"; + + public static void main(String[] args) { + // Should have no effect + System.setProperty("java.locale.useOldISOCodes", "false"); + Locale locale = new Locale(newCode); + assertEquals(obsoleteCode, locale.getLanguage(), + "newCode 'he' was not mapped to 'iw' with useOldISOCodes=true"); + } + } +} diff --git a/test/jdk/java/util/Locale/bug4122700.java b/test/jdk/java/util/Locale/bug4122700.java deleted file mode 100644 index 1406caba06e..00000000000 --- a/test/jdk/java/util/Locale/bug4122700.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 4122700 - * @summary Verify that list of available locales is non-empty, and print the list - */ - -import java.util.Locale; - -public class bug4122700 { - public static void main(String[] args) throws Exception { - Locale[] systemLocales = Locale.getAvailableLocales(); - if (systemLocales.length == 0) - throw new Exception("Available locale list is empty!"); - System.out.println("Found " + systemLocales.length + " locales:"); - Locale[] locales = new Locale[systemLocales.length]; - for (int i = 0; i < locales.length; i++) { - Locale lowest = null; - for (int j = 0; j < systemLocales.length; j++) { - if (i > 0 && locales[i - 1].toString().compareTo(systemLocales[j].toString()) >= 0) - continue; - if (lowest == null || systemLocales[j].toString().compareTo(lowest.toString()) < 0) - lowest = systemLocales[j]; - } - locales[i] = lowest; - } - for (int i = 0; i < locales.length; i++) { - if (locales[i].getCountry().length() == 0) - System.out.println(" " + locales[i].getDisplayLanguage() + ":"); - else { - if (locales[i].getVariant().length() == 0) - System.out.println(" " + locales[i].getDisplayCountry()); - else - System.out.println(" " + locales[i].getDisplayCountry() + ", " - + locales[i].getDisplayVariant()); - } - } - } -} diff --git a/test/jdk/java/util/Locale/bug4123285.html b/test/jdk/java/util/Locale/bug4123285.html deleted file mode 100644 index 7cb7a3d07d8..00000000000 --- a/test/jdk/java/util/Locale/bug4123285.html +++ /dev/null @@ -1 +0,0 @@ - diff --git a/test/jdk/java/util/Locale/bug4123285.java b/test/jdk/java/util/Locale/bug4123285.java deleted file mode 100644 index 23cbb8ad5bd..00000000000 --- a/test/jdk/java/util/Locale/bug4123285.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -import java.util.Locale; - -public class bug4123285 extends java.applet.Applet { - public void start() { - System.out.println("Hello, world!"); - Locale[] systemLocales = null; - try { - System.out.println("Default locale = " + Locale.getDefault()); - systemLocales = Locale.getAvailableLocales(); - System.out.println("Found " + systemLocales.length + " locales:"); - Locale[] locales = new Locale[systemLocales.length]; - for (int i = 0; i < locales.length; i++) { - Locale lowest = null; - for (int j = 0; j < systemLocales.length; j++) { - if (i > 0 && locales[i - 1].toString().compareTo(systemLocales[j].toString()) >= 0) - continue; - if (lowest == null || systemLocales[j].toString().compareTo(lowest.toString()) < 0) - lowest = systemLocales[j]; - } - locales[i] = lowest; - } - for (int i = 0; i < locales.length; i++) { - if (locales[i].getCountry().length() == 0) - System.out.println(" " + locales[i].getDisplayLanguage() + ":"); - else { - if (locales[i].getVariant().length() == 0) - System.out.println(" " + locales[i].getDisplayCountry()); - else - System.out.println(" " + locales[i].getDisplayCountry() + ", " - + locales[i].getDisplayVariant()); - } - } - } - catch (Exception e) { - e.printStackTrace(); - } - } -} diff --git a/test/jdk/java/util/Locale/bug6312358.java b/test/jdk/java/util/Locale/bug6312358.java deleted file mode 100644 index ff2ad347f60..00000000000 --- a/test/jdk/java/util/Locale/bug6312358.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -/* - * @test - * @bug 6312358 - * @summary Verify that an NPE is thrown by issueing Locale.getInstance() with - * any argument being null. - * @modules java.base/java.util:open - */ - -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.Locale; - -public class bug6312358 { - - - public static void main(String[] args) throws Exception { - - try { - // Locale.getInstance is not directly accessible. - Method getInstanceMethod = Locale.class.getDeclaredMethod( - "getInstance", String.class, String.class, String.class - ); - getInstanceMethod.setAccessible(true); - - getInstanceMethod.invoke(null, "null", "GB", ""); - try { - getInstanceMethod.invoke(null, null, "GB", ""); - throw new RuntimeException("Should NPE with language set to null"); - } catch (InvocationTargetException exc) { - Throwable cause = exc.getCause(); - if (!(cause instanceof NullPointerException)) { - throw new RuntimeException(cause+" is thrown with language set to null"); - } - } - - getInstanceMethod.invoke(null, "en", "null", ""); - try { - getInstanceMethod.invoke(null, "en", null, ""); - throw new RuntimeException("Should NPE with country set to null"); - } catch (InvocationTargetException exc) { - Throwable cause = exc.getCause(); - if (!(cause instanceof NullPointerException)) { - throw new RuntimeException(cause+" is thrown with country set to null"); - } - } - - getInstanceMethod.invoke(null, "en", "GB", "null"); - try { - getInstanceMethod.invoke(null, "en", "GB", null); - throw new RuntimeException("Should NPE with variant set to null"); - } catch (InvocationTargetException exc) { - Throwable cause = exc.getCause(); - if (!(cause instanceof NullPointerException)) { - throw new RuntimeException(cause+" is thrown with variant set to null"); - } - } - } catch (java.lang.NoSuchMethodException exc) { - // method is not found. consider it as a success - } - } -} diff --git a/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java b/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java index 6fd79ebf88a..66a60f11ad4 100644 --- a/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java +++ b/test/jdk/java/util/ResourceBundle/Control/MissingResourceCauseTestRun.java @@ -90,15 +90,13 @@ private static void runCmd() throws Throwable { // UnreadableRB.properties is in current directory String cp = Utils.TEST_CLASSES + File.pathSeparator + Utils.TEST_SRC + File.pathSeparator + "."; - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(cp) - .addToolArg("MissingResourceCauseTest"); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-ea", "-esa", + "-cp", cp, + "MissingResourceCauseTest"); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test failed. " + "Unexpected exit code: " + exitCode); diff --git a/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java b/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java index 1d8bdbb89db..24c6e181ccc 100644 --- a/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java +++ b/test/jdk/java/util/ResourceBundle/modules/ModuleTestUtil.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -29,6 +29,7 @@ import java.util.stream.Stream; import jdk.test.lib.JDKToolLauncher; +import jdk.test.lib.Utils; import jdk.test.lib.compiler.CompilerUtils; import jdk.test.lib.process.ProcessTools; @@ -133,17 +134,15 @@ public static void copyResFiles(Path src, Path dest, String mn, */ public static void runModule(String mp, String mn, List localeList) throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-p") - .addToolArg(mp) - .addToolArg("-m") - .addToolArg(mn); - localeList.forEach(launcher::addToolArg); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + List args = List.of( + "-ea", "-esa", + "-p", mp, + "-m", mn); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(args.stream(), localeList.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test failed. " + "Unexpected exit code: " + exitCode); @@ -161,19 +160,17 @@ public static void runModule(String mp, String mn, List localeList) */ public static void runModuleWithCp(String cp, String mp, String mn, List localeList, boolean expected) throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(cp) - .addToolArg("-p") - .addToolArg(mp) - .addToolArg("-m") - .addToolArg(mn); - localeList.forEach(launcher::addToolArg); + List args = List.of( + "-ea", "-esa", + "-cp", cp, + "-p", mp, + "-m", mn); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(args.stream(), localeList.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); if (expected) { if (exitCode != 0) { throw new RuntimeException("Execution of the test loads bundles " @@ -198,18 +195,17 @@ public static void runModuleWithCp(String cp, String mp, String mn, */ public static void runModuleWithLegacyCode(String mp, String mn, List localeList) throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-Djava.locale.useOldISOCodes=true") - .addToolArg("-p") - .addToolArg(mp) - .addToolArg("-m") - .addToolArg(mn); - localeList.forEach(launcher::addToolArg); + List args = List.of( + "-ea", "-esa", + "-Djava.locale.useOldISOCodes=true", + "-p", mp, + "-m", mn); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(args.stream(), localeList.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test failed. " + "Unexpected exit code: " + exitCode); diff --git a/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java b/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java index b1c79c0367f..85e8e531a31 100644 --- a/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java +++ b/test/jdk/java/util/ResourceBundle/modules/layer/LayerTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -71,16 +71,13 @@ private static void compileCmd() throws Throwable { } private static void runCmd() throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASSES) - .addToolArg("Main") - .addToolArg(Utils.TEST_CLASSES); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-ea", "-esa", + "-cp", Utils.TEST_CLASSES, + "Main", Utils.TEST_CLASSES); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test failed. " + "Unexpected exit code: " + exitCode); diff --git a/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java b/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java index 4540d5a378b..e9567fcdaad 100644 --- a/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java +++ b/test/jdk/java/util/ResourceBundle/modules/unnamed/UnNamedTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -39,6 +39,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.stream.Stream; import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.Utils; @@ -73,42 +74,34 @@ private static void compileCmd() throws Throwable { private static void runCmd() throws Throwable { // access resource bundles that are exported private unconditionally. - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASSES) - .addToolArg("--module-path") - .addToolArg(MODS_DIR.toString()) - .addToolArg("--add-modules") - .addToolArg("bundles") - .addToolArg("Main"); - LOCALE_LIST.forEach(launcher::addToolArg); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + List args = List.of( + "-ea", "-esa", + "-cp", Utils.TEST_CLASSES, + "--module-path", MODS_DIR.toString(), + "--add-modules", "bundles", + "Main"); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(args.stream(), LOCALE_LIST.stream()).toList()); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test1 failed. " + "Unexpected exit code: " + exitCode); } // --add-exports can't open resources - launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(Utils.TEST_CLASSES) - .addToolArg("--module-path") - .addToolArg(MODS_DIR.toString()) - .addToolArg("--add-modules") - .addToolArg("bundles") - .addToolArg("--add-opens") - .addToolArg("bundles/jdk.test.internal.resources=ALL-UNNAMED") - .addToolArg("Main"); - LOCALE_LIST.forEach(launcher::addToolArg); + List argsWithOpens = List.of( + "-ea", "-esa", + "-cp", Utils.TEST_CLASSES, + "--module-path", MODS_DIR.toString(), + "--add-modules", "bundles", + "--add-opens", "bundles/jdk.test.internal.resources=ALL-UNNAMED", + "Main"); + pb = ProcessTools.createTestJavaProcessBuilder( + Stream.concat(argsWithOpens.stream(), LOCALE_LIST.stream()).toList()); - exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + // Evaluate process status + exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Execution of the test2 failed. " + "Unexpected exit code: " + exitCode); diff --git a/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java b/test/jdk/java/util/ResourceBundle/modules/visibility/VisibilityTest.java index 7f940586337..e0fdb9a93ab 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, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,7 @@ * @bug 8137317 8139238 8210408 * @summary Visibility tests for ResourceBundle.getBundle with and without * an unnamed module argument. + * @requires vm.flagless * @library /test/lib * .. * @build jdk.test.lib.JDKToolLauncher @@ -39,10 +40,12 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; +import java.util.stream.Stream; import jdk.test.lib.JDKToolLauncher; import jdk.test.lib.Utils; import jdk.test.lib.process.ProcessTools; + import org.testng.annotations.BeforeTest; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; @@ -328,11 +331,10 @@ public void RunWithPkgRes(List argsList) throws Throwable { } private int runCmd(List argsList) throws Throwable { - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-ea") - .addToolArg("-esa"); - argsList.forEach(launcher::addToolArg); - - return ProcessTools.executeCommand(launcher.getCommand()).getExitValue(); + // Build process (without VM flags) + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( + Stream.concat(Stream.of("-ea", "-esa"), argsList.stream()).toList()); + // Evaluate process status + return ProcessTools.executeCommand(pb).getExitValue(); } -} \ No newline at end of file +} diff --git a/test/jdk/java/util/TimeZone/Bug4322313.java b/test/jdk/java/util/TimeZone/Bug4322313.java index a65a87149b9..e9060bc1e54 100644 --- a/test/jdk/java/util/TimeZone/Bug4322313.java +++ b/test/jdk/java/util/TimeZone/Bug4322313.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,14 +27,17 @@ * @summary Make sure that new implementation of custom time zone * support for TimeZone.getTimeZone() works correctly and the * getDisplayName() methods are locale independent. - * @library /java/text/testlib + * @run junit Bug4322313 */ -import java.io.*; -import java.text.*; -import java.util.*; +import java.util.Locale; +import java.util.TimeZone; -public class Bug4322313 extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug4322313 { private static final int MPM = 60 * 1000; /* Milliseconds per minute */ private static final Object[][] VALIDS = { /* given ID rawOffset normalized ID */ @@ -80,6 +83,7 @@ public class Bug4322313 extends IntlTest { "GMT+09:00 ", }; + @Test void Test4322313() { Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -106,7 +110,7 @@ void Test4322313() { "\"] Invalid TimeZone ID, expected:" + VALIDS[k][2] + ", got:" + tz.getID() + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] Valid TimeZone ID, got:" + VALIDS[k][2]); } @@ -119,7 +123,7 @@ void Test4322313() { "\"] Invalid RawOffset, expected:" + VALIDS[k][1] + ", got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] Vaild RawOffset, got:" + offset); } @@ -132,7 +136,7 @@ void Test4322313() { "\"] DSTSavings should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + VALIDS[k][0] + "\"] DSTSavings is zero."); } @@ -150,7 +154,7 @@ void Test4322313() { "\"] Invalid TimeZone ID, expected:GMT, got:" + tz.getID() + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] Valid TimeZone ID, got:" + tz.getID()); } @@ -163,7 +167,7 @@ void Test4322313() { "\"] RawOffset should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] RawOffset is zero."); } @@ -176,7 +180,7 @@ void Test4322313() { "\"] DSTSavings should be zero, got:" + offset + ", " + tz); } else { - logln("\tPassed [Locale=" + + System.out.println("\tPassed [Locale=" + locale + ", \"" + INVALIDS[k] + "\"] DSTSavings is zero."); } @@ -218,13 +222,9 @@ void Test4322313() { TimeZone.setDefault(savedTimeZone); } if (err) { - errln("TimeZone.getTimeZone() test failed"); + fail("TimeZone.getTimeZone() test failed"); } else { - logln("TimeZone.getTimeZone() test passed"); + System.out.println("TimeZone.getTimeZone() test passed"); } } - - public static void main (String[] args) throws Exception { - new Bug4322313().run(args); - } } diff --git a/test/jdk/java/util/TimeZone/Bug6329116.java b/test/jdk/java/util/TimeZone/Bug6329116.java index 32105881194..6e85fe8cb5b 100644 --- a/test/jdk/java/util/TimeZone/Bug6329116.java +++ b/test/jdk/java/util/TimeZone/Bug6329116.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,27 +27,24 @@ * 7039469 7090843 7103108 7103405 7158483 8008577 8059206 8064560 8072042 * 8077685 8151876 8166875 8169191 8170316 8176044 * @summary Make sure that timezone short display names are idenical to Olson's data. - * @library /java/text/testlib - * @build Bug6329116 TextFileReader - * @run main/othervm -Djava.locale.providers=COMPAT,SPI Bug6329116 + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI Bug6329116 */ import java.io.*; import java.text.*; import java.util.*; -public class Bug6329116 extends IntlTest { +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class Bug6329116 { static Locale[] locales = Locale.getAvailableLocales(); static String[] timezones = TimeZone.getAvailableIDs(); - public static void main(String[] args) throws IOException { - if (bug6329116()) { - throw new RuntimeException("At least one timezone display name is incorrect."); - } - } - - static boolean bug6329116() throws IOException { + @Test + public void bug6329116() throws IOException { boolean err = false; HashMap aliasTable = new HashMap<>(); @@ -200,7 +197,9 @@ static boolean bug6329116() throws IOException { } } - return err; + if (err) { + fail("At least one timezone display name is incorrect."); + } } static boolean useLocalzedShortDisplayName(TimeZone tz, diff --git a/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java b/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java index ece90a9d7cd..5fd48efadcc 100644 --- a/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java +++ b/test/jdk/java/util/TimeZone/CustomTzIDCheckDST.java @@ -29,16 +29,18 @@ * @requires os.family != "windows" * @run main/othervm CustomTzIDCheckDST */ + import java.util.Calendar; import java.util.Date; -import java.util.List; import java.util.SimpleTimeZone; import java.util.TimeZone; import java.time.DayOfWeek; import java.time.ZonedDateTime; import java.time.temporal.TemporalAdjusters; + import jdk.test.lib.process.ProcessTools; import jdk.test.lib.process.OutputAnalyzer; + public class CustomTzIDCheckDST { // Northern Hemisphere private static String CUSTOM_TZ = "MEZ-1MESZ,M3.5.0,M10.5.0/3"; @@ -46,7 +48,7 @@ public class CustomTzIDCheckDST { private static String CUSTOM_TZ2 = "MEZ-1MESZ,M10.5.0,M3.5.0/3"; public static void main(String args[]) throws Throwable { if (args.length == 0) { - ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(List.of("CustomTzIDCheckDST", "runTZTest")); + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder("CustomTzIDCheckDST", "runTZTest"); pb.environment().put("TZ", CUSTOM_TZ); OutputAnalyzer output = ProcessTools.executeProcess(pb); output.shouldHaveExitValue(0); diff --git a/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java b/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java index a1d44ea080d..c70ccc204de 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java +++ b/test/jdk/java/util/TimeZone/TimeZoneBoundaryTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,18 +23,26 @@ /* * @test - * @library /java/text/testlib * @summary test Time Zone Boundary + * @run junit TimeZoneBoundaryTest */ -import java.text.*; -import java.util.*; +import java.text.DateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.SimpleTimeZone; +import java.util.TimeZone; + +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; /** * A test which discovers the boundaries of DST programmatically and verifies * that they are correct. */ -public class TimeZoneBoundaryTest extends IntlTest +public class TimeZoneBoundaryTest { static final int ONE_SECOND = 1000; static final int ONE_MINUTE = 60*ONE_SECOND; @@ -57,10 +65,6 @@ public class TimeZoneBoundaryTest extends IntlTest static final long AUSTRALIA_1997_BEG = 877797000000L; static final long AUSTRALIA_1997_END = 859653000000L; - public static void main(String[] args) throws Exception { - new TimeZoneBoundaryTest().run(args); - } - /** * Date.toString().substring() Boundary Test * Look for a DST changeover to occur within 6 months of the given Date. @@ -75,7 +79,7 @@ void findDaylightBoundaryUsingDate(Date d, String startMode, long expectedBounda if (d.toString().indexOf(startMode) == -1) { - logln("Error: " + startMode + " not present in " + d); + System.out.println("Error: " + startMode + " not present in " + d); } // Use a binary search, assuming that we have a Standard @@ -98,15 +102,15 @@ void findDaylightBoundaryUsingDate(Date d, String startMode, long expectedBounda } } - logln("Date Before: " + showDate(min)); - logln("Date After: " + showDate(max)); + System.out.println("Date Before: " + showDate(min)); + System.out.println("Date After: " + showDate(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST, long expectedBoundary) @@ -128,14 +132,14 @@ void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST, if (tz.inDaylightTime(d) != startsInDST) { - errln("FAIL: " + tz.getID() + " inDaylightTime(" + + fail("FAIL: " + tz.getID() + " inDaylightTime(" + d + ") != " + startsInDST); startsInDST = !startsInDST; // Flip over; find the apparent value } if (tz.inDaylightTime(new Date(max)) == startsInDST) { - errln("FAIL: " + tz.getID() + " inDaylightTime(" + + fail("FAIL: " + tz.getID() + " inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); return; } @@ -154,16 +158,16 @@ void findDaylightBoundaryUsingTimeZone(Date d, boolean startsInDST, } } - logln(tz.getID() + " Before: " + showDate(min, tz)); - logln(tz.getID() + " After: " + showDate(max, tz)); + System.out.println(tz.getID() + " Before: " + showDate(min, tz)); + System.out.println(tz.getID() + " After: " + showDate(max, tz)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } private static String showDate(long l) @@ -209,23 +213,23 @@ void verifyDST(Date d, TimeZone time_zone, boolean expUseDaylightTime, boolean expInDaylightTime, int expZoneOffset, int expDSTOffset) { - logln("-- Verifying time " + d + + System.out.println("-- Verifying time " + d + " in zone " + time_zone.getID()); if (time_zone.inDaylightTime(d) == expInDaylightTime) - logln("PASS: inDaylightTime = " + time_zone.inDaylightTime(d)); + System.out.println("PASS: inDaylightTime = " + time_zone.inDaylightTime(d)); else - errln("FAIL: inDaylightTime = " + time_zone.inDaylightTime(d)); + fail("FAIL: inDaylightTime = " + time_zone.inDaylightTime(d)); if (time_zone.useDaylightTime() == expUseDaylightTime) - logln("PASS: useDaylightTime = " + time_zone.useDaylightTime()); + System.out.println("PASS: useDaylightTime = " + time_zone.useDaylightTime()); else - errln("FAIL: useDaylightTime = " + time_zone.useDaylightTime()); + fail("FAIL: useDaylightTime = " + time_zone.useDaylightTime()); if (time_zone.getRawOffset() == expZoneOffset) - logln("PASS: getRawOffset() = " + expZoneOffset/(double)ONE_HOUR); + System.out.println("PASS: getRawOffset() = " + expZoneOffset/(double)ONE_HOUR); else - errln("FAIL: getRawOffset() = " + time_zone.getRawOffset()/(double)ONE_HOUR + + fail("FAIL: getRawOffset() = " + time_zone.getRawOffset()/(double)ONE_HOUR + "; expected " + expZoneOffset/(double)ONE_HOUR); GregorianCalendar gc = new GregorianCalendar(time_zone); @@ -237,13 +241,14 @@ void verifyDST(Date d, TimeZone time_zone, gc.get(gc.SECOND)) * 1000 + gc.get(gc.MILLISECOND)); if (offset == expDSTOffset) - logln("PASS: getOffset() = " + offset/(double)ONE_HOUR); + System.out.println("PASS: getOffset() = " + offset/(double)ONE_HOUR); else - errln("FAIL: getOffset() = " + offset/(double)ONE_HOUR + + fail("FAIL: getOffset() = " + offset/(double)ONE_HOUR + "; expected " + expDSTOffset/(double)ONE_HOUR); } @SuppressWarnings("deprecation") + @Test public void TestBoundaries() { TimeZone pst = TimeZone.getTimeZone("PST"); @@ -263,19 +268,19 @@ public void TestBoundaries() inDST ? -7*ONE_HOUR : -8*ONE_HOUR); } - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingDate(new Date(97,0,1), "PST", PST_1997_BEG); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingDate(new Date(97,6,1), "PDT", PST_1997_END); // Southern hemisphere test - logln("========================================"); + System.out.println("========================================"); TimeZone z = TimeZone.getTimeZone(AUSTRALIA); findDaylightBoundaryUsingTimeZone(new Date(97,0,1), true, AUSTRALIA_1997_END, z); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingTimeZone(new Date(97,0,1), false, PST_1997_BEG); - logln("========================================"); + System.out.println("========================================"); findDaylightBoundaryUsingTimeZone(new Date(97,6,1), true, PST_1997_END); } finally { TimeZone.setDefault(save); @@ -297,7 +302,7 @@ void testUsingBinarySearch(SimpleTimeZone tz, Date d, long expectedBoundary) if (tz.inDaylightTime(new Date(max)) == startsInDST) { - logln("Error: inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); + System.out.println("Error: inDaylightTime(" + (new Date(max)) + ") != " + (!startsInDST)); } while ((max - min) > INTERVAL) @@ -313,121 +318,50 @@ void testUsingBinarySearch(SimpleTimeZone tz, Date d, long expectedBoundary) } } - logln("Binary Search Before: " + showDate(min)); - logln("Binary Search After: " + showDate(max)); + System.out.println("Binary Search Before: " + showDate(min)); + System.out.println("Binary Search After: " + showDate(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected boundary at " + expectedBoundary); + System.out.println("PASS: Expected boundary at " + expectedBoundary); else - errln("FAIL: Expected boundary at " + expectedBoundary); + fail("FAIL: Expected boundary at " + expectedBoundary); } - /* - static void testUsingMillis(Date d, boolean startsInDST) - { - long millis = d.getTime(); - long max = millis + (long)(370 * ONE_DAY); // A year plus extra - - boolean lastDST = startsInDST; - while (millis < max) - { - cal.setTime(new Date(millis)); - boolean inDaylight = cal.inDaylightTime(); - - if (inDaylight != lastDST) - { - logln("Switch " + (inDaylight ? "into" : "out of") - + " DST at " + (new Date(millis))); - lastDST = inDaylight; - } - - millis += 15*ONE_MINUTE; - } - } - */ - /** * Test new rule formats. */ @SuppressWarnings("deprecation") - public void TestNewRules() - { - //logln(Locale.getDefault().getDisplayName()); - //logln(TimeZone.getDefault().getID()); - //logln(new Date(0)); - - if (true) - { - // Doesn't matter what the default TimeZone is here, since we - // are creating our own TimeZone objects. - - SimpleTimeZone tz; - - logln("-----------------------------------------------------------------"); - logln("Aug 2ndTues .. Mar 15"); - tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_1", - Calendar.AUGUST, 2, Calendar.TUESDAY, 2*ONE_HOUR, - Calendar.MARCH, 15, 0, 2*ONE_HOUR); - //logln(tz.toString()); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,0,1), 858416400000L); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,6,1), 871380000000L); - - logln("-----------------------------------------------------------------"); - logln("Apr Wed>=14 .. Sep Sun<=20"); - tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_2", - Calendar.APRIL, 14, -Calendar.WEDNESDAY, 2*ONE_HOUR, - Calendar.SEPTEMBER, -20, -Calendar.SUNDAY, 2*ONE_HOUR); - //logln(tz.toString()); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,0,1), 861184800000L); - logln("========================================"); - testUsingBinarySearch(tz, new Date(97,6,1), 874227600000L); - } - - /* - if (true) - { - logln("========================================"); - logln("Stepping using millis"); - testUsingMillis(new Date(97,0,1), false); - } - - if (true) - { - logln("========================================"); - logln("Stepping using fields"); - testUsingFields(1997, false); - } - - if (false) - { - cal.clear(); - cal.set(1997, 3, 5, 10, 0); - // cal.inDaylightTime(); - logln("Date = " + cal.getTime()); - logln("Millis = " + cal.getTime().getTime()/3600000); - } - */ + @Test + public void TestNewRules() { + // Doesn't matter what the default TimeZone is here, since we + // are creating our own TimeZone objects. + + SimpleTimeZone tz; + + System.out.println("-----------------------------------------------------------------"); + System.out.println("Aug 2ndTues .. Mar 15"); + tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_1", + Calendar.AUGUST, 2, Calendar.TUESDAY, 2*ONE_HOUR, + Calendar.MARCH, 15, 0, 2*ONE_HOUR); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,0,1), 858416400000L); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,6,1), 871380000000L); + + System.out.println("-----------------------------------------------------------------"); + System.out.println("Apr Wed>=14 .. Sep Sun<=20"); + tz = new SimpleTimeZone(-8*ONE_HOUR, "Test_2", + Calendar.APRIL, 14, -Calendar.WEDNESDAY, 2*ONE_HOUR, + Calendar.SEPTEMBER, -20, -Calendar.SUNDAY, 2*ONE_HOUR); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,0,1), 861184800000L); + System.out.println("========================================"); + testUsingBinarySearch(tz, new Date(97,6,1), 874227600000L); } - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - // Long Bug - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - //---------------------------------------------------------------------- - - //public void Test3() - //{ - // findDaylightBoundaryUsingTimeZone(new Date(97,6,1), true); - //} - /** * Find boundaries by stepping. */ @@ -439,15 +373,15 @@ void findBoundariesStepwise(int year, long interval, TimeZone z, int expectedCha long limit = time + ONE_YEAR + ONE_DAY; boolean lastState = z.inDaylightTime(d); int changes = 0; - logln("-- Zone " + z.getID() + " starts in " + year + " with DST = " + lastState); - logln("useDaylightTime = " + z.useDaylightTime()); + System.out.println("-- Zone " + z.getID() + " starts in " + year + " with DST = " + lastState); + System.out.println("useDaylightTime = " + z.useDaylightTime()); while (time < limit) { d.setTime(time); boolean state = z.inDaylightTime(d); if (state != lastState) { - logln((state ? "Entry " : "Exit ") + + System.out.println((state ? "Entry " : "Exit ") + "at " + d); lastState = state; ++changes; @@ -456,23 +390,24 @@ void findBoundariesStepwise(int year, long interval, TimeZone z, int expectedCha } if (changes == 0) { - if (!lastState && !z.useDaylightTime()) logln("No DST"); - else errln("FAIL: Timezone<" + z.getID() + "> DST all year, or no DST with true useDaylightTime"); + if (!lastState && !z.useDaylightTime()) System.out.println("No DST"); + else fail("FAIL: Timezone<" + z.getID() + "> DST all year, or no DST with true useDaylightTime"); } else if (changes != 2) { - errln("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; should see 0 or 2"); + fail("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; should see 0 or 2"); } else if (!z.useDaylightTime()) { - errln("FAIL: Timezone<" + z.getID() + "> useDaylightTime false but 2 changes seen"); + fail("FAIL: Timezone<" + z.getID() + "> useDaylightTime false but 2 changes seen"); } if (changes != expectedChanges) { - errln("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; expected " + expectedChanges); + fail("FAIL: Timezone<" + z.getID() + "> " + changes + " changes seen; expected " + expectedChanges); } } + @Test public void TestStepwise() { findBoundariesStepwise(1997, ONE_DAY, TimeZone.getTimeZone("ACT"), 0); diff --git a/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java b/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java index c510c39cd16..f5d80cd6069 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java +++ b/test/jdk/java/util/TimeZone/TimeZoneDatePermissionCheckRun.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -66,17 +66,15 @@ public static void main(String[] args) throws Throwable { //run it with the security manager on, plus accesscontroller debugging //will go into infinite recursion trying to get enough permissions for //printing Date of failing certificate unless fix is applied. - JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("java"); - launcher.addToolArg("-Djava.security.manager") - .addToolArg("-Djava.security.debug=access,failure,policy") - .addToolArg("-ea") - .addToolArg("-esa") - .addToolArg("-cp") - .addToolArg(jarPath) - .addToolArg("TimeZoneDatePermissionCheck"); - - int exitCode = ProcessTools.executeCommand(launcher.getCommand()) - .getExitValue(); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + "-Djava.security.manager", + "-Djava.security.debug=access,failure,policy", + "-ea", "-esa", + "-cp", jarPath, + "TimeZoneDatePermissionCheck"); + // Evaluate process status + int exitCode = ProcessTools.executeCommand(pb).getExitValue(); if (exitCode != 0) { throw new RuntimeException("Unexpected exit code: " + exitCode); } diff --git a/test/jdk/java/util/TimeZone/TimeZoneRegression.java b/test/jdk/java/util/TimeZone/TimeZoneRegression.java index 3dabbe49119..6343279689f 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneRegression.java +++ b/test/jdk/java/util/TimeZone/TimeZoneRegression.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -27,42 +27,44 @@ * 4154525 4154537 4154542 4154650 4159922 4162593 4173604 4176686 4184229 4208960 * 4966229 6433179 6851214 8007520 8008577 * @library /java/text/testlib - * @run main/othervm -Djava.locale.providers=COMPAT,SPI TimeZoneRegression + * @run junit/othervm -Djava.locale.providers=COMPAT,SPI TimeZoneRegression */ import java.util.*; import java.io.*; import java.text.*; -public class TimeZoneRegression extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TimeZoneRegression().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TimeZoneRegression { + @Test public void Test4073209() { TimeZone z1 = TimeZone.getTimeZone("PST"); TimeZone z2 = TimeZone.getTimeZone("PST"); if (z1 == z2) { - errln("Fail: TimeZone should return clones"); + fail("Fail: TimeZone should return clones"); } } @SuppressWarnings("deprecation") + @Test public void Test4073215() { SimpleTimeZone z = new SimpleTimeZone(0, "GMT"); if (z.useDaylightTime()) { - errln("Fail: Fix test to start with non-DST zone"); + fail("Fail: Fix test to start with non-DST zone"); } z.setStartRule(Calendar.FEBRUARY, 1, Calendar.SUNDAY, 0); z.setEndRule(Calendar.MARCH, -1, Calendar.SUNDAY, 0); if (!z.useDaylightTime()) { - errln("Fail: DST not active"); + fail("Fail: DST not active"); } if (z.inDaylightTime(new Date(97, Calendar.JANUARY, 31)) || !z.inDaylightTime(new Date(97, Calendar.MARCH, 1)) || z.inDaylightTime(new Date(97, Calendar.MARCH, 31))) { - errln("Fail: DST not working as expected"); + fail("Fail: DST not working as expected"); } } @@ -74,6 +76,7 @@ public void Test4073215() { * day of end 0:59 AM STD = display name 1:59 AM DT * 1:00 AM STD = display name 1:00 AM ST */ + @Test public void Test4084933() { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -113,10 +116,11 @@ private void sub4084933(TimeZone tz) { offset3 != SToffset || offset4 != DToffset || offset5 != DToffset || offset6 != SToffset || offset7 != SToffset || offset8 != SToffset) - errln("Fail: TimeZone misbehaving"); { + fail("Fail: TimeZone misbehaving"); { } } + @Test public void Test4096952() { String[] ZONES = { "GMT", "MET", "IST" }; boolean pass = true; @@ -124,7 +128,7 @@ public void Test4096952() { for (int i=0; i max) max = ids.length; - logln(hname + ' ' + ids.length + + System.out.println(hname + ' ' + ids.length + ((ids.length > 0) ? (" e.g. " + ids[0]) : "")); } catch (Exception e) { - errln(hname + ' ' + "Fail: " + e); + fail(hname + ' ' + "Fail: " + e); } } - logln("Maximum zones per offset = " + max); + System.out.println("Maximum zones per offset = " + max); } + @Test public void Test4151429() { try { TimeZone tz = TimeZone.getTimeZone("GMT"); String name = tz.getDisplayName(true, Integer.MAX_VALUE, Locale.getDefault()); - errln("IllegalArgumentException not thrown by TimeZone.getDisplayName()"); + fail("IllegalArgumentException not thrown by TimeZone.getDisplayName()"); } catch(IllegalArgumentException e) {} } @@ -373,6 +381,7 @@ public void Test4151429() { * SimpleTimeZone accepts illegal DST savings values. These values * must be non-zero. There is no upper limit at this time. */ + @Test public void Test4154525() { final int GOOD = 1, BAD = 0; int[] DATA = { @@ -404,15 +413,15 @@ public void Test4154525() { break; } if (valid) { - logln("Pass: DST savings of " + savings + " accepted by " + method); + System.out.println("Pass: DST savings of " + savings + " accepted by " + method); } else { - errln("Fail: DST savings of " + savings + " accepted by " + method); + fail("Fail: DST savings of " + savings + " accepted by " + method); } } catch (IllegalArgumentException e) { if (valid) { - errln("Fail: DST savings of " + savings + " to " + method + " gave " + e); + fail("Fail: DST savings of " + savings + " to " + method + " gave " + e); } else { - logln("Pass: DST savings of " + savings + " to " + method + " gave " + e); + System.out.println("Pass: DST savings of " + savings + " to " + method + " gave " + e); } } } @@ -423,6 +432,7 @@ public void Test4154525() { * SimpleTimeZone.hasSameRules() doesn't work for zones with no DST * and different DST parameters. */ + @Test public void Test4154537() { // tz1 and tz2 have no DST and different rule parameters SimpleTimeZone tz1 = new SimpleTimeZone(0, "1", 0, 0, 0, 0, 2, 0, 0, 0); @@ -435,15 +445,15 @@ public void Test4154537() { if (tz1.useDaylightTime() || tz2.useDaylightTime() || !tza.useDaylightTime() || !tzA.useDaylightTime() || !tzb.useDaylightTime()) { - errln("Test is broken -- rewrite it"); + fail("Test is broken -- rewrite it"); } if (!tza.hasSameRules(tzA) || tza.hasSameRules(tzb)) { - errln("Fail: hasSameRules() broken for zones with rules"); + fail("Fail: hasSameRules() broken for zones with rules"); } if (!tz1.hasSameRules(tz2)) { - errln("Fail: hasSameRules() returns false for zones without rules"); - errln("zone 1 = " + tz1); - errln("zone 2 = " + tz2); + fail("Fail: hasSameRules() returns false for zones without rules"); + fail("zone 1 = " + tz1); + fail("zone 2 = " + tz2); } } @@ -451,6 +461,7 @@ public void Test4154537() { * SimpleTimeZone constructors, setStartRule(), and setEndRule() don't * check for out-of-range arguments. */ + @Test public void Test4154542() { final int GOOD = 1; final int BAD = 0; @@ -496,7 +507,7 @@ public void Test4154542() { ex = e; } if ((ex == null) != shouldBeGood) { - errln("setStartRule(month=" + month + ", day=" + day + + fail("setStartRule(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -509,7 +520,7 @@ public void Test4154542() { ex = e; } if ((ex == null) != shouldBeGood) { - errln("setEndRule(month=" + month + ", day=" + day + + fail("setEndRule(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -524,7 +535,7 @@ public void Test4154542() { ex = e; } if ((ex == null) != shouldBeGood) { - errln("SimpleTimeZone(month=" + month + ", day=" + day + + fail("SimpleTimeZone(month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (", ) should work but throws " + ex) : ", ) should fail but doesn't")); @@ -539,7 +550,7 @@ public void Test4154542() { ex = e; } if ((ex == null) != shouldBeGood) { - errln("SimpleTimeZone(, month=" + month + ", day=" + day + + fail("SimpleTimeZone(, month=" + month + ", day=" + day + ", dayOfWeek=" + dayOfWeek + ", time=" + time + (shouldBeGood ? (") should work but throws " + ex) : ") should fail but doesn't")); @@ -550,6 +561,7 @@ public void Test4154542() { /** * SimpleTimeZone.getOffset accepts illegal arguments. */ + @Test public void Test4154650() { final int GOOD=1, BAD=0; final int GOOD_ERA=GregorianCalendar.AD, GOOD_YEAR=1998, GOOD_MONTH=Calendar.AUGUST; @@ -594,7 +606,7 @@ public void Test4154650() { e = ex; } if (good != (e == null)) { - errln("Fail: getOffset(" + + fail("Fail: getOffset(" + DATA[i+1] + ", " + DATA[i+2] + ", " + DATA[i+3] + ", " + DATA[i+4] + ", " + DATA[i+5] + ", " + DATA[i+6] + (good ? (") threw " + e) : ") accepts invalid args")); @@ -605,6 +617,7 @@ public void Test4154650() { /** * TimeZone constructors allow null IDs. */ + @Test public void Test4159922() { TimeZone z = null; @@ -612,38 +625,38 @@ public void Test4159922() { // allow null. try { z = TimeZone.getTimeZone((String)null); - errln("FAIL: Null allowed in getTimeZone"); + fail("FAIL: Null allowed in getTimeZone"); } catch (NullPointerException e) {} z = TimeZone.getTimeZone("GMT"); try { z.getDisplayName(false, TimeZone.SHORT, null); - errln("FAIL: Null allowed in getDisplayName(3)"); + fail("FAIL: Null allowed in getDisplayName(3)"); } catch (NullPointerException e) {} try { z.getDisplayName(null); - errln("FAIL: Null allowed in getDisplayName(1)"); + fail("FAIL: Null allowed in getDisplayName(1)"); } catch (NullPointerException e) {} try { if (z.hasSameRules(null)) { - errln("FAIL: hasSameRules returned true"); + fail("FAIL: hasSameRules returned true"); } } catch (NullPointerException e) { - errln("FAIL: Null NOT allowed in hasSameRules"); + fail("FAIL: Null NOT allowed in hasSameRules"); } try { z.inDaylightTime(null); - errln("FAIL: Null allowed in inDaylightTime"); + fail("FAIL: Null allowed in inDaylightTime"); } catch (NullPointerException e) {} try { z.setID(null); - errln("FAIL: Null allowed in setID"); + fail("FAIL: Null allowed in setID"); } catch (NullPointerException e) {} TimeZone save = TimeZone.getDefault(); try { TimeZone.setDefault(null); } catch (NullPointerException e) { - errln("FAIL: Null NOT allowed in setDefault"); + fail("FAIL: Null NOT allowed in setDefault"); } finally { TimeZone.setDefault(save); } @@ -652,15 +665,15 @@ public void Test4159922() { SimpleTimeZone s = null; try { s = new SimpleTimeZone(0, null); - errln("FAIL: Null allowed in SimpleTimeZone(2)"); + fail("FAIL: Null allowed in SimpleTimeZone(2)"); } catch (NullPointerException e) {} try { s = new SimpleTimeZone(0, null, 0, 1, 0, 0, 0, 1, 0, 0); - errln("FAIL: Null allowed in SimpleTimeZone(10)"); + fail("FAIL: Null allowed in SimpleTimeZone(10)"); } catch (NullPointerException e) {} try { s = new SimpleTimeZone(0, null, 0, 1, 0, 0, 0, 1, 0, 0, 1000); - errln("FAIL: Null allowed in SimpleTimeZone(11)"); + fail("FAIL: Null allowed in SimpleTimeZone(11)"); } catch (NullPointerException e) {} } @@ -669,6 +682,7 @@ public void Test4159922() { * transitions at midnight correctly. */ @SuppressWarnings("deprecation") + @Test public void Test4162593() { SimpleDateFormat fmt = new SimpleDateFormat("z", Locale.US); final int ONE_HOUR = 60*60*1000; @@ -711,18 +725,18 @@ public void Test4162593() { Date d = new Date(p[0], p[1], p[2], p[3], p[4]); boolean transitionExpected = ((Boolean)DATA[j+2]).booleanValue(); - logln(tz.getID() + ":"); + System.out.println(tz.getID() + ":"); for (int i=0; i<4; ++i) { zone[i] = fmt.format(d); - logln("" + i + ": " + d); + System.out.println("" + i + ": " + d); d = new Date(d.getTime() + ONE_HOUR); } if (zone[0].equals(zone[1]) && (zone[1].equals(zone[2]) != transitionExpected) && zone[2].equals(zone[3])) { - logln("Ok: transition " + transitionExpected); + System.out.println("Ok: transition " + transitionExpected); } else { - errln("Fail: boundary transition incorrect"); + fail("Fail: boundary transition incorrect"); } } } @@ -736,6 +750,7 @@ public void Test4162593() { /** * TimeZone broken in last hour of year */ + @Test public void Test4173604() { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -748,7 +763,7 @@ private void sub4173604(TimeZone pst) { int o23 = pst.getOffset(1, 1998, 11, 31, Calendar.THURSDAY, 23*60*60*1000); int o00 = pst.getOffset(1, 1999, 0, 1, Calendar.FRIDAY, 0); if (o22 != o23 || o22 != o00) { - errln("Offsets should be the same (for PST), but got: " + + fail("Offsets should be the same (for PST), but got: " + "12/31 22:00 " + o22 + ", 12/31 23:00 " + o23 + ", 01/01 00:00 " + o00); @@ -767,12 +782,12 @@ private void sub4173604(TimeZone pst) { ++transitions; Calendar t = (Calendar)cal.clone(); t.add(Calendar.MINUTE, -delta); - logln(t.getTime() + " " + t.get(Calendar.DST_OFFSET)); - logln(cal.getTime() + " " + (lastDST=cal.get(Calendar.DST_OFFSET))); + System.out.println(t.getTime() + " " + t.get(Calendar.DST_OFFSET)); + System.out.println(cal.getTime() + " " + (lastDST=cal.get(Calendar.DST_OFFSET))); } } if (transitions != 4) { - errln("Saw " + transitions + " transitions; should have seen 4"); + fail("Saw " + transitions + " transitions; should have seen 4"); } } @@ -780,6 +795,7 @@ private void sub4173604(TimeZone pst) { * getDisplayName doesn't work with unusual savings/offsets. */ @SuppressWarnings("deprecation") + @Test public void Test4176686() { // Construct a zone that does not observe DST but // that does have a DST savings (which should be ignored). @@ -827,7 +843,7 @@ public void Test4176686() { for (int i=0; i " + DATA[i+1] + ", exp " + DATA[i+2]); + fail("FAIL: " + DATA[i] + " -> " + DATA[i+1] + ", exp " + DATA[i+2]); } } } @@ -835,57 +851,58 @@ public void Test4176686() { /** * SimpleTimeZone allows invalid DOM values. */ + @Test public void Test4184229() { SimpleTimeZone zone = null; try { zone = new SimpleTimeZone(0, "A", 0, -1, 0, 0, 0, 0, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 startDay"); + fail("Failed. No exception has been thrown for DOM -1 startDay"); } catch(IllegalArgumentException e) { - logln("(a) " + e.getMessage()); + System.out.println("(a) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, 0, 0, 0, 0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 endDay"); + fail("Failed. No exception has been thrown for DOM -1 endDay"); } catch(IllegalArgumentException e) { - logln("(b) " + e.getMessage()); + System.out.println("(b) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, -1, 0, 0, 0, 0, 0, 0, 1000); - errln("Failed. No exception has been thrown for DOM -1 startDay +savings"); + fail("Failed. No exception has been thrown for DOM -1 startDay +savings"); } catch(IllegalArgumentException e) { - logln("(c) " + e.getMessage()); + System.out.println("(c) " + e.getMessage()); } try { zone = new SimpleTimeZone(0, "A", 0, 0, 0, 0, 0, -1, 0, 0, 1000); - errln("Failed. No exception has been thrown for DOM -1 endDay +savings"); + fail("Failed. No exception has been thrown for DOM -1 endDay +savings"); } catch(IllegalArgumentException e) { - logln("(d) " + e.getMessage()); + System.out.println("(d) " + e.getMessage()); } // Make a valid constructor call for subsequent tests. zone = new SimpleTimeZone(0, "A", 0, 1, 0, 0, 0, 1, 0, 0); try { zone.setStartRule(0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 setStartRule +savings"); + fail("Failed. No exception has been thrown for DOM -1 setStartRule +savings"); } catch(IllegalArgumentException e) { - logln("(e) " + e.getMessage()); + System.out.println("(e) " + e.getMessage()); } try { zone.setStartRule(0, -1, 0); - errln("Failed. No exception has been thrown for DOM -1 setStartRule"); + fail("Failed. No exception has been thrown for DOM -1 setStartRule"); } catch(IllegalArgumentException e) { - logln("(f) " + e.getMessage()); + System.out.println("(f) " + e.getMessage()); } try { zone.setEndRule(0, -1, 0, 0); - errln("Failed. No exception has been thrown for DOM -1 setEndRule +savings"); + fail("Failed. No exception has been thrown for DOM -1 setEndRule +savings"); } catch(IllegalArgumentException e) { - logln("(g) " + e.getMessage()); + System.out.println("(g) " + e.getMessage()); } try { zone.setEndRule(0, -1, 0); - errln("Failed. No exception has been thrown for DOM -1 setEndRule"); + fail("Failed. No exception has been thrown for DOM -1 setEndRule"); } catch(IllegalArgumentException e) { - logln("(h) " + e.getMessage()); + System.out.println("(h) " + e.getMessage()); } } @@ -893,6 +910,7 @@ public void Test4184229() { * SimpleTimeZone.getOffset() throws IllegalArgumentException when to get * of 2/29/1996 (leap day). */ + @Test public void Test4208960 () { // test both SimpleTimeZone and ZoneInfo objects. // @since 1.4 @@ -905,14 +923,14 @@ private void sub4208960(TimeZone tz) { int offset = tz.getOffset(GregorianCalendar.AD, 1996, Calendar.FEBRUARY, 29, Calendar.THURSDAY, 0); } catch (IllegalArgumentException e) { - errln("FAILED: to get TimeZone.getOffset(2/29/96)"); + fail("FAILED: to get TimeZone.getOffset(2/29/96)"); } try { int offset = tz.getOffset(GregorianCalendar.AD, 1997, Calendar.FEBRUARY, 29, Calendar.THURSDAY, 0); - errln("FAILED: TimeZone.getOffset(2/29/97) expected to throw Exception."); + fail("FAILED: TimeZone.getOffset(2/29/97) expected to throw Exception."); } catch (IllegalArgumentException e) { - logln("got IllegalArgumentException"); + System.out.println("got IllegalArgumentException"); } } @@ -921,6 +939,7 @@ private void sub4208960(TimeZone tz) { * sun.util.calendar.ZoneInfo doesn't clone properly. */ @SuppressWarnings("deprecation") + @Test public void Test4966229() { TimeZone savedTZ = TimeZone.getDefault(); try { @@ -945,7 +964,7 @@ public void Test4966229() { cal2.setTime(d); int hourOfDay = cal2.get(cal.HOUR_OF_DAY); if (hourOfDay != expectedHourOfDay) { - errln("wrong hour of day: got: " + hourOfDay + fail("wrong hour of day: got: " + hourOfDay + ", expected: " + expectedHourOfDay); } } finally { @@ -956,6 +975,7 @@ public void Test4966229() { /** * 6433179: (tz) Incorrect DST end for America/Winnipeg and Canada/Central in 2038+ */ + @Test public void Test6433179() { // Use the old America/Winnipeg rule for testing. Note that // startMode is WALL_TIME for testing. It's actually @@ -974,7 +994,7 @@ public void Test6433179() { cal.set(cal.DAY_OF_WEEK_IN_MONTH, -1); cal.add(Calendar.HOUR_OF_DAY, 2); if (cal.get(cal.DST_OFFSET) == 0) { - errln("Should still be in DST."); + fail("Should still be in DST."); } } diff --git a/test/jdk/java/util/TimeZone/TimeZoneTest.java b/test/jdk/java/util/TimeZone/TimeZoneTest.java index 8e5d403f87b..ec2326293fd 100644 --- a/test/jdk/java/util/TimeZone/TimeZoneTest.java +++ b/test/jdk/java/util/TimeZone/TimeZoneTest.java @@ -27,8 +27,8 @@ * 8008577 8077685 8098547 8133321 8138716 8148446 8151876 8159684 8166875 8181157 * 8228469 8274407 8305113 * @modules java.base/sun.util.resources - * @library /java/text/testlib * @summary test TimeZone + * @run junit TimeZoneTest */ import java.io.*; @@ -36,14 +36,14 @@ import java.util.*; import sun.util.resources.LocaleData; -public class TimeZoneTest extends IntlTest +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.fail; + +public class TimeZoneTest { static final int millisPerHour = 3600000; - public static void main(String[] args) throws Exception { - new TimeZoneTest().run(args); - } - /** * Bug 4130885 * Certain short zone IDs, used since 1.1.x, are incorrect. @@ -99,6 +99,7 @@ public static void main(String[] args) throws Exception { * else. E.g., EST usually indicates the US Eastern zone, so it cannot be * used for Brazil (BET). */ + @Test public void TestShortZoneIDs() throws Exception { ZoneDescriptor[] JDK_116_REFERENCE_LIST = { @@ -153,10 +154,10 @@ public void TestShortZoneIDs() throws Exception { ZoneDescriptor referenceZone = JDK_116_REFERENCE_LIST[i]; ZoneDescriptor currentZone = hash.get(referenceZone.getID()); if (referenceZone.equals(currentZone)) { - logln("ok " + referenceZone); + System.out.println("ok " + referenceZone); } else { - errln("Fail: Expected " + referenceZone + + fail("Fail: Expected " + referenceZone + "; got " + currentZone); } } @@ -238,6 +239,7 @@ static final String formatMinutes(int min) { * ID "Custom" is no longer used for TimeZone objects created with * a custom time zone ID, such as "GMT-8". See 4322313. */ + @Test public void TestCustomParse() throws Exception { Object[] DATA = { // ID Expected offset in minutes @@ -261,7 +263,7 @@ public void TestCustomParse() throws Exception { Integer exp = (Integer)DATA[i+1]; TimeZone zone = TimeZone.getTimeZone(id); if (zone.getID().equals("GMT")) { - logln(id + " -> generic GMT"); + System.out.println(id + " -> generic GMT"); // When TimeZone.getTimeZone() can't parse the id, it // returns GMT -- a dubious practice, but required for // backward compatibility. @@ -273,7 +275,7 @@ public void TestCustomParse() throws Exception { else { int ioffset = zone.getRawOffset()/60000; String offset = formatMinutes(ioffset); - logln(id + " -> " + zone.getID() + " GMT" + offset); + System.out.println(id + " -> " + zone.getID() + " GMT" + offset); if (exp == null) { throw new Exception("Expected parse failure for " + id + ", got offset of " + offset + @@ -300,12 +302,13 @@ else if (ioffset != exp.intValue()) { * 4/21/98 - make smarter, so the test works if the ext resources * are present or not. */ + @Test public void TestDisplayName() { TimeZone zone = TimeZone.getTimeZone("PST"); String name = zone.getDisplayName(Locale.ENGLISH); - logln("PST->" + name); + System.out.println("PST->" + name); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected \"Pacific Standard Time\""); + fail("Fail: Expected \"Pacific Standard Time\""); //***************************************************************** // THE FOLLOWING LINES MUST BE UPDATED IF THE LOCALE DATA CHANGES @@ -324,7 +327,7 @@ public void TestDisplayName() { ((Integer)DATA[i+1]).intValue(), Locale.ENGLISH); if (!name.equals(DATA[i+2])) - errln("Fail: Expected " + DATA[i+2] + "; got " + name); + fail("Fail: Expected " + DATA[i+2] + "; got " + name); } // Make sure that we don't display the DST name by constructing a fake @@ -332,11 +335,11 @@ public void TestDisplayName() { SimpleTimeZone zone2 = new SimpleTimeZone(0, "PST"); zone2.setStartRule(Calendar.JANUARY, 1, 0); zone2.setEndRule(Calendar.DECEMBER, 31, 0); - logln("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date())); + System.out.println("Modified PST inDaylightTime->" + zone2.inDaylightTime(new Date())); name = zone2.getDisplayName(Locale.ENGLISH); - logln("Modified PST->" + name); + System.out.println("Modified PST->" + name); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected \"Pacific Standard Time\""); + fail("Fail: Expected \"Pacific Standard Time\""); // Make sure we get the default display format for Locales // with no display name data. @@ -347,7 +350,7 @@ public void TestDisplayName() { // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES // THE FOLLOWING LINE MUST BE UPDATED IF THE LOCALE DATA CHANGES //***************************************************************** - logln("PST(zh_CN)->" + name); + System.out.println("PST(zh_CN)->" + name); // Now be smart -- check to see if zh resource is even present. // If not, we expect the en fallback behavior. @@ -359,9 +362,9 @@ public void TestDisplayName() { boolean noZH = enRB == zhRB; if (noZH) { - logln("Warning: Not testing the zh_CN behavior because resource is absent"); + System.out.println("Warning: Not testing the zh_CN behavior because resource is absent"); if (!name.equals("Pacific Standard Time")) - errln("Fail: Expected Pacific Standard Time"); + fail("Fail: Expected Pacific Standard Time"); } else if (!name.equals("Pacific Standard Time") && !name.equals("\u592a\u5e73\u6d0b\u6807\u51c6\u65f6\u95f4") && @@ -370,48 +373,49 @@ else if (!name.equals("Pacific Standard Time") && !name.equals("GMT-8:00") && !name.equals("GMT-0800") && !name.equals("GMT-800")) { - errln("Fail: Expected GMT-08:00 or something similar"); - errln("************************************************************"); - errln("THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED"); - errln("************************************************************"); + fail("Fail: Expected GMT-08:00 or something similar\n" + + "************************************************************\n" + + "THE ABOVE FAILURE MAY JUST MEAN THE LOCALE DATA HAS CHANGED\n" + + "************************************************************\n"); } // Now try a non-existent zone zone2 = new SimpleTimeZone(90*60*1000, "xyzzy"); name = zone2.getDisplayName(Locale.ENGLISH); - logln("GMT+90min->" + name); + System.out.println("GMT+90min->" + name); if (!name.equals("GMT+01:30") && !name.equals("GMT+1:30") && !name.equals("GMT+0130") && !name.equals("GMT+130")) - errln("Fail: Expected GMT+01:30 or something similar"); + fail("Fail: Expected GMT+01:30 or something similar"); } + @Test public void TestGenericAPI() { String id = "NewGMT"; int offset = 12345; SimpleTimeZone zone = new SimpleTimeZone(offset, id); if (zone.useDaylightTime()) { - errln("FAIL: useDaylightTime should return false"); + fail("FAIL: useDaylightTime should return false"); } TimeZone zoneclone = (TimeZone)zone.clone(); if (!zoneclone.equals(zone)) { - errln("FAIL: clone or operator== failed"); + fail("FAIL: clone or operator== failed"); } zoneclone.setID("abc"); if (zoneclone.equals(zone)) { - errln("FAIL: clone or operator!= failed"); + fail("FAIL: clone or operator!= failed"); } zoneclone = (TimeZone)zone.clone(); if (!zoneclone.equals(zone)) { - errln("FAIL: clone or operator== failed"); + fail("FAIL: clone or operator== failed"); } zoneclone.setRawOffset(45678); if (zoneclone.equals(zone)) { - errln("FAIL: clone or operator!= failed"); + fail("FAIL: clone or operator!= failed"); } TimeZone saveDefault = TimeZone.getDefault(); @@ -419,10 +423,10 @@ public void TestGenericAPI() { TimeZone.setDefault(zone); TimeZone defaultzone = TimeZone.getDefault(); if (defaultzone == zone) { - errln("FAIL: Default object is identical, not clone"); + fail("FAIL: Default object is identical, not clone"); } if (!defaultzone.equals(zone)) { - errln("FAIL: Default object is not equal"); + fail("FAIL: Default object is not equal"); } } finally { @@ -431,13 +435,14 @@ public void TestGenericAPI() { } @SuppressWarnings("deprecation") + @Test public void TestRuleAPI() { // ErrorCode status = ZERO_ERROR; int offset = (int)(60*60*1000*1.75); // Pick a weird offset SimpleTimeZone zone = new SimpleTimeZone(offset, "TestZone"); - if (zone.useDaylightTime()) errln("FAIL: useDaylightTime should return false"); + if (zone.useDaylightTime()) fail("FAIL: useDaylightTime should return false"); // Establish our expected transition times. Do this with a non-DST // calendar with the (above) declared local offset. @@ -465,18 +470,18 @@ public void TestRuleAPI() long expMarchOne = 636251400000L; if (marchOne != expMarchOne) { - errln("FAIL: Expected start computed as " + marchOne + + fail("FAIL: Expected start computed as " + marchOne + " = " + new Date(marchOne)); - logln(" Should be " + expMarchOne + + System.out.println(" Should be " + expMarchOne + " = " + new Date(expMarchOne)); } long expJulyOne = 646793100000L; if (julyOne != expJulyOne) { - errln("FAIL: Expected start computed as " + julyOne + + fail("FAIL: Expected start computed as " + julyOne + " = " + new Date(julyOne)); - logln(" Should be " + expJulyOne + + System.out.println(" Should be " + expJulyOne + " = " + new Date(expJulyOne)); } @@ -487,15 +492,15 @@ public void TestRuleAPI() if (zone.inDaylightTime(new Date(marchOne - 1000)) || !zone.inDaylightTime(new Date(marchOne))) - errln("FAIL: Start rule broken"); + fail("FAIL: Start rule broken"); if (!zone.inDaylightTime(new Date(julyOne - 1000)) || zone.inDaylightTime(new Date(julyOne))) - errln("FAIL: End rule broken"); + fail("FAIL: End rule broken"); zone.setStartYear(1991); if (zone.inDaylightTime(new Date(marchOne)) || zone.inDaylightTime(new Date(julyOne - 1000))) - errln("FAIL: Start year broken"); + fail("FAIL: Start year broken"); // failure(status, "TestRuleAPI"); // delete gc; @@ -508,7 +513,7 @@ void testUsingBinarySearch(SimpleTimeZone tz, long min, long max, long expectedB boolean startsInDST = tz.inDaylightTime(new Date(min)); // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; if (tz.inDaylightTime(new Date(max)) == startsInDST) { - logln("Error: inDaylightTime(" + new Date(max) + ") != " + (!startsInDST)); + System.out.println("Error: inDaylightTime(" + new Date(max) + ") != " + (!startsInDST)); return; } // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; @@ -522,52 +527,54 @@ void testUsingBinarySearch(SimpleTimeZone tz, long min, long max, long expectedB } // if (failure(status, "SimpleTimeZone::inDaylightTime")) return; } - logln("Binary Search Before: " + min + " = " + new Date(min)); - logln("Binary Search After: " + max + " = " + new Date(max)); + System.out.println("Binary Search Before: " + min + " = " + new Date(min)); + System.out.println("Binary Search After: " + max + " = " + new Date(max)); long mindelta = expectedBoundary - min; long maxdelta = max - expectedBoundary; if (mindelta >= 0 && mindelta <= INTERVAL && mindelta >= 0 && mindelta <= INTERVAL) - logln("PASS: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); + System.out.println("PASS: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); else - errln("FAIL: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); + fail("FAIL: Expected bdry: " + expectedBoundary + " = " + new Date(expectedBoundary)); } static final int INTERVAL = 100; // Bug 006; verify the offset for a specific zone. + @Test public void TestPRTOffset() { TimeZone tz = TimeZone.getTimeZone( "PRT" ); if( tz == null ) { - errln( "FAIL: TimeZone(PRT) is null" ); + fail( "FAIL: TimeZone(PRT) is null" ); } else{ if (tz.getRawOffset() != (-4*millisPerHour)) - errln("FAIL: Offset for PRT should be -4"); + fail("FAIL: Offset for PRT should be -4"); } } // Test various calls @SuppressWarnings("deprecation") + @Test public void TestVariousAPI518() { TimeZone time_zone = TimeZone.getTimeZone("PST"); Date d = new Date(97, Calendar.APRIL, 30); - logln("The timezone is " + time_zone.getID()); + System.out.println("The timezone is " + time_zone.getID()); if (time_zone.inDaylightTime(d) != true) - errln("FAIL: inDaylightTime returned false"); + fail("FAIL: inDaylightTime returned false"); if (time_zone.useDaylightTime() != true) - errln("FAIL: useDaylightTime returned false"); + fail("FAIL: useDaylightTime returned false"); if (time_zone.getRawOffset() != -8*millisPerHour) - errln( "FAIL: getRawOffset returned wrong value"); + fail( "FAIL: getRawOffset returned wrong value"); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(d); @@ -575,10 +582,11 @@ public void TestVariousAPI518() gc.get(gc.DAY_OF_MONTH), gc.get(gc.DAY_OF_WEEK), 0) != -7*millisPerHour) - errln("FAIL: getOffset returned wrong value"); + fail("FAIL: getOffset returned wrong value"); } // Test getAvailableID API + @Test public void TestGetAvailableIDs913() { StringBuffer buf = new StringBuffer("TimeZone.getAvailableIDs() = { "); @@ -589,7 +597,7 @@ public void TestGetAvailableIDs913() buf.append(s[i]); } buf.append(" };"); - logln(buf.toString()); + System.out.println(buf.toString()); buf.setLength(0); buf.append("TimeZone.getAvailableIDs(GMT+02:00) = { "); @@ -600,31 +608,32 @@ public void TestGetAvailableIDs913() buf.append(s[i]); } buf.append(" };"); - logln(buf.toString()); + System.out.println(buf.toString()); TimeZone tz = TimeZone.getTimeZone("PST"); if (tz != null) - logln("getTimeZone(PST) = " + tz.getID()); + System.out.println("getTimeZone(PST) = " + tz.getID()); else - errln("FAIL: getTimeZone(PST) = null"); + fail("FAIL: getTimeZone(PST) = null"); tz = TimeZone.getTimeZone("America/Los_Angeles"); if (tz != null) - logln("getTimeZone(America/Los_Angeles) = " + tz.getID()); + System.out.println("getTimeZone(America/Los_Angeles) = " + tz.getID()); else - errln("FAIL: getTimeZone(PST) = null"); + fail("FAIL: getTimeZone(PST) = null"); // Bug 4096694 tz = TimeZone.getTimeZone("NON_EXISTENT"); if (tz == null) - errln("FAIL: getTimeZone(NON_EXISTENT) = null"); + fail("FAIL: getTimeZone(NON_EXISTENT) = null"); else if (!tz.getID().equals("GMT")) - errln("FAIL: getTimeZone(NON_EXISTENT) = " + tz.getID()); + fail("FAIL: getTimeZone(NON_EXISTENT) = " + tz.getID()); } /** * Bug 4107276 */ + @Test public void TestDSTSavings() { // It might be better to find a way to integrate this test into the main TimeZone // tests above, but I don't have time to figure out how to do this (or if it's @@ -634,43 +643,44 @@ public void TestDSTSavings() { (int)(0.5 * millisPerHour)); if (tz.getRawOffset() != -5 * millisPerHour) - errln("Got back a raw offset of " + (tz.getRawOffset() / millisPerHour) + + fail("Got back a raw offset of " + (tz.getRawOffset() / millisPerHour) + " hours instead of -5 hours."); if (!tz.useDaylightTime()) - errln("Test time zone should use DST but claims it doesn't."); + fail("Test time zone should use DST but claims it doesn't."); if (tz.getDSTSavings() != 0.5 * millisPerHour) - errln("Set DST offset to 0.5 hour, but got back " + (tz.getDSTSavings() / + fail("Set DST offset to 0.5 hour, but got back " + (tz.getDSTSavings() / millisPerHour) + " hours instead."); int offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JANUARY, 1, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + fail("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 1, Calendar.MONDAY, 10 * millisPerHour); if (offset != -4.5 * millisPerHour) - errln("The offset for 10 AM, 6/1/98 should have been -4.5 hours, but we got " + fail("The offset for 10 AM, 6/1/98 should have been -4.5 hours, but we got " + (offset / millisPerHour) + " hours."); tz.setDSTSavings(millisPerHour); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JANUARY, 1, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + fail("The offset for 10 AM, 1/1/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.JUNE, 1, Calendar.MONDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10 AM, 6/1/98 (with a 1-hour DST offset) should have been -4 hours, but we got " + fail("The offset for 10 AM, 6/1/98 (with a 1-hour DST offset) should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); } /** * Bug 4107570 */ + @Test public void TestAlternateRules() { // Like TestDSTSavings, this test should probably be integrated somehow with the main // test at the top of this class, but I didn't have time to figure out how to do that. @@ -685,25 +695,25 @@ public void TestAlternateRules() { int offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 5, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 3/5/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 3/5/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 15, Calendar.SUNDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 3/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 3/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 15, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 25, Calendar.SUNDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 10/25/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 10/25/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); // test the day-of-week-after-day-in-month API @@ -713,25 +723,25 @@ public void TestAlternateRules() { offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 11, Calendar.WEDNESDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 3/11/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 3/11/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.MARCH, 14, Calendar.SATURDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 3/14/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 3/14/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 15, Calendar.THURSDAY, 10 * millisPerHour); if (offset != -4 * millisPerHour) - errln("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + fail("The offset for 10AM, 10/15/98 should have been -4 hours, but we got " + (offset / millisPerHour) + " hours."); offset = tz.getOffset(GregorianCalendar.AD, 1998, Calendar.OCTOBER, 17, Calendar.SATURDAY, 10 * millisPerHour); if (offset != -5 * millisPerHour) - errln("The offset for 10AM, 10/17/98 should have been -5 hours, but we got " + fail("The offset for 10AM, 10/17/98 should have been -5 hours, but we got " + (offset / millisPerHour) + " hours."); } } diff --git a/test/jdk/java/util/TimeZone/TransitionTest.java b/test/jdk/java/util/TimeZone/TransitionTest.java index 5f012d09d72..fb3e42cf17e 100644 --- a/test/jdk/java/util/TimeZone/TransitionTest.java +++ b/test/jdk/java/util/TimeZone/TransitionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,8 +24,8 @@ /* * @test * @bug 4278609 4761696 - * @library /java/text/testlib * @summary Make sure to handle DST transition ending at 0:00 January 1. + * @run junit TransitionTest */ import java.text.SimpleDateFormat; @@ -36,12 +36,13 @@ import java.util.SimpleTimeZone; import java.util.TimeZone; -public class TransitionTest extends IntlTest { +import org.junit.jupiter.api.Test; - public static void main(String[] args) throws Exception { - new TransitionTest().run(args); - } +import static org.junit.jupiter.api.Assertions.fail; + +public class TransitionTest { + @Test public void Test4278609() { SimpleTimeZone tz = new SimpleTimeZone(0, "MyTimeZone", /* DST start day: August, 1, 0:00 */ @@ -77,7 +78,7 @@ public void Test4278609() { SimpleDateFormat format = new SimpleDateFormat("dd MMM HH:mm:ss zzz", Locale.US); format.setTimeZone(tz); - errln("Wrong DST transition: " + tz + fail("Wrong DST transition: " + tz + "\na date just after DST = " + format.format(date) + "\ngetOffset = " + offset); } @@ -88,6 +89,7 @@ public void Test4278609() { * * Derived from JCK test cases some of which specify wrong day of week values. */ + @Test public void Test4761696() { GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT")); @@ -121,7 +123,7 @@ public void Test4761696() { long endTime = cal.getTimeInMillis() + rawOffset; long expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#1: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#1: wrong offset: got "+offset+", expected="+expectedOffset); } // test#2 @@ -150,7 +152,7 @@ public void Test4761696() { endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("Wrong offset: got "+offset+", expected="+expectedOffset); + fail("Wrong offset: got "+offset+", expected="+expectedOffset); } rawOffset = 43200000; @@ -179,7 +181,7 @@ public void Test4761696() { endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#2: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#2: wrong offset: got "+offset+", expected="+expectedOffset); } // test#3 @@ -209,7 +211,7 @@ public void Test4761696() { endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#3: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#3: wrong offset: got "+offset+", expected="+expectedOffset); } // test#4 @@ -243,7 +245,7 @@ public void Test4761696() { long startTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime >= startTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#4: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#4: wrong offset: got "+offset+", expected="+expectedOffset); } // test#5 @@ -272,7 +274,7 @@ public void Test4761696() { endTime = cal.getTimeInMillis() + rawOffset; expectedOffset = (localtime < endTime) ? rawOffset + saving : rawOffset; if (offset != expectedOffset) { - errln("test#5: wrong offset: got "+offset+", expected="+expectedOffset); + fail("test#5: wrong offset: got "+offset+", expected="+expectedOffset); } } diff --git a/test/jdk/java/util/logging/LoggingDeadlock2.java b/test/jdk/java/util/logging/LoggingDeadlock2.java index 4aa3121abc1..e8a0bb49d87 100644 --- a/test/jdk/java/util/logging/LoggingDeadlock2.java +++ b/test/jdk/java/util/logging/LoggingDeadlock2.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,11 +25,12 @@ * @test * @bug 6467152 6716076 6829503 8132550 * @summary deadlock occurs in LogManager initialization and JVM termination + * @key randomness + * @library /test/lib * @author Serguei Spitsyn / Hitachi / Martin Buchholz * * @build LoggingDeadlock2 * @run main LoggingDeadlock2 - * @key randomness */ /* @@ -50,7 +51,6 @@ * This is a regression test for this bug. */ -import java.util.Arrays; import java.util.List; import java.util.Random; import java.util.concurrent.CyclicBarrier; @@ -63,6 +63,8 @@ import java.io.Reader; import java.util.concurrent.TimeUnit; +import jdk.test.lib.process.ProcessTools; + public class LoggingDeadlock2 { // ask child process to dumpstack after 60secs @@ -74,7 +76,9 @@ public class LoggingDeadlock2 { public static void realMain(String arg[]) throws Throwable { try { System.out.println(javaChildArgs); - ProcessBuilder pb = new ProcessBuilder(javaChildArgs); + // Build process (with VM flags) + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( + javaChildArgs); ProcessResults r = run(pb.start()); equal(r.exitValue(), 99); @@ -151,9 +155,6 @@ public void run() { //---------------------------------------------------------------- // The rest of this test is copied from ProcessBuilder/Basic.java //---------------------------------------------------------------- - private static final String javaExe = - System.getProperty("java.home") + - File.separator + "bin" + File.separator + "java"; private static final String jstackExe = System.getProperty("java.home") + File.separator + "bin" + File.separator + "jstack"; @@ -161,10 +162,8 @@ public void run() { private static final String classpath = System.getProperty("java.class.path"); - private static final List javaChildArgs = - Arrays.asList(new String[] - { javaExe, "-classpath", classpath, - "LoggingDeadlock2$JavaChild"}); + private static final List javaChildArgs = List.of( + "-classpath", classpath, "LoggingDeadlock2$JavaChild"); private static class ProcessResults { private final String out; diff --git a/test/jdk/java/util/zip/Available.java b/test/jdk/java/util/zip/Available.java index f2272243101..373282c894b 100644 --- a/test/jdk/java/util/zip/Available.java +++ b/test/jdk/java/util/zip/Available.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -22,69 +22,136 @@ */ /* @test - @bug 4028605 4109069 4234207 4401122 - @summary Make sure ZipInputStream/InflaterInputStream.available() will - return 0 after EOF has reached and 1 otherwise. - */ + * @bug 4028605 4109069 4234207 4401122 8339154 + * @summary Verify that ZipInputStream, InflaterInputStream, ZipFileInputStream, + * ZipFileInflaterInputStream.available() return values according + * to their specification or long-standing behavior + * @run junit Available + */ +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; import java.io.*; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.zip.*; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; + public class Available { - public static void main(String[] args) throws Exception { - // 4028605 4109069 4234207 - test1(); - // test 4401122 - test2(); - } + // ZIP file produced in this test + private final Path zip = Path.of("available.jar"); - private static void test1() throws Exception { - File f = new File(System.getProperty("test.src", "."), "input.jar"); + /** + * Create the ZIP file used in this test, containing + * one deflated and one stored entry. + * + * @throws IOException if an unexpected error occurs + */ + @BeforeEach + public void setup() throws IOException { + byte[] contents = "contents".repeat(10).getBytes(StandardCharsets.UTF_8); - // test ZipInputStream - try (FileInputStream fis = new FileInputStream(f); - ZipInputStream z = new ZipInputStream(fis)) - { - z.getNextEntry(); - tryAvail(z); - } + try (ZipOutputStream zo = new ZipOutputStream(Files.newOutputStream(zip))) { + // First entry uses DEFLATE method + zo.putNextEntry(new ZipEntry("deflated.txt")); + zo.write(contents); - // test InflaterInputStream - try (ZipFile zfile = new ZipFile(f)) { - tryAvail(zfile.getInputStream(zfile.getEntry("Available.java"))); + // Second entry uses STORED method + ZipEntry stored = new ZipEntry("stored.txt"); + stored.setMethod(ZipEntry.STORED); + stored.setSize(contents.length); + CRC32 crc32 = new CRC32(); + crc32.update(contents); + stored.setCrc(crc32.getValue()); + zo.putNextEntry(stored); + zo.write(contents); } } - static void tryAvail(InputStream in) throws Exception { - byte[] buf = new byte[1024]; - int n; + /** + * Delete the ZIP file created by this test + * + * @throws IOException if an unexpected error occurs + */ + @AfterEach + public void cleanup() throws IOException { + Files.deleteIfExists(zip); + } + + /** + * Verify that ZipInputStream.available() returns 0 after EOF or + * closeEntry, otherwise 1, as specified in the API description. + * This tests 4028605 4109069 4234207 + * @throws IOException if an unexpected error occurs + */ + @Test + public void testZipInputStream() throws IOException { + try (InputStream in = Files.newInputStream(zip)) { + ZipInputStream z = new ZipInputStream(in); + z.getNextEntry(); + assertEquals(1, z.available()); + z.read(); + assertEquals(1, z.available()); + z.transferTo(OutputStream.nullOutputStream()); + assertEquals(0, z.available(), + "ZipInputStream.available() should return 0 after EOF"); + + z.close(); + assertThrows(IOException.class, () -> z.available(), + "Expected an IOException when calling available on a closed stream"); + } - while ((n = in.read(buf)) != -1); - if (in.available() != 0) { - throw new Exception("available should return 0 after EOF"); + try (InputStream in = Files.newInputStream(zip); + ZipInputStream z = new ZipInputStream(in)) { + z.getNextEntry(); + z.closeEntry(); + assertEquals(0, z.available(), + "ZipInputStream.available() should return 0 after closeEntry"); } } - // To reproduce 4401122 - private static void test2() throws Exception { - File f = new File(System.getProperty("test.src", "."), "input.jar"); - try (ZipFile zf = new ZipFile(f)) { - InputStream in = zf.getInputStream(zf.getEntry("Available.java")); + /** + * Verify that ZipFileInputStream|ZipFileInflaterInputStream.available() + * return the number of remaining uncompressed bytes. + * + * This verifies unspecified, but long-standing behavior. See 4401122. + * + * @throws IOException if an unexpected error occurs + */ + @ParameterizedTest + @ValueSource(strings = { "stored.txt", "deflated.txt" }) + public void testZipFileStreamsRemainingBytes(String entryName) throws IOException { + try (ZipFile zfile = new ZipFile(zip.toFile())) { + ZipEntry entry = zfile.getEntry(entryName); + // Could be ZipFileInputStream or ZipFileInflaterInputStream + InputStream in = zfile.getInputStream(entry); int initialAvailable = in.available(); - in.read(); - if (in.available() != initialAvailable - 1) - throw new RuntimeException("Available not decremented."); - for(int j=0; j 0; i--) { + // Reading a single byte should decrement available by 1 in.read(); - if (in.available() != 0) - throw new RuntimeException(); + assertEquals(i - 1, in.available(), "Available not decremented"); + } + + // No remaining uncompressed bytes + assertEquals(0, in.available()); + + // available() should still return 0 after close in.close(); - if (in.available() != 0) - throw new RuntimeException(); + assertEquals(0, in.available()); } } - } diff --git a/test/jdk/java/util/zip/EntryCount64k.java b/test/jdk/java/util/zip/EntryCount64k.java index 68b86e50ece..08d896a124a 100644 --- a/test/jdk/java/util/zip/EntryCount64k.java +++ b/test/jdk/java/util/zip/EntryCount64k.java @@ -37,7 +37,6 @@ import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.RandomAccessFile; -import java.nio.file.Paths; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; @@ -161,11 +160,7 @@ static void checkCanRead(File zipFile, int entryCount) throws Throwable { } // Check java -jar - String javaHome = System.getProperty("java.home"); - String java = Paths.get(javaHome, "bin", "java").toString(); - String[] cmd = { java, "-jar", zipFile.getName() }; - ProcessBuilder pb = new ProcessBuilder(cmd); - OutputAnalyzer a = ProcessTools.executeProcess(pb); + OutputAnalyzer a = ProcessTools.executeTestJvm("-jar", zipFile.getName()); a.shouldHaveExitValue(0); a.stdoutShouldMatch("\\AMain\\Z"); a.stderrShouldMatch("\\A\\Z"); diff --git a/test/jdk/javax/accessibility/JMenu/TestJMenuScreenMagnifier.java b/test/jdk/javax/accessibility/JMenu/TestJMenuScreenMagnifier.java new file mode 100644 index 00000000000..da4a199e8c3 --- /dev/null +++ b/test/jdk/javax/accessibility/JMenu/TestJMenuScreenMagnifier.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8283404 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @requires (os.family == "mac") + * @summary Verifies if JMenu accessibility label magnifies using + * screen magnifier a11y tool. + * @run main/manual TestJMenuScreenMagnifier + */ + +import java.lang.reflect.InvocationTargetException; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.SwingUtilities; + +public class TestJMenuScreenMagnifier { + private static JFrame frame; + private static final String INSTRUCTIONS = + "1) Enable Screen magnifier on theMac \n\n" + + "System Preference -> Accessibility -> Zoom -> " + + "Select ( Enable Hover Text) \n\n" + + "2) Move the mouse over the \"File\" or \"Edit\" menu by pressing " + + "\"cmd\" button.\n\n" + + "3) If magnified label is visible, Press Pass else Fail."; + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + PassFailJFrame passFailJFrame = new PassFailJFrame( + "JMenu Screen Magnifier Test Instructions", INSTRUCTIONS, 5, 12, 40); + try { + SwingUtilities.invokeAndWait( + TestJMenuScreenMagnifier::createAndShowUI); + passFailJFrame.awaitAndCheck(); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); + } + } + private static void createAndShowUI() { + frame = new JFrame("JMenu A11Y Screen Magnifier Test"); + + JMenu file = new JMenu("File"); + file.getAccessibleContext().setAccessibleName("File Menu"); + + JMenuItem open = new JMenuItem("Open"); + open.getAccessibleContext().setAccessibleName("Open MenuItem"); + + JMenuItem quit = new JMenuItem("Quit"); + quit.getAccessibleContext().setAccessibleName("Quit MenuItem"); + + file.add(open); + file.add(quit); + + JMenu edit = new JMenu("Edit"); + edit.getAccessibleContext().setAccessibleName("Edit Menu"); + + JMenuItem cut = new JMenuItem("Cut"); + cut.getAccessibleContext().setAccessibleName("Cut MenuItem"); + + edit.add(cut); + + JMenuBar jMenuBar = new JMenuBar(); + + jMenuBar.add(file); + jMenuBar.add(edit); + + + PassFailJFrame.addTestWindow(frame); + PassFailJFrame.positionTestWindow(frame, + PassFailJFrame.Position.HORIZONTAL); + frame.setJMenuBar(jMenuBar); + frame.setSize(300, 100); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + frame.setVisible(true); + } +} diff --git a/test/jdk/javax/accessibility/JTabbedPane/AccessibleTabbedPaneTest.java b/test/jdk/javax/accessibility/JTabbedPane/AccessibleTabbedPaneTest.java new file mode 100644 index 00000000000..0b0ae01ff1b --- /dev/null +++ b/test/jdk/javax/accessibility/JTabbedPane/AccessibleTabbedPaneTest.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.accessibility.AccessibleValue; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; + +/** + * @test + * @bug 8283387 + * @summary [macos] a11y : Screen magnifier does not show selected Tab + * JTabbedPane accessible children had no AccessibleValue manipulation API + * Testing this API since it was added in the fix for 8283387 + * @run main AccessibleTabbedPaneTest + */ + +public class AccessibleTabbedPaneTest { + public static void main(String[] args) { + JTabbedPane pane = new JTabbedPane(); + JPanel p1, p2, p3; + p1 = new JPanel(); + p2 = new JPanel(); + p3 = new JPanel(); + pane.add("One", p1); + pane.add("Two", p2); + pane.add("Three", p3); + for (int i = 0; i < pane.getAccessibleContext().getAccessibleChildrenCount(); i++) { + if (pane.getAccessibleContext() + .getAccessibleChild(i) + .getAccessibleContext() + .getAccessibleValue() == null) { + throw new RuntimeException("Test failed, accessible value for tab "+ i + " is null"); + } + } + AccessibleValue p2a = pane.getAccessibleContext() + .getAccessibleChild(1) + .getAccessibleContext() + .getAccessibleValue(); + // Select second tab using a11y API. + if (p2a.setCurrentAccessibleValue(1)) { + if (pane.getSelectedIndex() != 1) { + throw new RuntimeException("Can not change tab selection using a11y API"); + } + } + + // Try to deselect it - that should not be allowed + if (p2a.setCurrentAccessibleValue(0)) { + throw new RuntimeException("We should not be able to deselect " + + "currently selected tab via a11y API"); + } + } +} diff --git a/test/jdk/javax/crypto/CryptoPermissions/InconsistentEntries.java b/test/jdk/javax/crypto/CryptoPermissions/InconsistentEntries.java new file mode 100644 index 00000000000..92843e819c6 --- /dev/null +++ b/test/jdk/javax/crypto/CryptoPermissions/InconsistentEntries.java @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8286779 + * @summary Test limited/default_local.policy containing inconsistent entries + * @library /test/lib + * @run testng/othervm InconsistentEntries + */ + +import org.testng.Assert; +import org.testng.annotations.AfterTest; +import org.testng.annotations.BeforeTest; +import org.testng.annotations.Test; + +import javax.crypto.*; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.StandardCopyOption; +import java.security.Security; + +public class InconsistentEntries { + + private static final String JDK_HOME = System.getProperty("test.jdk"); + private static final String TEST_SRC = System.getProperty("test.src"); + private static final Path POLICY_DIR = Paths.get(JDK_HOME, "conf", "security", + "policy", "testlimited"); + private static final Path POLICY_FILE = Paths.get(TEST_SRC, "default_local.policy"); + + Path targetFile = null; + + @BeforeTest + public void setUp() throws IOException { + if (!POLICY_DIR.toFile().exists()) { + Files.createDirectory(POLICY_DIR); + } + + targetFile = POLICY_DIR.resolve(POLICY_FILE.getFileName()); + Files.copy(POLICY_FILE, targetFile, StandardCopyOption.REPLACE_EXISTING); + } + + @AfterTest + public void cleanUp() throws IOException { + Files.delete(targetFile); + } + + @Test + public void test() throws Exception { + String JAVA_HOME = System.getProperty("java.home"); + String FS = System.getProperty("file.separator"); + Path testlimited = Path.of(JAVA_HOME + FS + "conf" + FS + "security" + + FS + "policy" + FS + "testlimited"); + if (!Files.exists(testlimited)) { + throw new RuntimeException( + "custom policy subdirectory: testlimited does not exist"); + } + + File testpolicy = new File(JAVA_HOME + FS + "conf" + FS + "security" + + FS + "policy" + FS + "testlimited" + FS + "default_local.policy"); + if (testpolicy.length() == 0) { + throw new RuntimeException( + "policy: default_local.policy does not exist or is empty"); + } + + Security.setProperty("crypto.policy", "testlimited"); + + Assert.assertThrows(ExceptionInInitializerError.class, + () -> Cipher.getMaxAllowedKeyLength("AES")); + } +} diff --git a/test/jdk/javax/crypto/CryptoPermissions/default_local.policy b/test/jdk/javax/crypto/CryptoPermissions/default_local.policy new file mode 100644 index 00000000000..06f5911ded0 --- /dev/null +++ b/test/jdk/javax/crypto/CryptoPermissions/default_local.policy @@ -0,0 +1,4 @@ +grant { + permission javax.crypto.CryptoAllPermission; + permission javax.crypto.CryptoPermission "DES", 64; +} diff --git a/test/jdk/javax/management/MBeanServer/ExceptionTest.java b/test/jdk/javax/management/MBeanServer/ExceptionTest.java index 3ea04f7d7ca..bb58e941242 100644 --- a/test/jdk/javax/management/MBeanServer/ExceptionTest.java +++ b/test/jdk/javax/management/MBeanServer/ExceptionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -123,10 +123,13 @@ public void run(Map args) { } finally { try { // Close JMX Connector Client - cc.close(); + if (cc != null) { + cc.close(); + } // Stop connertor server - cs.stop(); - + if (cs != null) { + cs.stop(); + } } catch (Exception e) { Utils.printThrowable(e, true); throw new RuntimeException( diff --git a/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java b/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java index e9f060248ec..0526f86b4a1 100644 --- a/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java +++ b/test/jdk/javax/management/remote/mandatory/connection/DeadLockTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -46,21 +46,23 @@ public class DeadLockTest { public static void main(String[] args) { System.out.println(">>> test on a client notification deadlock."); - boolean ok = true; + boolean fail = false; for (int i = 0; i < protocols.length; i++) { try { test(protocols[i]); } catch (Exception e) { + fail = true; // any one protocol failure, fails the test System.out.println(">>> Test failed for " + protocols[i]); e.printStackTrace(System.out); } } - + if (fail) { + throw new RuntimeException("FAILED"); + } System.out.println(">>> Test passed"); } - private static void test(String proto) - throws Exception { + private static void test(String proto) throws Exception { System.out.println(">>> Test for protocol " + proto); JMXServiceURL u = null; @@ -78,6 +80,7 @@ private static void test(String proto) server = JMXConnectorServerFactory.newJMXConnectorServer(u, env, mbs); } catch (MalformedURLException e) { System.out.println(">>> Skipping unsupported URL " + proto); + return; // skip testing this protocol } server.start(); @@ -101,10 +104,10 @@ private static void test(String proto) // which should be closed by the server. conn.getDefaultDomain(); - // allow the listner to have time to work + // allow the listener to have time to work Thread.sleep(100); - // get a closed notif, should no block. + // get a closed notif, should not block. client.close(); Thread.sleep(100); diff --git a/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java b/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java index 72ae5766307..8f8ef54eade 100644 --- a/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java +++ b/test/jdk/javax/management/remote/mandatory/notif/NotifReconnectDeadlockTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,6 +26,9 @@ * @bug 6199899 * @summary Tests reconnection done by a fetching notif thread. * @author Shanliang JIANG + * @requires vm.compMode != "Xcomp" + * @comment Running with -Xcomp is likely to cause a timeout from ServerCommunicatorAdmin + * before addNotificationListener can complete. * * @run clean NotifReconnectDeadlockTest * @run build NotifReconnectDeadlockTest diff --git a/test/jdk/javax/management/security/HashedPasswordFileTest.java b/test/jdk/javax/management/security/HashedPasswordFileTest.java index ae109b9e930..7a3f02bc7c8 100644 --- a/test/jdk/javax/management/security/HashedPasswordFileTest.java +++ b/test/jdk/javax/management/security/HashedPasswordFileTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -200,6 +200,12 @@ private JMXServiceURL createServerSide(boolean useHash) return cs.getAddress(); } + private void stopServerSide() throws IOException { + if (cs != null) { + cs.stop(); + } + } + @Test public void testClearTextPasswordFile() throws IOException { Boolean[] bvals = new Boolean[]{true, false}; @@ -217,7 +223,7 @@ public void testClearTextPasswordFile() throws IOException { } Assert.assertEquals(isPasswordFileHashed(), bval); } finally { - cs.stop(); + stopServerSide(); } } } @@ -241,7 +247,7 @@ public void testReadOnlyPasswordFile() throws IOException { } Assert.assertEquals(isPasswordFileHashed(), false); } finally { - cs.stop(); + stopServerSide(); } } } @@ -263,7 +269,7 @@ public void testHashedPasswordFile() throws IOException { } } } finally { - cs.stop(); + stopServerSide(); } } } @@ -400,7 +406,7 @@ public void testPasswordChange() throws IOException { } } } finally { - cs.stop(); + stopServerSide(); } } diff --git a/test/jdk/javax/net/ssl/DTLS/TEST.properties b/test/jdk/javax/net/ssl/DTLS/TEST.properties index ceb6c8c9c42..a50cba09c0f 100644 --- a/test/jdk/javax/net/ssl/DTLS/TEST.properties +++ b/test/jdk/javax/net/ssl/DTLS/TEST.properties @@ -6,3 +6,4 @@ modules = \ java.security.jgss/sun.security.krb5.internal:+open \ java.security.jgss/sun.security.krb5.internal.ktab \ java.base/sun.security.util +maxOutputSize = 2500000 diff --git a/test/jdk/javax/swing/AbstractButton/bug4290656.java b/test/jdk/javax/swing/AbstractButton/bug4290656.java new file mode 100644 index 00000000000..82e36f0aad8 --- /dev/null +++ b/test/jdk/javax/swing/AbstractButton/bug4290656.java @@ -0,0 +1,116 @@ +/* + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4290656 + * @summary Tests if custom AbstractButton implementation fails with Metal L&F + * @key headful + */ + +import java.awt.BorderLayout; +import java.awt.Graphics; +import java.awt.Robot; +import javax.swing.AbstractButton; +import javax.swing.DefaultButtonModel; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.plaf.ButtonUI; + +public class bug4290656 { + static JFrame f; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4290656"); + try { + UIManager.setLookAndFeel(new javax.swing.plaf.metal.MetalLookAndFeel()); + } catch (Exception e) { + throw new RuntimeException("Failed to set metal L&F."); + } + + MyCustomButton button = new MyCustomButton(); + MyCustomToggleButton toggleButton = new MyCustomToggleButton(); + f.getContentPane().add(button, BorderLayout.NORTH); + f.getContentPane().add(toggleButton, BorderLayout.SOUTH); + + f.setLocationRelativeTo(null); + f.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + } +} + +class MyCustomButton extends AbstractButton { + private static final String uiClassID = "ButtonUI"; + + public MyCustomButton() { + setModel(new DefaultButtonModel()); + init(null, null); + } + + public void updateUI() { + setUI((ButtonUI) UIManager.getUI(this)); + } + + public String getUIClassID() { + return uiClassID; + } + + protected void paintBorder(Graphics g) { + super.paintBorder(g); + } +} + +class MyCustomToggleButton extends AbstractButton { + private static final String uiClassID = "ToggleButtonUI"; + + public MyCustomToggleButton() { + setModel(new DefaultButtonModel()); + init(null, null); + } + + public void updateUI() { + setUI((ButtonUI) UIManager.getUI(this)); + } + + public String getUIClassID() { + return uiClassID; + } + + protected void paintBorder(Graphics g) { + super.paintBorder(g); + } +} diff --git a/test/jdk/javax/swing/AbstractDocument/bug4549069.java b/test/jdk/javax/swing/AbstractDocument/bug4549069.java new file mode 100644 index 00000000000..472830399ee --- /dev/null +++ b/test/jdk/javax/swing/AbstractDocument/bug4549069.java @@ -0,0 +1,124 @@ +/* + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4549069 + * @summary Tests if javax.swing.text.AbstractDocument.BranchElement.getEndOffset() throws AIOOBE + * @key headful + */ + +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.Timer; +import java.util.TimerTask; +import javax.swing.JFrame; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.undo.UndoManager; + +public class bug4549069 { + static Timer timer; + static volatile Point p; + + static JFrame f; + static JTextArea jta; + static UndoManager um; + static Robot robot; + + public static void main(String[] argv) throws Exception { + robot = new Robot(); + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4549069"); + f.addWindowListener(new TestStateListener()); + + jta = new JTextArea(); + um = new UndoManager(); + jta.setDocument(new DefaultStyledDocument()); + jta.getDocument().addUndoableEditListener(um); + + String text = "Press Ctrl-Z (undo) to get\n" + + "a stacktrace U shouldn't XX\n"; + jta.setText(text); + + jta.addKeyListener(new KeyAdapter() { + public void keyPressed(KeyEvent e) { + if (um.canUndo()) { + um.undo(); + } + } + }); + + f.getContentPane().add(jta); + f.pack(); + f.setVisible(true); + }); + + robot.waitForIdle(); + robot.delay(1000); + } finally { + if (f != null) { + SwingUtilities.invokeAndWait(() -> { + f.dispose(); + }); + } + } + } + + static class TestStateListener extends WindowAdapter { + public void windowOpened(WindowEvent ev) { + timer = new Timer(); + timer.schedule(new RobotTask(), 1000); + } + } + + static class RobotTask extends TimerTask { + public void run() { + try { + SwingUtilities.invokeAndWait(() -> { + p = jta.getLocationOnScreen(); + }); + } catch (Exception e) { + throw new RuntimeException("Could not get location"); + + } + robot.mouseMove(p.x, p.y); + robot.waitForIdle(); + + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + + robot.keyPress(KeyEvent.VK_SPACE); + robot.keyRelease(KeyEvent.VK_SPACE); + robot.waitForIdle(); + } + } +} diff --git a/test/jdk/javax/swing/AbstractWriter/bug4185537.java b/test/jdk/javax/swing/AbstractWriter/bug4185537.java new file mode 100644 index 00000000000..3425f12a83a --- /dev/null +++ b/test/jdk/javax/swing/AbstractWriter/bug4185537.java @@ -0,0 +1,140 @@ +/* + * Copyright (c) 1998, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4185537 + * @summary javax.swing.text.AbstractWriter: TOTAL REWRITE COMPLETE. + */ + +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import javax.swing.text.AbstractWriter; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.Document; + +public class bug4185537 { + static char[] chars = {'a', 'b', 'c', 'd', 'e'}; + static StringWriter wr = new StringWriter(); + + public static void main(String[] argv) { + DefaultStyledDocument doc = new DefaultStyledDocument(); + + SimpleWriter sw = new SimpleWriter(wr, doc, 5, 200); + sw.test_getWriter(); + + if (sw.getStartOffset() != 5) { + throw new RuntimeException("getStartOffset fails..."); + } + if (sw.getEndOffset() != 205) { + throw new RuntimeException("getEndOffset fails..."); + } + + sw.setLineSeparator("+"); + if (!sw.getLineSeparator().equals("+")) { + throw new RuntimeException("Doesn't set line separator correctly..."); + } + sw.test_writeLineSeparator(); + + sw.test_write_output(); + sw.test_CurrentLineLength(); + sw.test_getLineLength(); + sw.test_getIndentLevel(); + sw.test_CanWrapLines(); + if (!wr.toString().equals("+abcde")) { + throw new RuntimeException("Test fails..."); + } + try { + wr.close(); + } catch (Exception e) { + System.out.println("Exception..."); + } + } + + static class SimpleWriter extends AbstractWriter { + + public SimpleWriter(Writer w, Document d, int pos, int len) { + super(w, d, pos, len); + } + + void test_writeLineSeparator() { + try { + writeLineSeparator(); + } catch (IOException e) { + e.printStackTrace(); + throw new RuntimeException("writeLineSeparator fails..."); + } + } + + void test_getWriter() { + if (getWriter() != wr) throw new RuntimeException("Writer gets incorrect..."); + } + + void test_CurrentLineLength() { + setCurrentLineLength(0); + if (getCurrentLineLength() != 0) throw new RuntimeException("Doesn't set CurrentLineLength..."); + if (!isLineEmpty()) { + throw new RuntimeException("isLineEmpty() should return false..."); + } + } + + void test_getLineLength() { + setLineLength(80); + if (getLineLength() != 80) { + throw new RuntimeException("Default line length doesn't set..."); + } + } + + void test_CanWrapLines() { + setCanWrapLines(true); + if (!getCanWrapLines()) { + throw new RuntimeException("Doesn't set wrapping lines correctly"); + } + } + + void test_getIndentLevel() { + incrIndent(); + if (getIndentLevel() != 1) { + throw new RuntimeException("getIndentLevel() fails..."); + } + } + + void test_write_output() { + try { + write(chars, 0, 3); + } catch (IOException e) { + throw new RuntimeException("write(char[], int, int): unexpected IOException..."); + } + try { + output(chars, 3, 2); + } catch (IOException e) { + throw new RuntimeException("output(char[], int, int): unexpected IOException..."); + } + } + + public void write() throws IOException, BadLocationException { + } + } +} diff --git a/test/jdk/javax/swing/BasicMenuItemUI/bug4239714.java b/test/jdk/javax/swing/BasicMenuItemUI/bug4239714.java new file mode 100644 index 00000000000..f3d61f01d01 --- /dev/null +++ b/test/jdk/javax/swing/BasicMenuItemUI/bug4239714.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4239714 + * @summary Tests that BasicMenuItemUI.installComponent() is protected + */ + +import javax.swing.JMenuItem; +import javax.swing.plaf.basic.BasicMenuItemUI; + +public class bug4239714 { + public static void main(String[] argv) throws Exception { + Tester tester = new Tester(); + tester.test(); + } + + static class Tester extends BasicMenuItemUI { + public void test() { + JMenuItem mi = new JMenuItem("bug4239714"); + installComponents(mi); + } + } +} diff --git a/test/jdk/javax/swing/BasicMenuUI/bug4244616.java b/test/jdk/javax/swing/BasicMenuUI/bug4244616.java new file mode 100644 index 00000000000..f595ae319d9 --- /dev/null +++ b/test/jdk/javax/swing/BasicMenuUI/bug4244616.java @@ -0,0 +1,77 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4244616 + * @summary Tests that debug output in BasicMenuUI private inner classes + * is commented out + */ + +import java.awt.event.ActionEvent; +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import javax.swing.Action; +import javax.swing.ActionMap; +import javax.swing.JMenu; +import javax.swing.plaf.basic.BasicMenuUI; + +public class bug4244616 { + public static void main(String[] argv) throws Exception { + JMenu menu = new JMenu(); + BasicMenuUI ui = new BasicMenuUI(); + ui.installUI(menu); + ActionMap amap = menu.getActionMap(); + + String[] names = {"selectMenu", "cancel", + "selectNext", "selectPrevious"}; + ActionEvent ev = new ActionEvent(menu, + ActionEvent.ACTION_PERFORMED, "test event"); + + // Stream redirection + final PrintStream oldOut = System.out; + final PrintStream oldErr = System.err; + try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); + ByteArrayOutputStream berr = new ByteArrayOutputStream(); + PrintStream out = new PrintStream(bout); + PrintStream err = new PrintStream(berr)) { + for (int i = 0; i < names.length; i++) { + Action action = amap.get(names[i]); + try { + action.actionPerformed(ev); + } catch (Exception ignored) { + } + } + + if (bout.size() != 0 || berr.size() != 0) { + System.out.println("bout: " + bout); + System.out.println("berr: " + berr); + throw new RuntimeException("Failed: some debug output occurred"); + } + } finally { + // Restore streams + System.setOut(oldOut); + System.setErr(oldErr); + } + } +} diff --git a/test/jdk/javax/swing/DefaultTableCellRenderer/bug4240870.java b/test/jdk/javax/swing/DefaultTableCellRenderer/bug4240870.java new file mode 100644 index 00000000000..7b032e65940 --- /dev/null +++ b/test/jdk/javax/swing/DefaultTableCellRenderer/bug4240870.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4240870 4240855 + * @summary Tests that DefaultTableCellRenderer overrides following methods: + * validate() + * revalidate() + * repaint(long, int, int, int, int) + * repaint(Rectangle) + * firePropertyChange(String, Object, Object) + * firePropertyChange(String, boolean, boolean) + */ + +import java.beans.PropertyChangeEvent; +import java.beans.PropertyChangeListener; +import javax.swing.table.DefaultTableCellRenderer; + +public class bug4240870 { + public static void main(String[] argv) { + // Test overridden public methods using reflection + String methodName = null; + try { + Class clazz = Class.forName( + "javax.swing.table.DefaultTableCellRenderer"); + Class[] noArgs = {}; + methodName = "validate"; + clazz.getDeclaredMethod(methodName, noArgs); + methodName = "revalidate"; + clazz.getDeclaredMethod(methodName, noArgs); + + Class[] args1 = {long.class, int.class, int.class, + int.class, int.class}; + methodName = "repaint"; + clazz.getDeclaredMethod(methodName, args1); + Class[] args2 = {Class.forName("java.awt.Rectangle")}; + methodName = "repaint"; + clazz.getDeclaredMethod(methodName, args2); + + Class objectClass = Class.forName("java.lang.Object"); + Class stringClass = Class.forName("java.lang.String"); + Class[] args3 = {stringClass, objectClass, objectClass}; + methodName = "firePropertyChange"; + clazz.getDeclaredMethod(methodName, args3); + Class[] args4 = {stringClass, boolean.class, boolean.class}; + clazz.getDeclaredMethod(methodName, args4); + } catch (NoSuchMethodException e) { + throw new RuntimeException("Failed: " + methodName + " not overridden"); + } catch (ClassNotFoundException e) { + } + + // test protected firePropertyChange(String, Object, Object) + Renderer r = new Renderer(); + r.addPropertyChangeListener(new Listener()); + r.test(); + } + + static class Renderer extends DefaultTableCellRenderer { + public void test() { + super.firePropertyChange("text", "old_text", "new_text"); + super.firePropertyChange("stuff", "old_stuff", "new_stuff"); + } + } + + static class Listener implements PropertyChangeListener { + public void propertyChange(PropertyChangeEvent e) { + if (!e.getPropertyName().equals("text")) { + throw new RuntimeException("Failed: firePropertyChange not overridden"); + } + } + } +} diff --git a/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java b/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java deleted file mode 100644 index 8f3da452c21..00000000000 --- a/test/jdk/javax/swing/JButton/PressedButtonRightClickTest.java +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright (c) 2016, 2024, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - - -import java.awt.AWTException; -import java.awt.BorderLayout; -import java.awt.EventQueue; -import java.awt.Point; -import java.awt.Robot; -import java.awt.event.InputEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import javax.swing.JButton; -import javax.swing.JFrame; -import javax.swing.SwingUtilities; - -/* - * @test - * @key headful - * @bug 8049069 - * @summary Tests whether right mouse click releases a pressed JButton - */ - -public class PressedButtonRightClickTest { - - private static Robot testRobot; - private static JFrame myFrame; - private static JButton myButton; - - public static void main(String[] args) throws Throwable { - - SwingUtilities.invokeAndWait(PressedButtonRightClickTest::constructTestUI); - - try { - testRobot = new Robot(); - } catch (AWTException ex) { - throw new RuntimeException("Exception in Robot creation"); - } - - testRobot.waitForIdle(); - testRobot.delay(500); - - // Method performing auto test operation - try { - test(); - } finally { - EventQueue.invokeAndWait(PressedButtonRightClickTest::disposeTestUI); - } - } - - private static void test() { - Point loc = myFrame.getLocationOnScreen(); - - testRobot.mouseMove((loc.x + 100), (loc.y + 100)); - - // Press the left mouse button - System.out.println("press BUTTON1_DOWN_MASK"); - testRobot.mousePress(InputEvent.BUTTON1_DOWN_MASK); - myButton.setText("Left button pressed"); - testRobot.delay(500); - - // Press the right mouse button - System.out.println("press BUTTON3_DOWN_MASK"); - testRobot.mousePress(InputEvent.BUTTON3_DOWN_MASK); - myButton.setText("Left button pressed + Right button pressed"); - testRobot.delay(500); - - // Release the right mouse button - System.out.println("release BUTTON3_DOWN_MASK"); - testRobot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); - myButton.setText("Right button released"); - testRobot.waitForIdle(); - testRobot.delay(500); - - // Test whether the button is still pressed - boolean pressed = myButton.getModel().isPressed(); - System.out.println("release BUTTON1_DOWN_MASK"); - testRobot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - if (!pressed) { - disposeTestUI(); - throw new RuntimeException("Test Failed!"); - } - } - - private static void disposeTestUI() { - myFrame.setVisible(false); - myFrame.dispose(); - } - - public static void constructTestUI() { - myFrame = new JFrame(); - myFrame.setLayout(new BorderLayout()); - myButton = new JButton("Whatever"); - myButton.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent e) { - System.out.println(e); - } - - @Override - public void mousePressed(MouseEvent e) { - System.out.println(e); - } - - @Override - public void mouseReleased(MouseEvent e) { - System.out.println(e); - } - - @Override - public void mouseEntered(MouseEvent e) { - System.out.println(e); - } - - @Override - public void mouseExited(MouseEvent e) { - System.out.println(e); - } - }); - myFrame.add(myButton, BorderLayout.CENTER); - myFrame.setSize(400, 300); - myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - myFrame.setLocationRelativeTo(null); - myFrame.setVisible(true); - } -} - diff --git a/test/jdk/javax/swing/JButton/bug4323121.java b/test/jdk/javax/swing/JButton/bug4323121.java index 0b352ce57eb..f23cfe43f6a 100644 --- a/test/jdk/javax/swing/JButton/bug4323121.java +++ b/test/jdk/javax/swing/JButton/bug4323121.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,59 +24,81 @@ /* * @test * @bug 4323121 - * @summary Tests whether any button that extends JButton always - returns true for isArmed() + * @summary Tests whether a button model always returns true for isArmed() + * when mouse hovers over the button * @key headful * @run main bug4323121 */ -import java.awt.Graphics; import java.awt.Point; import java.awt.Robot; +import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; -import java.awt.event.MouseListener; -import java.awt.event.MouseMotionListener; +import java.util.concurrent.CountDownLatch; + import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; -public class bug4323121 { +import static java.util.concurrent.TimeUnit.SECONDS; + +public final class bug4323121 { static JFrame frame; - static testButton button; - static volatile Point pt; - static volatile int buttonW; - static volatile int buttonH; - static volatile boolean failed = false; + static JButton button; + + static volatile Point buttonCenter; + + private static final CountDownLatch mouseEntered = new CountDownLatch(1); + + // Usage of this flag is thread-safe because of using the mouseEntered latch + private static boolean modelArmed; public static void main(String[] args) throws Exception { Robot robot = new Robot(); robot.setAutoDelay(100); + try { SwingUtilities.invokeAndWait(() -> { + button = new JButton("gotcha"); + button.addMouseListener(new MouseAdapter() { + @Override + public void mouseEntered(MouseEvent e) { + if (button.getModel().isArmed()) { + modelArmed = true; + } + mouseEntered.countDown(); + } + }); + frame = new JFrame("bug4323121"); - button = new testButton("gotcha"); frame.getContentPane().add(button); + frame.pack(); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); + robot.waitForIdle(); - robot.delay(1000); + SwingUtilities.invokeAndWait(() -> { - pt = button.getLocationOnScreen(); - buttonW = button.getSize().width; - buttonH = button.getSize().height; + Point location = button.getLocationOnScreen(); + buttonCenter = new Point(location.x + button.getWidth() / 2, + location.y + button.getHeight() / 2); }); - robot.mouseMove(pt.x + buttonW / 2, pt.y + buttonH / 2); - robot.waitForIdle(); - if (failed) { - throw new RuntimeException("Any created button returns " + - "true for isArmed()"); + + robot.mouseMove(buttonCenter.x, buttonCenter.y); + + if (!mouseEntered.await(1, SECONDS)) { + throw new RuntimeException("Mouse entered event wasn't received"); + } + if (modelArmed) { + throw new RuntimeException("getModel().isArmed() returns true " + + "when mouse hovers over the button"); } } finally { - SwingUtilities.invokeAndWait(() -> { + SwingUtilities.invokeAndWait(() -> { if (frame != null) { frame.dispose(); } @@ -84,42 +106,4 @@ public static void main(String[] args) throws Exception { } } - static class testButton extends JButton implements MouseMotionListener, MouseListener { - public testButton(String label) { - super(label); - addMouseMotionListener(this); - addMouseListener(this); - } - - protected void paintComponent(Graphics g) { - super.paintComponent(g); - } - - protected void paintBorder(Graphics g) { - } - - public void mousePressed(MouseEvent e) { - } - - public void mouseDragged(MouseEvent e) { - } - - public void mouseMoved(MouseEvent e) { - } - - public void mouseReleased(MouseEvent e) { - } - - public void mouseEntered(MouseEvent e) { - if (getModel().isArmed()) { - failed = true; - } - } - - public void mouseExited(MouseEvent e) { - } - - public void mouseClicked(MouseEvent e) { - } - } } diff --git a/test/jdk/javax/swing/JButton/bug4490179.java b/test/jdk/javax/swing/JButton/bug4490179.java index 079c7a026f8..bf2df9e7bcc 100644 --- a/test/jdk/javax/swing/JButton/bug4490179.java +++ b/test/jdk/javax/swing/JButton/bug4490179.java @@ -23,7 +23,7 @@ /* * @test - * @bug 4490179 + * @bug 4490179 8049069 * @summary Tests that JButton only responds to left mouse clicks. * @key headful * @run main bug4490179 @@ -31,61 +31,107 @@ import java.awt.Point; import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; import java.awt.event.InputEvent; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.concurrent.CountDownLatch; + import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.SwingUtilities; -public class bug4490179 { +import static java.util.concurrent.TimeUnit.MILLISECONDS; +import static java.util.concurrent.TimeUnit.SECONDS; + +public final class bug4490179 + extends MouseAdapter + implements ActionListener { static JFrame frame; static JButton button; - static volatile Point pt; - static volatile int buttonW; - static volatile int buttonH; - static volatile boolean passed = true; + + private static volatile Point buttonCenter; + + private static final CountDownLatch windowGainedFocus = new CountDownLatch(1); + + private static final CountDownLatch mouseButton1Released = new CountDownLatch(1); + private static final CountDownLatch mouseButton3Released = new CountDownLatch(2); + + private static final CountDownLatch actionPerformed = new CountDownLatch(1); public static void main(String[] args) throws Exception { Robot robot = new Robot(); robot.setAutoDelay(100); - robot.setAutoWaitForIdle(true); + + final bug4490179 eventHandler = new bug4490179(); try { SwingUtilities.invokeAndWait(() -> { - frame = new JFrame("bug4490179"); button = new JButton("Button"); + button.addActionListener(eventHandler); + button.addMouseListener(eventHandler); + + frame = new JFrame("bug4490179"); frame.getContentPane().add(button); - button.addActionListener(e -> { - if ((e.getModifiers() & InputEvent.BUTTON1_MASK) - != InputEvent.BUTTON1_MASK) { - System.out.println("Status: Failed"); - passed = false; + + frame.addWindowFocusListener(new WindowAdapter() { + @Override + public void windowGainedFocus(WindowEvent e) { + windowGainedFocus.countDown(); } }); + frame.pack(); frame.setLocationRelativeTo(null); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); }); + + if (!windowGainedFocus.await(1, SECONDS)) { + throw new RuntimeException("Window didn't gain focus"); + } robot.waitForIdle(); - robot.delay(1000); + SwingUtilities.invokeAndWait(() -> { - pt = button.getLocationOnScreen(); - buttonW = button.getSize().width; - buttonH = button.getSize().height; + Point location = button.getLocationOnScreen(); + buttonCenter = new Point(location.x + button.getWidth() / 2, + location.y + button.getHeight() / 2); }); - robot.mouseMove(pt.x + buttonW / 2, pt.y + buttonH / 2); - robot.waitForIdle(); + robot.mouseMove(buttonCenter.x, buttonCenter.y); + System.out.println("Press / Release button 3"); robot.mousePress(InputEvent.BUTTON3_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); + System.out.println("Press button 1"); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + System.out.println("Press button 3"); robot.mousePress(InputEvent.BUTTON3_DOWN_MASK); + System.out.println("Release button 3"); robot.mouseRelease(InputEvent.BUTTON3_DOWN_MASK); - robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - robot.delay(500); - if (!passed) { - throw new RuntimeException("Test Failed"); + try { + if (!mouseButton3Released.await(1, SECONDS)) { + throw new RuntimeException("Mouse button 3 isn't released"); + } + + robot.waitForIdle(); + + if (actionPerformed.await(100, MILLISECONDS)) { + throw new RuntimeException("Action event triggered by releasing button 3"); + } + } finally { + System.out.println("Release button 1"); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + } + + if (!mouseButton1Released.await(1, SECONDS)) { + throw new RuntimeException("Mouse button 1 isn't released"); + } + if (!actionPerformed.await(100, MILLISECONDS)) { + throw new RuntimeException("Action event isn't triggered by releasing button 1"); } } finally { SwingUtilities.invokeAndWait(() -> { @@ -95,4 +141,21 @@ public static void main(String[] args) throws Exception { }); } } + + @Override + public void actionPerformed(ActionEvent e) { + System.out.println(" actionPerformed"); + actionPerformed.countDown(); + } + + @Override + public void mouseReleased(MouseEvent e) { + if (e.getButton() == MouseEvent.BUTTON1) { + System.out.println(" mouseReleased: button 1"); + mouseButton1Released.countDown(); + } else if (e.getButton() == MouseEvent.BUTTON3) { + System.out.println(" mouseReleased: button 3"); + mouseButton3Released.countDown(); + } + } } diff --git a/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.html b/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.html deleted file mode 100644 index 33cc90e77cf..00000000000 --- a/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.html +++ /dev/null @@ -1,36 +0,0 @@ - - - - - -Verify that scaled components are rendered smoothly to image. - -1. Run the test. -2. Check that Selected and Deselected JCheckBox icons are drawn smoothly. -If so, press PASS, else press FAIL. - - - - - diff --git a/test/jdk/javax/swing/JCheckBox/8032667/bug8032667_image_diff.java b/test/jdk/javax/swing/JCheckBox/8032667/bug8032667_image_diff.java deleted file mode 100644 index 827b0fe1e63..00000000000 --- a/test/jdk/javax/swing/JCheckBox/8032667/bug8032667_image_diff.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Copyright (c) 2014, 2018, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Image; -import java.awt.image.BufferedImage; -import javax.swing.JCheckBox; -import javax.swing.JComponent; -import javax.swing.SwingUtilities; - -import jdk.test.lib.Platform; - -/* @test - * @bug 8032667 - * @summary [macosx] Components cannot be rendered in HiDPI to BufferedImage - * @library /test/lib - * @build jdk.test.lib.Platform - * @run main bug8032667_image_diff - */ -public class bug8032667_image_diff { - - static final int IMAGE_WIDTH = 130; - static final int IMAGE_HEIGHT = 50; - - public static void main(String[] args) throws Exception { - - if (!Platform.isOSX()) { - return; - } - - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - - JCheckBox checkBox = new JCheckBox(); - checkBox.setSelected(true); - checkBox.setSize(new Dimension(IMAGE_WIDTH, IMAGE_HEIGHT)); - - final BufferedImage image1 = getHiDPIImage(checkBox); - final BufferedImage image2 = getScaledImage(checkBox); - - if(equal(image1, image2)){ - throw new RuntimeException("2x image equals to non smooth image"); - } - } - }); - } - - static boolean equal(BufferedImage image1, BufferedImage image2) { - - int w = image1.getWidth(); - int h = image1.getHeight(); - - if (w != image2.getWidth() || h != image2.getHeight()) { - return false; - } - - for (int i = 0; i < w; i++) { - for (int j = 0; j < h; j++) { - int color1 = image1.getRGB(i, j); - int color2 = image2.getRGB(i, j); - - if (color1 != color2) { - return false; - } - } - } - return true; - } - - static BufferedImage getHiDPIImage(JComponent component) { - return getImage(component, 2, IMAGE_WIDTH, IMAGE_HEIGHT); - } - - static BufferedImage getScaledImage(JComponent component) { - Image image1x = getImage(component, 1, IMAGE_WIDTH, IMAGE_HEIGHT); - final BufferedImage image2x = new BufferedImage( - 2 * IMAGE_WIDTH, 2 * IMAGE_HEIGHT, BufferedImage.TYPE_INT_ARGB); - final Graphics g = image2x.getGraphics(); - ((Graphics2D) g).scale(2, 2); - g.drawImage(image1x, 0, 0, null); - g.dispose(); - return image2x; - } - - static BufferedImage getImage(JComponent component, int scale, int width, int height) { - final BufferedImage image = new BufferedImage( - scale * width, scale * height, BufferedImage.TYPE_INT_ARGB); - final Graphics g = image.getGraphics(); - ((Graphics2D) g).scale(scale, scale); - component.paint(g); - g.dispose(); - return image; - } -} diff --git a/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.java b/test/jdk/javax/swing/JCheckBox/bug8032667.java similarity index 56% rename from test/jdk/javax/swing/JCheckBox/8032667/bug8032667.java rename to test/jdk/javax/swing/JCheckBox/bug8032667.java index fda8852e520..3fa1a90b41f 100644 --- a/test/jdk/javax/swing/JCheckBox/8032667/bug8032667.java +++ b/test/jdk/javax/swing/JCheckBox/bug8032667.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,24 +20,28 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ + import java.awt.BorderLayout; -import java.awt.Canvas; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.image.BufferedImage; -import javax.swing.JApplet; + import javax.swing.JCheckBox; import javax.swing.JComponent; -import javax.swing.SwingUtilities; +import javax.swing.JFrame; +import javax.swing.JPanel; /* @test * @bug 8032667 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary [macosx] Components cannot be rendered in HiDPI to BufferedImage - * @run applet/manual=yesno bug8032667.html + * @run main/manual bug8032667 */ -public class bug8032667 extends JApplet { + +public class bug8032667 { static final int scale = 2; static final int width = 130; @@ -45,30 +49,43 @@ public class bug8032667 extends JApplet { static final int scaledWidth = scale * width; static final int scaledHeight = scale * height; - @Override - public void init() { - SwingUtilities.invokeLater(new Runnable() { + private static final String INSTRUCTIONS = """ + Verify that scaled components are rendered smoothly to image. - @Override - public void run() { + 1. Run the test. + 2. Check that Selected and Deselected JCheckBox icons are drawn smoothly. + If so, press PASS, else press FAIL. + """; - final Image image1 = getImage(getCheckBox("Deselected", false)); - final Image image2 = getImage(getCheckBox("Selected", true)); - - Canvas canvas = new Canvas() { + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug8032667 Test Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .testUI(bug8032667::createAndShowGUI) + .build() + .awaitAndCheck(); + } - @Override - public void paint(Graphics g) { - super.paint(g); - g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this); - g.drawImage(image2, 0, scaledHeight + 5, - scaledWidth, scaledHeight, this); - } - }; + public static JFrame createAndShowGUI() { + JFrame frame = new JFrame("bug8032667 HiDPI Component Test"); + frame.setLayout(new BorderLayout()); + frame.setBounds(0, 400, 400, 400); - getContentPane().add(canvas, BorderLayout.CENTER); + final Image image1 = getImage(getCheckBox("Deselected", false)); + final Image image2 = getImage(getCheckBox("Selected", true)); + JPanel panel = new JPanel() { + @Override + public void paint(Graphics g) { + super.paint(g); + g.drawImage(image1, 0, 0, scaledWidth, scaledHeight, this); + g.drawImage(image2, 0, scaledHeight + 5, + scaledWidth, scaledHeight, this); } - }); + }; + frame.add(panel, BorderLayout.CENTER); + return frame; } static JCheckBox getCheckBox(String text, boolean selected) { diff --git a/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java b/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java index fdd66248c18..96756394b4f 100644 --- a/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java +++ b/test/jdk/javax/swing/JColorChooser/8065098/JColorChooserDnDTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -34,21 +34,17 @@ public class JColorChooserDnDTest { public static void main(String[] args) { - SwingUtilities.invokeLater(new Runnable() { - - @Override - public void run() { - JFrame frame = new JFrame(); - frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); - JPanel panel = new JPanel(); - JColorChooser colorChooser = new JColorChooser(); - colorChooser.setDragEnabled(true); - panel.setBorder(BorderFactory.createTitledBorder("JColorChoosers")); - panel.add(colorChooser); - frame.setContentPane(panel); - frame.pack(); - frame.setVisible(true); - } + SwingUtilities.invokeLater(() -> { + JFrame frame = new JFrame(); + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JPanel panel = new JPanel(); + JColorChooser colorChooser = new JColorChooser(); + colorChooser.setDragEnabled(true); + panel.setBorder(BorderFactory.createTitledBorder("JColorChoosers")); + panel.add(colorChooser); + frame.setContentPane(panel); + frame.pack(); + frame.setVisible(true); }); } } diff --git a/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.html b/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.html deleted file mode 100644 index 3fc612cccf2..00000000000 --- a/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.html +++ /dev/null @@ -1,40 +0,0 @@ - - - - - 1. Compile the java test JColorChooserDnDTest.java: - > /bin/javac JColorChooserDnDTest.java - 2. Run the first instance of the java test: - > /bin/java JColorChooserDnDTest - 3. Select a color in the color chooser - 4. Run the second instance of the java test: - > /bin/java JColorChooserDnDTest - 5. Drag and drop the selected color from the first color chooser - preview panel to the second color chooser preview panel - 6. If the color is dragged to the second color chooser then the test passes. - - - - - diff --git a/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java b/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java index 0fadffc4247..0402607644e 100644 --- a/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java +++ b/test/jdk/javax/swing/JColorChooser/8065098/bug8065098.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,15 +20,39 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -import javax.swing.JApplet; /* * @test * @bug 8065098 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary JColorChooser no longer supports drag and drop * between two JVM instances - * @run applet/manual=yesno bug8065098.html + * @run main/manual bug8065098 */ -public class bug8065098 extends JApplet { +public class bug8065098 { + private static final String INSTRUCTIONS = """ + 1. Compile the java test JColorChooserDnDTest.java: + > /bin/javac JColorChooserDnDTest.java + 2. Run the first instance of the java test: + > /bin/java JColorChooserDnDTest + 3. Select a color in the color chooser. + 4. Run the second instance of the java test: + > /bin/java JColorChooserDnDTest + 5. Drag and drop the selected color from the first color chooser + preview panel to the second color chooser preview panel + 6. If the color is dragged to the second color chooser, then the + test passes. Otherwise, the test fails. + """; + + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("bug8065098 Test Instructions") + .instructions(INSTRUCTIONS) + .rows((int) INSTRUCTIONS.lines().count() + 2) + .columns(40) + .build() + .awaitAndCheck(); + } } diff --git a/test/jdk/javax/swing/JColorChooser/Test4222508.html b/test/jdk/javax/swing/JColorChooser/Test4222508.html deleted file mode 100644 index 0fcf430ca4c..00000000000 --- a/test/jdk/javax/swing/JColorChooser/Test4222508.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - -Use the check box above the color chooser to disable it. -You could not choose a color using by the disable color chooser. - - - - - diff --git a/test/jdk/javax/swing/JColorChooser/Test4222508.java b/test/jdk/javax/swing/JColorChooser/Test4222508.java index 156e58e6ceb..fbe5c848a63 100644 --- a/test/jdk/javax/swing/JColorChooser/Test4222508.java +++ b/test/jdk/javax/swing/JColorChooser/Test4222508.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,36 +21,50 @@ * questions. */ +import java.awt.BorderLayout; +import javax.swing.JCheckBox; +import javax.swing.JColorChooser; +import javax.swing.JFrame; + /* * @test * @bug 4222508 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary Tests the color chooser disabling - * @author Sergey Malenkov - * @run applet/manual=yesno Test4222508.html + * @run main/manual Test4222508 */ +public final class Test4222508 { -import java.awt.BorderLayout; -import java.awt.event.ItemEvent; -import java.awt.event.ItemListener; -import javax.swing.JApplet; -import javax.swing.JCheckBox; -import javax.swing.JColorChooser; + public static void main(String[] args) throws Exception { + String instructions = "Click on colors in the JColorChooser.\n" + + "Then uncheck the checkbox and click on colors again.\n" + + "If the JColorChooser is disabled when the checkbox is unchecked, " + + "then pass the test."; -public final class Test4222508 extends JApplet implements ItemListener { + PassFailJFrame.builder() + .title("Test4222508") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(10) + .testUI(Test4222508::test) + .build() + .awaitAndCheck(); + } - private JCheckBox checkbox; - private JColorChooser chooser; + public static JFrame test() { + JFrame frame = new JFrame("JColorChooser with enable/disable checkbox"); + frame.setLayout(new BorderLayout()); + JColorChooser chooser = new JColorChooser(); + JCheckBox checkbox = new JCheckBox("Enable the color chooser below", true); + checkbox.addItemListener(e -> chooser.setEnabled(checkbox.isSelected())); - @Override - public void init() { - this.chooser = new JColorChooser(); - this.checkbox = new JCheckBox("Enable the color chooser below", true); - this.checkbox.addItemListener(this); - add(BorderLayout.NORTH, this.checkbox); - add(BorderLayout.CENTER, this.chooser); - } + frame.add(chooser, BorderLayout.SOUTH); + frame.add(checkbox, BorderLayout.NORTH); + frame.pack(); - public void itemStateChanged(ItemEvent event) { - this.chooser.setEnabled(this.checkbox.isSelected()); + return frame; } + } diff --git a/test/jdk/javax/swing/JColorChooser/Test4319113.html b/test/jdk/javax/swing/JColorChooser/Test4319113.html deleted file mode 100644 index b0b0ee281fe..00000000000 --- a/test/jdk/javax/swing/JColorChooser/Test4319113.html +++ /dev/null @@ -1,39 +0,0 @@ - - - - -1. Press button "Show ColorChooser" in the frame "frame" and - a color chooser dialog should appear. -2. Without closing the color chooser, change Look And Feel - selecting it from the combobox in the frame "frame". - Dialog appearance will change. -3. Resize the color chooser by mouse drag. - - If you see some remnants of the previous color chooser, - press "Fail" else press "Pass". - - - - - diff --git a/test/jdk/javax/swing/JColorChooser/Test4319113.java b/test/jdk/javax/swing/JColorChooser/Test4319113.java index 7113d8259f1..19239213d24 100644 --- a/test/jdk/javax/swing/JColorChooser/Test4319113.java +++ b/test/jdk/javax/swing/JColorChooser/Test4319113.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,27 +21,15 @@ * questions. */ -/* - * @test - * @bug 4319113 - * @summary Tests the open JColorChooser behavior on LaF change. - * @author yan - * @run applet/manual=yesno Test4319113.html - */ - - import java.awt.Color; import java.awt.Component; import java.awt.Frame; import java.awt.GridLayout; -import java.awt.LayoutManager; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; -import java.io.PrintStream; -import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JComboBox; @@ -50,47 +38,66 @@ import javax.swing.SwingUtilities; import javax.swing.UIManager; -public class Test4319113 -extends JApplet -implements ActionListener { - private final JFrame frame = new JFrame("frame"); - private JComboBox cbPlaf; +/* + * @test + * @bug 4319113 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Tests the open JColorChooser behavior on LaF change. + * @run main/manual Test4319113 + */ +public class Test4319113 { - @Override - public void init() { - try { - java.awt.EventQueue.invokeLater( () -> { - Test4319113.this.frame.setLayout(new GridLayout(2, 1)); - Test4319113.this.show(Test4319113.this.frame); - }); - }catch(Exception ex) { - ex.printStackTrace(); - } - } + public static void main(String[] args) throws Exception { + String instructions = "1. Press button \"Show ColorChooser\" in the frame \"frame\" and\n" + + " a color chooser dialog should appear.\n" + + "2. Without closing the color chooser, change Look And Feel\n" + + " selecting it from the combobox in the frame \"frame\".\n" + + " Dialog appearance will change.\n" + + "3. Resize the color chooser by mouse drag.\n" + + "\n" + + " If you see some remnants of the previous color chooser,\n" + + " press \"Fail\" else press \"Pass\"."; - @Override - public void actionPerformed(ActionEvent actionEvent) { - Object object = actionEvent.getSource(); - Component component = object instanceof Component ? (Component)object : null; - JDialog jDialog = JColorChooser.createDialog(component, "ColorChooser", false, new JColorChooser(Color.BLUE), null, null); - jDialog.setVisible(true); + PassFailJFrame.builder() + .title("Test4319113") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(10) + .testUI(Test4319113::test) + .build() + .awaitAndCheck(); } - private void show(Window window) { + private static JFrame test() { + JFrame frame = new JFrame("JColorChooser behavior on LaF change"); + frame.setLayout(new GridLayout(2, 1)); + JButton jButton = new JButton("Show ColorChooser"); jButton.setActionCommand("Show ColorChooser"); - jButton.addActionListener(this); - this.cbPlaf = new JComboBox(UIManager.getInstalledLookAndFeels()); - this.cbPlaf.addItemListener(new ItemListener(){ + jButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent actionEvent) { + Object object = actionEvent.getSource(); + Component component = object instanceof Component ? (Component) object : null; + JDialog jDialog = JColorChooser.createDialog(component, "ColorChooser", + false, new JColorChooser(Color.BLUE), null, null); + jDialog.setVisible(true); + } + }); + JComboBox cbPlaf = new JComboBox(UIManager.getInstalledLookAndFeels()); + cbPlaf.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent itemEvent) { if (itemEvent.getStateChange() == 1) { - SwingUtilities.invokeLater(new Runnable(){ + SwingUtilities.invokeLater(new Runnable() { @Override public void run() { - UIManager.LookAndFeelInfo lookAndFeelInfo = (UIManager.LookAndFeelInfo)Test4319113.this.cbPlaf.getSelectedItem(); + UIManager.LookAndFeelInfo lookAndFeelInfo = + (UIManager.LookAndFeelInfo) cbPlaf.getSelectedItem(); try { UIManager.setLookAndFeel(lookAndFeelInfo.getClassName()); Frame[] arrframe = Frame.getFrames(); @@ -98,8 +105,7 @@ public void run() { while (--n >= 0) { Test4319113.updateWindowTreeUI(arrframe[n]); } - } - catch (Exception var2_3) { + } catch (Exception var2_3) { System.err.println("Exception while changing L&F!"); } } @@ -108,10 +114,12 @@ public void run() { } }); - window.add(this.cbPlaf); - window.add(jButton); - window.pack(); - window.setVisible(true); + + frame.add(cbPlaf); + frame.add(jButton); + frame.pack(); + + return frame; } private static void updateWindowTreeUI(Window window) { diff --git a/test/jdk/javax/swing/JColorChooser/Test4759306.html b/test/jdk/javax/swing/JColorChooser/Test4759306.html deleted file mode 100644 index 6e3bfed203f..00000000000 --- a/test/jdk/javax/swing/JColorChooser/Test4759306.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - -If you see the preview panel, then test failed, otherwise it passed. - - - - - diff --git a/test/jdk/javax/swing/JColorChooser/Test4759306.java b/test/jdk/javax/swing/JColorChooser/Test4759306.java index 37a549acd79..762031ec481 100644 --- a/test/jdk/javax/swing/JColorChooser/Test4759306.java +++ b/test/jdk/javax/swing/JColorChooser/Test4759306.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2008, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,22 +21,34 @@ * questions. */ +import javax.swing.JColorChooser; +import javax.swing.JPanel; + /* * @test * @bug 4759306 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame * @summary Checks if JColorChooser.setPreviewPanel removes the old one - * @author Konstantin Eremin - @run applet/manual=yesno Test4759306.html + * @run main/manual Test4759306 */ +public class Test4759306 { -import javax.swing.JApplet; -import javax.swing.JColorChooser; -import javax.swing.JPanel; + public static void main(String[] args) throws Exception { + PassFailJFrame.builder() + .title("Test4759306") + .instructions("Check that there is no panel titled \"Preview\" in the JColorChooser.") + .rows(5) + .columns(40) + .testTimeOut(10) + .splitUIRight(Test4759306::createColorChooser) + .build() + .awaitAndCheck(); + } -public class Test4759306 extends JApplet { - public void init() { + private static JColorChooser createColorChooser() { JColorChooser chooser = new JColorChooser(); chooser.setPreviewPanel(new JPanel()); - getContentPane().add(chooser); + return chooser; } } diff --git a/test/jdk/javax/swing/JColorChooser/Test4759934.html b/test/jdk/javax/swing/JColorChooser/Test4759934.html deleted file mode 100644 index 64dec2db159..00000000000 --- a/test/jdk/javax/swing/JColorChooser/Test4759934.html +++ /dev/null @@ -1,37 +0,0 @@ - - - - -1. Press button "Show Dialog" at the frame "Test" and - the dialog with button "Show ColorChooser" should appears. -2. Press button "Show ColorChooser" at the dialog "Dialog" and - the colorchooser should appears. -3. Press the button "Cancel" of colorchooser. - If the focus will come to the frame "Test" then test fails. - If the focus will come to the dialog "Dialog" then test passes. - - - - - diff --git a/test/jdk/javax/swing/JColorChooser/Test4759934.java b/test/jdk/javax/swing/JColorChooser/Test4759934.java index 620de37e2d4..72a1ed4dcec 100644 --- a/test/jdk/javax/swing/JColorChooser/Test4759934.java +++ b/test/jdk/javax/swing/JColorChooser/Test4759934.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2008, 2024 Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,60 +21,87 @@ * questions. */ -/* - * @test - * @bug 4759934 - * @summary Tests windows activation problem - * @author Andrey Pikalev - * @run applet/manual=yesno Test4759934.html - */ - import java.awt.Color; import java.awt.Component; import java.awt.Window; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; import javax.swing.JDialog; import javax.swing.JFrame; -public class Test4759934 extends JApplet implements ActionListener { +/* + * @test + * @bug 4759934 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Tests windows activation problem + * @run main/manual Test4759934 + */ +public class Test4759934 { private static final String CMD_DIALOG = "Show Dialog"; // NON-NLS: first button private static final String CMD_CHOOSER = "Show ColorChooser"; // NON-NLS: second button - private final JFrame frame = new JFrame("Test"); // NON-NLS: frame title + private static JFrame frame; - public void init() { - show(this.frame, CMD_DIALOG); - } + private static ActionListener al = new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + String command = event.getActionCommand(); + if (CMD_DIALOG.equals(command)) { + JDialog dialog = new JDialog(frame, "Dialog"); // NON-NLS: dialog title + dialog.setLocation(200, 0); + show(dialog, CMD_CHOOSER, true); + } + else if (CMD_CHOOSER.equals(command)) { + Object source = event.getSource(); + Component component = (source instanceof Component) + ? (Component) source + : null; - public void actionPerformed(ActionEvent event) { - String command = event.getActionCommand(); - if (CMD_DIALOG.equals(command)) { - JDialog dialog = new JDialog(this.frame, "Dialog"); // NON-NLS: dialog title - dialog.setLocation(200, 0); - show(dialog, CMD_CHOOSER); + JColorChooser.showDialog(component, "ColorChooser", Color.BLUE); // NON-NLS: title + } } - else if (CMD_CHOOSER.equals(command)) { - Object source = event.getSource(); - Component component = (source instanceof Component) - ? (Component) source - : null; + }; - JColorChooser.showDialog(component, "ColorChooser", Color.BLUE); // NON-NLS: title - } + public static void main(String[] args) throws Exception { + String instructions = "1. Press button \"Show Dialog\" at the frame \"Test\" and\n" + + " the dialog with button \"Show ColorChooser\" should appears.\n" + + "2. Press button \"Show ColorChooser\" at the dialog \"Dialog\" and\n" + + " the colorchooser should appears.\n" + + "3. Press the button \"Cancel\" of colorchooser.\n" + + " If the focus will come to the frame \"Test\" then test fails.\n" + + " If the focus will come to the dialog \"Dialog\" then test passes."; + + PassFailJFrame.builder() + .title("Test4759934") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(10) + .testUI(Test4759934::test) + .build() + .awaitAndCheck(); } - private void show(Window window, String command) { + public static JFrame test() { + frame = new JFrame("ColorChooser dialog on button press test"); + show(frame, CMD_DIALOG, false); + return frame; + } + + private static void show(Window window, String command, boolean setVisible) { JButton button = new JButton(command); button.setActionCommand(command); - button.addActionListener(this); + button.addActionListener(al); + button.setFont(button.getFont().deriveFont(64.0f)); window.add(button); window.pack(); - window.setVisible(true); + if (setVisible) { + window.setVisible(true); + } } } diff --git a/test/jdk/javax/swing/JColorChooser/Test4887836.html b/test/jdk/javax/swing/JColorChooser/Test4887836.html deleted file mode 100644 index 68192afdbcb..00000000000 --- a/test/jdk/javax/swing/JColorChooser/Test4887836.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - -If you do not see white area under swatches, -then test passed, otherwise it failed. - - - - - diff --git a/test/jdk/javax/swing/JColorChooser/Test4887836.java b/test/jdk/javax/swing/JColorChooser/Test4887836.java index 9972b5fe085..82a09c46085 100644 --- a/test/jdk/javax/swing/JColorChooser/Test4887836.java +++ b/test/jdk/javax/swing/JColorChooser/Test4887836.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,23 +21,49 @@ * questions. */ +import java.awt.Color; +import java.awt.Font; +import javax.swing.JColorChooser; +import javax.swing.UIManager; + +import jtreg.SkippedException; + /* * @test * @bug 4887836 - * @summary Checks if no tooltip modification when no KeyStroke modifier - * @author Konstantin Eremin - * @run applet/manual=yesno Test4887836.html + * @library /java/awt/regtesthelpers /test/lib + * @build PassFailJFrame + * @summary Checks for white area under the JColorChooser Swatch tab + * @run main/manual Test4887836 */ -import java.awt.Color; -import java.awt.Font; -import javax.swing.JApplet; -import javax.swing.JColorChooser; -import javax.swing.UIManager; +public class Test4887836 { + + public static void main(String[] args) throws Exception { + + // ColorChooser UI design is different for GTK L&F. + // There is no Swatches tab available for GTK L&F, skip the testing. + if (UIManager.getLookAndFeel().getName().contains("GTK")) { + throw new SkippedException("Test not applicable for GTK L&F"); + } + + String instructions = """ + If you do not see white area under the \"Swatches\" tab, + then test passed, otherwise it failed."""; + + PassFailJFrame.builder() + .title("Test4759306") + .instructions(instructions) + .columns(40) + .testUI(Test4887836::createColorChooser) + .build() + .awaitAndCheck(); + } + + private static JColorChooser createColorChooser() { + JColorChooser chooser = new JColorChooser(Color.LIGHT_GRAY); -public class Test4887836 extends JApplet { - public void init() { - UIManager.put("Label.font", new Font("Perpetua", 0, 36)); // NON-NLS: property and font names - add(new JColorChooser(Color.LIGHT_GRAY)); + UIManager.put("Label.font", new Font("Font.DIALOG", 0, 36)); + return chooser; } } diff --git a/test/jdk/javax/swing/JColorChooser/Test6348456.html b/test/jdk/javax/swing/JColorChooser/Test6348456.html deleted file mode 100644 index d4a49c0f246..00000000000 --- a/test/jdk/javax/swing/JColorChooser/Test6348456.html +++ /dev/null @@ -1,32 +0,0 @@ - - - - -When applet starts, you'll see that the preview is white. -When you swap models, you'll see that the preview color is changed. - - - - - diff --git a/test/jdk/javax/swing/JColorChooser/Test6348456.java b/test/jdk/javax/swing/JColorChooser/Test6348456.java index c6d34e45582..b1830979295 100644 --- a/test/jdk/javax/swing/JColorChooser/Test6348456.java +++ b/test/jdk/javax/swing/JColorChooser/Test6348456.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,43 +21,67 @@ * questions. */ -/* - * @test - * @bug 6348456 - * @summary Tests model changing - * @author Sergey Malenkov - * @run applet/manual=yesno Test6348456.html - */ - import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -import javax.swing.JApplet; import javax.swing.JButton; import javax.swing.JColorChooser; +import javax.swing.JFrame; import javax.swing.colorchooser.DefaultColorSelectionModel; -public final class Test6348456 extends JApplet implements ActionListener { +/* + * @test + * @bug 6348456 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Tests model changing + * @run main/manual Test6348456 + */ - private static final DefaultColorSelectionModel WHITE = new DefaultColorSelectionModel(Color.WHITE); - private static final DefaultColorSelectionModel BLACK = new DefaultColorSelectionModel(Color.BLACK); +public final class Test6348456 { - private JColorChooser chooser; + private static final DefaultColorSelectionModel WHITE = + new DefaultColorSelectionModel(Color.WHITE); + private static final DefaultColorSelectionModel BLACK = + new DefaultColorSelectionModel(Color.BLACK); - @Override - public void init() { - JButton button = new JButton("Swap models"); - button.addActionListener(this); + private static JColorChooser chooser; - this.chooser = new JColorChooser(Color.RED); - this.chooser.setSelectionModel(WHITE); + public static void main(String[] args) throws Exception { + String instructions = "When test starts, you'll see that the preview is white.\n" + + "When you swap models, you'll see that the preview color is changed.\n" + + "Click pass if so, otherwise fail."; - add(BorderLayout.NORTH, button); - add(BorderLayout.CENTER, this.chooser); + PassFailJFrame.builder() + .title("Test6348456") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(10) + .testUI(Test6348456::test) + .build() + .awaitAndCheck(); } - public void actionPerformed(ActionEvent event){ - this.chooser.setSelectionModel(this.chooser.getSelectionModel() == BLACK ? WHITE : BLACK); + public static JFrame test() { + JFrame frame = new JFrame("JColor Swap Models Test"); + JButton button = new JButton("Swap models"); + button.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent event) { + chooser.setSelectionModel(chooser.getSelectionModel() == BLACK ? WHITE : BLACK); + + } + }); + + chooser = new JColorChooser(Color.RED); + chooser.setSelectionModel(WHITE); + + frame.add(BorderLayout.NORTH, button); + frame.add(BorderLayout.CENTER, chooser); + frame.pack(); + + return frame; } } diff --git a/test/jdk/javax/swing/JColorChooser/Test6977726.html b/test/jdk/javax/swing/JColorChooser/Test6977726.html deleted file mode 100644 index 866332236fc..00000000000 --- a/test/jdk/javax/swing/JColorChooser/Test6977726.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - -If you don't see the preview panel, then test failed, otherwise it passed. - - - - - diff --git a/test/jdk/javax/swing/JColorChooser/Test6977726.java b/test/jdk/javax/swing/JColorChooser/Test6977726.java index bb42cee5b26..a79931c93eb 100644 --- a/test/jdk/javax/swing/JColorChooser/Test6977726.java +++ b/test/jdk/javax/swing/JColorChooser/Test6977726.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,22 +21,42 @@ * questions. */ +import java.awt.Color; +import javax.swing.JColorChooser; +import javax.swing.JLabel; + /* * @test * @bug 6977726 - * @summary Checks if JColorChooser.setPreviewPanel removes the old one - * @author Sergey Malenkov - * @run applet/manual=yesno Test6977726.html + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary Checks if JColorChooser.setPreviewPanel(JLabel) doesn't remove the preview panel but + * removes the content of the default preview panel + * @run main/manual Test6977726 */ -import javax.swing.JApplet; -import javax.swing.JColorChooser; -import javax.swing.JLabel; +public class Test6977726 { + + public static void main(String[] args) throws Exception { + String instructions = """ + Check that there is a panel with "Text Preview Panel" text + and with title "Preview" in the JColorChooser. + Test passes if the panel is as described, test fails otherwise."""; + + PassFailJFrame.builder() + .title("Test6977726") + .instructions(instructions) + .rows(5) + .columns(40) + .testTimeOut(2) + .testUI(Test6977726::createColorChooser) + .build() + .awaitAndCheck(); + } -public class Test6977726 extends JApplet { - public void init() { - JColorChooser chooser = new JColorChooser(); + private static JColorChooser createColorChooser() { + JColorChooser chooser = new JColorChooser(Color.BLUE); chooser.setPreviewPanel(new JLabel("Text Preview Panel")); - getContentPane().add(chooser); + return chooser; } } diff --git a/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java b/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java index d21dd40a160..5540bb30614 100644 --- a/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java +++ b/test/jdk/javax/swing/JComboBox/6559152/bug6559152.java @@ -24,29 +24,32 @@ /* * @test * @key headful - * @bug 6559152 + * @bug 6559152 8294067 * @summary Checks that you can select an item in JComboBox with keyboard * when it is a JTable cell editor. * @run main bug6559152 */ +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; + import javax.swing.DefaultCellEditor; +import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JFrame; -import javax.swing.JComboBox; +import javax.swing.JTable; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; -import javax.swing.JTable; -import java.awt.Point; -import java.awt.event.KeyEvent; -import java.awt.event.InputEvent; -import java.awt.Robot; public class bug6559152 { private static JFrame frame; private static JComboBox cb; private static Robot robot; private static Point p = null; + private static Dimension d; public static void main(String[] args) throws Exception { robot = new Robot(); @@ -69,6 +72,7 @@ static void blockTillDisplayed(JComponent comp) throws Exception { try { SwingUtilities.invokeAndWait(() -> { p = comp.getLocationOnScreen(); + d = comp.getSize(); }); } catch (IllegalStateException e) { try { @@ -97,7 +101,7 @@ private static void setupUI() { } private static void test() throws Exception { - robot.mouseMove(p.x, p.y); + robot.mouseMove(p.x + d.width / 2, p.y + d.height / 2); robot.waitForIdle(); robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); diff --git a/test/jdk/javax/swing/JComponent/bug4765272.java b/test/jdk/javax/swing/JComponent/bug4765272.java new file mode 100644 index 00000000000..d88d5f328ed --- /dev/null +++ b/test/jdk/javax/swing/JComponent/bug4765272.java @@ -0,0 +1,130 @@ +/* + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4765272 + * @summary REGRESSION: IAE: focusCycleRoot not focus cyle root of a Component + * @key headful + */ + +import java.awt.Component; +import java.awt.Container; +import java.awt.FlowLayout; +import java.awt.FocusTraversalPolicy; +import java.awt.Robot; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public class bug4765272 { + static boolean focusGained = false; + static JFrame f; + static JButton bt1; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4765272"); + bt1 = new JButton("Button 1"); + JButton bt2 = new JButton("Button 2"); + + JPanel p = new JPanel(); + p.setLayout(new FlowLayout()); + p.add(bt1); + p.add(bt2); + f.getContentPane().add(p); + + FocusTraversalPolicy policy = new FocusTraversalPolicy() { + @Override + public Component getComponentAfter(Container aContainer, Component aComponent) { + if (aComponent == bt1) { + return bt2; + } + return bt1; + } + + @Override + public Component getComponentBefore(Container aContainer, Component aComponent) { + if (aComponent == bt1) { + return bt2; + } + return bt1; + } + + @Override + public Component getFirstComponent(Container aContainer) { + return bt1; + } + + @Override + public Component getLastComponent(Container aContainer) { + return bt2; + } + + @Override + public Component getDefaultComponent(Container aContainer) { + return bt1; + } + }; + + bt1.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + p.removeAll(); + synchronized (this) { + focusGained = true; + this.notifyAll(); + } + } + }); + + f.setLocationRelativeTo(null); + f.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + bt1.requestFocus(); + try { + if (!focusGained) { + Thread.sleep(5000); + } + } catch (Exception ex) { + ex.printStackTrace(); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + } +} diff --git a/test/jdk/javax/swing/JComponent/bug4979794.java b/test/jdk/javax/swing/JComponent/bug4979794.java new file mode 100644 index 00000000000..e8203045e57 --- /dev/null +++ b/test/jdk/javax/swing/JComponent/bug4979794.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4979794 + * @summary A component is sometimes the next component for itself in focus policy. + * @key headful + */ + +import java.awt.Component; +import java.awt.Container; +import java.awt.FocusTraversalPolicy; +import java.awt.Robot; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public class bug4979794 { + static JFrame fr; + static JButton btn1; + static JButton btn2; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4979794"); + fr.getContentPane().setLayout(null); + + JPanel p = new JPanel(); + p.setLayout(null); + fr.getContentPane().add(p); + + btn1 = new JButton("Button 1"); + btn1.setBounds(0, 0, 200, 200); + + btn2 = new JButton("Button 2"); + btn2.setBounds(0, 0, 200, 200); + + p.add(btn1); + p.add(btn2); + p.setSize(200, 200); + + fr.setLocationRelativeTo(null); + fr.setSize(300, 300); + fr.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + Container root = btn1.getFocusCycleRootAncestor(); + FocusTraversalPolicy policy = root.getFocusTraversalPolicy(); + Component next1 = policy.getComponentAfter(fr, btn1); + Component next2 = policy.getComponentAfter(fr, btn2); + if (next1 == next2) { + throw new RuntimeException("btn1 and btn2 have the same next Component."); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff --git a/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.html b/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.html deleted file mode 100644 index cf5ea552af3..00000000000 --- a/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.html +++ /dev/null @@ -1,31 +0,0 @@ - - - - - -1. Go into 'subdir' folder via double click -2. Return to parent directory -3. Go into 'subdir' folder: select 'subdir' folder and press the 'Open' button - - diff --git a/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java b/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java index 7c3473cfec9..60bc15012d3 100644 --- a/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java +++ b/test/jdk/javax/swing/JFileChooser/6698013/bug6698013.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,41 +21,53 @@ * questions. */ -/* @test - @bug 6698013 - @summary JFileChooser can no longer navigate non-local file systems. - @run applet/manual=done bug6698013.html -*/ - import java.io.File; - -import javax.swing.JApplet; import javax.swing.JFileChooser; import javax.swing.SwingUtilities; import javax.swing.filechooser.FileSystemView; -public class bug6698013 extends JApplet { - - final static VirtualFile root = new VirtualFile("testdir", true); - - final static VirtualFile rootFile = new VirtualFile("testdir/test.txt", false); +/* + * @test + * @bug 6698013 + * @library /java/awt/regtesthelpers + * @build PassFailJFrame + * @summary JFileChooser can no longer navigate non-local file systems. + * @run main/manual bug6698013 + */ - final static VirtualFile subdir = new VirtualFile("testdir/subdir", true); +public class bug6698013 { - final static VirtualFile subdirFile = new VirtualFile("testdir/subdir/subtest.txt", false); + final static VirtualFile root = new VirtualFile("testdir", true); public static void main(String[] args) throws Exception { - SwingUtilities.invokeAndWait(() -> new bug6698013().init()); - } - - public void init() { - JFileChooser chooser = new JFileChooser(new VirtualFileSystemView()); - chooser.setCurrentDirectory(root); - chooser.showOpenDialog(null); + String instructions = """ + 1. Go into 'subdir' folder via double click + 2. Return to parent directory + 3. Go into 'subdir' folder: select 'subdir' folder and press the 'Open' button + If both methods of navigating into the subdir work, pass test. Otherwise fail."""; + + PassFailJFrame pfframe = PassFailJFrame.builder() + .title("bug6698013") + .instructions(instructions) + .rows(25) + .columns(40) + .testTimeOut(10) + .build(); + + SwingUtilities.invokeAndWait(() -> { + JFileChooser chooser = new JFileChooser(new VirtualFileSystemView()); + chooser.setCurrentDirectory(root); + chooser.showOpenDialog(null); + }); + + pfframe.awaitAndCheck(); } } class VirtualFileSystemView extends FileSystemView { + final static VirtualFile rootFile = new VirtualFile("testdir/test.txt", false); + final static VirtualFile subdir = new VirtualFile("testdir/subdir", true); + final static VirtualFile subdirFile = new VirtualFile("testdir/subdir/subtest.txt", false); public boolean isRoot(File dir) { return bug6698013.root.equals(dir); @@ -87,11 +99,11 @@ public File getParentDirectory(File dir) { public File[] getFiles(File dir, boolean hide_hidden) { if (dir.equals(bug6698013.root)) { - return new File[]{bug6698013.rootFile, bug6698013.subdir}; + return new File[]{rootFile, subdir}; } - if (dir.equals(bug6698013.subdir)) { - return new File[]{bug6698013.subdirFile}; + if (dir.equals(subdir)) { + return new File[]{subdirFile}; } return null; diff --git a/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.java b/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.java index a2df90c76ea..de5d6fbd0a5 100644 --- a/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.java +++ b/test/jdk/javax/swing/JFileChooser/8080628/bug8080628.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 @@ -33,7 +33,17 @@ * @test * @bug 8080628 * @summary No mnemonics on Open and Save buttons in JFileChooser. - * @author Alexey Ivanov + * @requires os.family != "linux" + * @modules java.desktop/sun.swing + * @run main bug8080628 + */ + +/* + * @test + * @bug 8080628 + * @key headful + * @summary No mnemonics on Open and Save buttons in JFileChooser. + * @requires os.family == "linux" * @modules java.desktop/sun.swing * @run main bug8080628 */ @@ -81,8 +91,10 @@ private static void runTest() { try { UIManager.setLookAndFeel(info.getClassName()); } catch (final UnsupportedLookAndFeelException ignored) { + System.out.println("Unsupported L&F: " + info.getClassName()); continue; } + System.out.println("Testing L&F: " + info.getClassName()); for (Locale locale : LOCALES) { for (String key : MNEMONIC_KEYS) { diff --git a/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java b/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java index a1dc1532dce..b5f26aaf6e6 100644 --- a/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java +++ b/test/jdk/javax/swing/JInternalFrame/6725409/bug6725409.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,68 +21,61 @@ * questions. */ -/* @test +/* + * @test * @key headful * @bug 6725409 * @requires (os.family == "windows") * @summary Checks that JInternalFrame's system menu * can be localized during run-time - * @author Mikhail Lapshin - * @library /lib/client/ * @modules java.desktop/com.sun.java.swing.plaf.windows - * @build ExtendedRobot * @run main bug6725409 */ -import javax.swing.*; -import java.awt.*; +import java.awt.Robot; +import javax.swing.JDesktopPane; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JMenuItem; +import javax.swing.JPopupMenu; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel; +import com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane; public class bug6725409 { private JFrame frame; private JInternalFrame iFrame; - private TestTitlePane testTitlePane; - private boolean passed; - private static ExtendedRobot robot = createRobot(); + private static TestTitlePane testTitlePane; + private static volatile boolean passed; + private static Robot robot; public static void main(String[] args) throws Exception { - try { - UIManager.setLookAndFeel( - new com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel()); - } catch(UnsupportedLookAndFeelException e) { - System.out.println("The test is for Windows LaF only"); - return; - } + UIManager.setLookAndFeel( + new WindowsClassicLookAndFeel()); + robot = new Robot(); final bug6725409 bug6725409 = new bug6725409(); try { - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - bug6725409.setupUIStep1(); - } - }); + SwingUtilities.invokeAndWait(bug6725409::setupUIStep1); sync(); - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - bug6725409.setupUIStep2(); - } - }); + SwingUtilities.invokeAndWait(bug6725409::setupUIStep2); sync(); - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - bug6725409.test(); - } - }); + SwingUtilities.invokeAndWait(bug6725409::test); sync(); bug6725409.checkResult(); } finally { - if (bug6725409.frame != null) { - bug6725409.frame.dispose(); - } + SwingUtilities.invokeAndWait(() -> { + if (bug6725409.frame != null) { + bug6725409.frame.dispose(); + } + }); } } private void setupUIStep1() { - frame = new JFrame(); + frame = new JFrame("bug6725409"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); JDesktopPane desktop = new JDesktopPane(); @@ -147,19 +140,9 @@ private void checkResult() { private static void sync() { robot.waitForIdle(); } - private static ExtendedRobot createRobot() { - try { - ExtendedRobot robot = new ExtendedRobot(); - return robot; - }catch(Exception ex) { - ex.printStackTrace(); - throw new Error("Unexpected Failure"); - } - } // Extend WindowsInternalFrameTitlePane to get access to systemPopupMenu - private class TestTitlePane extends - com.sun.java.swing.plaf.windows.WindowsInternalFrameTitlePane { + private class TestTitlePane extends WindowsInternalFrameTitlePane { private JPopupMenu systemPopupMenu; public TestTitlePane(JInternalFrame f) { diff --git a/test/jdk/javax/swing/JPanel/bug4907772.java b/test/jdk/javax/swing/JPanel/bug4907772.java new file mode 100644 index 00000000000..56c784b7653 --- /dev/null +++ b/test/jdk/javax/swing/JPanel/bug4907772.java @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4907772 + * @summary 1.4 REGRESSION: JPanel responds to mouse clicks on overlapping JPanel + * @key headful + */ + +import java.awt.Component; +import java.awt.Container; +import java.awt.FocusTraversalPolicy; +import java.awt.Robot; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public class bug4907772 { + static JFrame fr; + static JButton btn1; + static JButton btn2; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4907772"); + fr.getContentPane().setLayout(null); + + JPanel p = new JPanel(); + p.setLayout(null); + fr.getContentPane().add(p); + + btn1 = new JButton("Button 1"); + btn1.setBounds(0, 0, 200, 200); + + btn2 = new JButton("Button 2"); + btn2.setBounds(0, 0, 200, 200); + + p.add(btn1); + p.add(btn2); + + fr.setLocationRelativeTo(null); + fr.pack(); + fr.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + Container root = btn1.getFocusCycleRootAncestor(); + FocusTraversalPolicy policy = root.getFocusTraversalPolicy(); + Component initial = policy.getInitialComponent(fr); + if (initial == btn2) { + throw new RuntimeException("The underlying button shouldn't be the initial component of FCR"); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff --git a/test/jdk/java/util/Locale/Bug4210525.java b/test/jdk/javax/swing/JScrollPane/bug4688907.java similarity index 61% rename from test/jdk/java/util/Locale/Bug4210525.java rename to test/jdk/javax/swing/JScrollPane/bug4688907.java index 3c025cb1afa..4920a3bceee 100644 --- a/test/jdk/java/util/Locale/Bug4210525.java +++ b/test/jdk/javax/swing/JScrollPane/bug4688907.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,30 +20,25 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -/** - @test - @summary Locale variant should not be uppercased - @run main Bug4210525 - @bug 4210525 -*/ -import java.util.Locale; +/* + * @test + * @bug 4688907 + * @summary ScrollPaneLayout.minimumLayoutSize incorrectly compares hsbPolicy + */ -public class Bug4210525 { +import java.awt.Dimension; +import javax.swing.JScrollPane; +public class bug4688907 { public static void main(String[] args) throws Exception { - String language = "en"; - String country = "US"; - String variant = "socal"; - - Locale aLocale = new Locale(language, country, variant); - - String localeVariant = aLocale.getVariant(); - if (localeVariant.equals(variant)) { - System.out.println("passed"); - } else { - System.out.println("failed"); - throw new Exception("Bug4210525 test failed."); + JScrollPane sp = new JScrollPane(); + Dimension d1 = sp.getMinimumSize(); + sp.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + Dimension d2 = sp.getMinimumSize(); + if (d1.height == d2.height) { + throw new RuntimeException("The scrollbar minimum size doesn't take " + + "into account horizontal scrollbar policy"); } } } diff --git a/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java b/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java index 97164c253dd..6a39d7b96fa 100644 --- a/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java +++ b/test/jdk/javax/swing/JTabbedPane/8134116/Bug8134116.java @@ -1,13 +1,43 @@ +/* + * Copyright (c) 2015, 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ -import java.awt.*; +import java.awt.Component; +import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.util.ArrayList; import java.util.List; + import javax.accessibility.Accessible; import javax.accessibility.AccessibleContext; import javax.accessibility.AccessibleState; import javax.accessibility.AccessibleStateSet; -import javax.swing.*; +import javax.swing.Icon; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; import javax.swing.plaf.nimbus.NimbusLookAndFeel; /* @@ -22,7 +52,7 @@ public class Bug8134116 { private static volatile Exception exception = null; private static JFrame frame; - public static void main(String args[]) throws Exception { + public static void main(String[] args) throws Exception { try { UIManager.setLookAndFeel(new NimbusLookAndFeel()); diff --git a/test/jdk/javax/swing/JTableHeader/bug4243927.java b/test/jdk/javax/swing/JTableHeader/bug4243927.java new file mode 100644 index 00000000000..a46b1fa86a5 --- /dev/null +++ b/test/jdk/javax/swing/JTableHeader/bug4243927.java @@ -0,0 +1,45 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4243927 + * @summary Tests that methods getAccessibleChild() and getAccessibleAt() + * of class JTableHeader.AccessibleJTableHeader do not throw NPE + */ + +import javax.accessibility.AccessibleComponent; +import javax.accessibility.AccessibleContext; +import javax.swing.table.JTableHeader; +import javax.swing.table.TableColumn; + +public class bug4243927 { + public static void main(String[] argv) { + JTableHeader header = new JTableHeader(); + header.getColumnModel().addColumn(new TableColumn(0)); + + AccessibleContext c = header.getAccessibleContext(); + c.getAccessibleChild(0); + ((AccessibleComponent)c).getAccessibleAt(new java.awt.Point(0,0)); + } +} diff --git a/test/jdk/javax/swing/JToolBar/bug4138694.java b/test/jdk/javax/swing/JToolBar/bug4138694.java new file mode 100644 index 00000000000..2750fe91bc9 --- /dev/null +++ b/test/jdk/javax/swing/JToolBar/bug4138694.java @@ -0,0 +1,59 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4138694 + * @summary When adding an Action object to a toolbar, the Action object's + * SHORT_DESCRIPTION property (if present) should be automatically used + * for toolTip text. + * @run main bug4138694 + */ + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.Action; +import javax.swing.JComponent; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4138694 { + public static final String actionName = "Action"; + + private static class MyAction extends AbstractAction { + public void actionPerformed(ActionEvent e) {} + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar jtb = new JToolBar(); + MyAction aa = new MyAction(); + aa.putValue(Action.SHORT_DESCRIPTION, actionName); + jtb.add(aa); + JComponent c = (JComponent)jtb.getComponentAtIndex(0); + if (!c.getToolTipText().equals(actionName)) { + throw new RuntimeException("ToolTip not set automatically..."); + } + }); + } +} diff --git a/test/jdk/javax/swing/JToolBar/bug4140421.java b/test/jdk/javax/swing/JToolBar/bug4140421.java new file mode 100644 index 00000000000..f089c96fdf8 --- /dev/null +++ b/test/jdk/javax/swing/JToolBar/bug4140421.java @@ -0,0 +1,42 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4140421 + * @summary Tests JToolBar set title correctly + * @run main bug4140421 + */ + +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4140421 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar tb = new JToolBar("MyToolBar"); + if (!tb.getName().equals("MyToolBar")) { + throw new RuntimeException("Title of JToolBar set incorrectly..."); + } + }); + } +} diff --git a/test/jdk/javax/swing/JToolBar/bug4196662.java b/test/jdk/javax/swing/JToolBar/bug4196662.java new file mode 100644 index 00000000000..309d2fff104 --- /dev/null +++ b/test/jdk/javax/swing/JToolBar/bug4196662.java @@ -0,0 +1,48 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4196662 + * @summary JToolBar has remove(int) method. + * @run main bug4196662 + */ + +import javax.swing.JButton; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4196662 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar tb = new JToolBar(); + tb.add(new JButton("Button1")); + JButton bt2 = new JButton("Button2"); + tb.add(bt2); + tb.add(new JButton("Button3")); + tb.remove(1); + if (tb.getComponentCount() != 2 || tb.getComponent(1) == bt2) { + throw new RuntimeException("Component wasn't removed..."); + } + }); + } +} diff --git a/test/jdk/javax/swing/JToolBar/bug4243930.java b/test/jdk/javax/swing/JToolBar/bug4243930.java new file mode 100644 index 00000000000..c6702f1fa44 --- /dev/null +++ b/test/jdk/javax/swing/JToolBar/bug4243930.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4243930 + * @summary Tests that JToolBar.remove() does not throw StackOverflowError + * @run main bug4243930 + */ + +import java.awt.event.ActionEvent; + +import javax.swing.AbstractAction; +import javax.swing.JButton; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4243930 { + + private static class NullAction extends AbstractAction { + public void actionPerformed(ActionEvent e){} + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar tb = new JToolBar(); + JButton test = tb.add(new NullAction()); + tb.remove(test); + }); + } +} diff --git a/test/jdk/javax/swing/JToolBar/bug4368050.java b/test/jdk/javax/swing/JToolBar/bug4368050.java new file mode 100644 index 00000000000..d0c99d4825f --- /dev/null +++ b/test/jdk/javax/swing/JToolBar/bug4368050.java @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4368050 + * @summary Default toolbar layout manager should be serializable. + * @run main bug4368050 + */ + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; + +import javax.swing.JToolBar; + +public class bug4368050 { + public static void main(String[] args) throws Exception { + JToolBar toolBar = new JToolBar(); + + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); + ObjectOutputStream oos = new ObjectOutputStream(baos)) { + oos.writeObject(toolBar); + byte[] buf = baos.toByteArray(); + try (ByteArrayInputStream bais = new ByteArrayInputStream(buf); + ObjectInputStream ois = new ObjectInputStream(bais)) { + ois.readObject(); + } + } + } +} diff --git a/test/jdk/javax/swing/JToolBar/bug4465534.java b/test/jdk/javax/swing/JToolBar/bug4465534.java new file mode 100644 index 00000000000..08035da8cd2 --- /dev/null +++ b/test/jdk/javax/swing/JToolBar/bug4465534.java @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4465534 + * @summary Tests adding borderless button to a toolbar + * @run main bug4465534 + */ + +import javax.swing.JButton; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; + +public class bug4465534 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JToolBar toolbar = new JToolBar(); + JButton button = new JButton("text"); + button.setBorder(null); + toolbar.add(button); + }); + } +} diff --git a/test/jdk/javax/swing/JToolBar/bug4700351.java b/test/jdk/javax/swing/JToolBar/bug4700351.java new file mode 100644 index 00000000000..1b2b28b9f2f --- /dev/null +++ b/test/jdk/javax/swing/JToolBar/bug4700351.java @@ -0,0 +1,64 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4700351 + * @summary Checks if JToolBar keeps orientation when dragged off + * @key headful + * @run main bug4700351 + */ + +import javax.swing.JFrame; +import javax.swing.JToolBar; +import javax.swing.SwingUtilities; +import javax.swing.plaf.basic.BasicToolBarUI; + +public class bug4700351 { + static JFrame fr; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4700351"); + JToolBar tb = new JToolBar(); + tb.setOrientation(JToolBar.VERTICAL); + fr.add(tb); + BasicToolBarUI ui = (javax.swing.plaf.basic.BasicToolBarUI) tb.getUI(); + if (!ui.isFloating()) { + ui.setFloatingLocation(100, 100); + ui.setFloating(true, tb.getLocation()); + } + if (tb.getOrientation() != JToolBar.VERTICAL) { + throw new RuntimeException("Error: toolbar's orientation " + + "has changed"); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff --git a/test/jdk/javax/swing/JToolTip/bug4107843.java b/test/jdk/javax/swing/JToolTip/bug4107843.java new file mode 100644 index 00000000000..0714871a707 --- /dev/null +++ b/test/jdk/javax/swing/JToolTip/bug4107843.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4107843 + * @summary ToolTipText for JTabbedPane. + * @run main bug4107843 + */ + +import javax.swing.JButton; +import javax.swing.JTabbedPane; +import javax.swing.SwingUtilities; + +public class bug4107843 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JTabbedPane tp = new JTabbedPane(); + tp.add("First", new JButton("Button1")); + tp.add("Second", new JButton("Button2")); + tp.setToolTipTextAt(0, "first button"); + if (!tp.getToolTipTextAt(0).equals("first button")) { + throw new RuntimeException("ToolTipText isn't set " + + "as expected..."); + } + tp.setToolTipTextAt(1, "second button"); + if (!tp.getToolTipTextAt(1).equals("second button")) { + throw new RuntimeException("ToolTipText isn't set " + + "as expected..."); + } + }); + } +} diff --git a/test/jdk/javax/swing/JTree/bug4161685.java b/test/jdk/javax/swing/JTree/bug4161685.java new file mode 100644 index 00000000000..5820bd1a076 --- /dev/null +++ b/test/jdk/javax/swing/JTree/bug4161685.java @@ -0,0 +1,52 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4161685 + * @summary JTree now has the public methods setAnchorSelectionPath, + * getAnchorSelectionPath, setLeadSelectionPath. + * @run main bug4161685 + */ + +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.TreePath; + +public class bug4161685 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JTree tr = new JTree(); + TreePath tp = tr.getPathForRow(2); + tr.setAnchorSelectionPath(tp); + if (tr.getAnchorSelectionPath() != tp) { + throw new RuntimeException("AnchorSelectionPath isn't " + + "set correctly..."); + } + tr.setLeadSelectionPath(tp); + if (tr.getLeadSelectionPath() != tp) { + throw new RuntimeException("LeadSelectionPath isn't " + + "set correctly..."); + } + }); + } +} diff --git a/test/jdk/javax/swing/JTree/bug4210432.java b/test/jdk/javax/swing/JTree/bug4210432.java new file mode 100644 index 00000000000..680e8e1e457 --- /dev/null +++ b/test/jdk/javax/swing/JTree/bug4210432.java @@ -0,0 +1,80 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4210432 + * @summary Tests if JTree allows nodes not visible to be selected + * @run main bug4210432 + */ + +import javax.swing.JPanel; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreePath; + +public class bug4210432 { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JPanel p = new JPanel(); + DefaultMutableTreeNode expansible = + new DefaultMutableTreeNode("expansible"); + DefaultMutableTreeNode unexpansible = + new DefaultMutableTreeNode("unexpansible"); + DefaultMutableTreeNode root = new DefaultMutableTreeNode("root"); + DefaultMutableTreeNode subexpansible1 = + new DefaultMutableTreeNode("sub-expansible 1"); + DefaultMutableTreeNode subexpansible2 = + new DefaultMutableTreeNode("sub-expansible 2"); + DefaultMutableTreeNode subsubexpansible1 = + new DefaultMutableTreeNode("sub-sub-expansible 1"); + DefaultMutableTreeNode subsubexpansible2 = + new DefaultMutableTreeNode("sub-sub-expansible 2"); + expansible.add(subexpansible1); + expansible.add(subexpansible2); + subexpansible1.add(subsubexpansible1); + subexpansible1.add(subsubexpansible2); + root.add(expansible); + root.add(unexpansible); + DefaultTreeModel model = new DefaultTreeModel(root); + JTree t = new JTree(model); + Object[] tpa = {root, expansible, subexpansible1}; + Object[] tpa2 = {root, expansible}; + t.setExpandsSelectedPaths(false); + t.setSelectionPath(new TreePath(tpa)); + p.add(t); + if (t.isExpanded(new TreePath(tpa2))) { + throw new RuntimeException("Test failed: JTree should not have " + + "expanded path"); + } + t.clearSelection(); + t.setExpandsSelectedPaths(true); + t.setSelectionPath(new TreePath(tpa)); + if (!t.isExpanded(new TreePath(tpa2))) { + throw new RuntimeException("Test failed: JTree should have " + + "expanded path"); + } + }); + } +} diff --git a/test/jdk/javax/swing/JTree/bug4213868.java b/test/jdk/javax/swing/JTree/bug4213868.java new file mode 100644 index 00000000000..60148becb4c --- /dev/null +++ b/test/jdk/javax/swing/JTree/bug4213868.java @@ -0,0 +1,62 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4213868 + * @summary Tests if AccessibleJTreeNode.getAccessibleIndexInParent() returns + * correct value + * @run main bug4213868 + */ + +import javax.accessibility.AccessibleContext; +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; + +public class bug4213868 { + public static JTree createTree() { + DefaultMutableTreeNode root = + new DefaultMutableTreeNode(0, true); + JTree tree = new JTree(root); + for (int i = 1; i < 10; i++) { + root.add(new DefaultMutableTreeNode(i)); + } + return tree; + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + JTree parent = createTree(); + AccessibleContext c = parent.getAccessibleContext() + .getAccessibleChild(0) + .getAccessibleContext(); + if (c.getAccessibleChild(1) + .getAccessibleContext() + .getAccessibleIndexInParent() != 1) { + throw new RuntimeException("Test failed: " + + "AccessibleJTreeNode.getAccessibleIndexInParent() " + + "returns incorrect value"); + } + }); + } +} diff --git a/test/jdk/javax/swing/JTree/bug4224491.java b/test/jdk/javax/swing/JTree/bug4224491.java new file mode 100644 index 00000000000..e22aca64a9c --- /dev/null +++ b/test/jdk/javax/swing/JTree/bug4224491.java @@ -0,0 +1,61 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4224491 + * @summary Tests if JTree's model & invokesStopCellEditing bound properties + * are working + * @run main bug4224491 + */ + +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; + +public class bug4224491 { + private static boolean modelChanged = false; + private static boolean invokesStopCellEditingChanged = false; + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + DefaultMutableTreeNode root = new DefaultMutableTreeNode(); + JTree jt = new JTree(new DefaultTreeModel(root)); + jt.addPropertyChangeListener(evt -> { + if (evt.getPropertyName().equals("model")) { + modelChanged = true; + } + if (evt.getPropertyName().equals("invokesStopCellEditing")) { + invokesStopCellEditingChanged = true; + } + }); + jt.setModel(new DefaultTreeModel(root)); + jt.setInvokesStopCellEditing(true); + if (!(modelChanged && invokesStopCellEditingChanged)) { + throw new RuntimeException("Test failed: JTree's model " + + "& invokesStopCellEditing bound properties " + + "are not working"); + } + }); + } +} diff --git a/test/jdk/javax/swing/JTree/bug4237370.java b/test/jdk/javax/swing/JTree/bug4237370.java new file mode 100644 index 00000000000..207bbd4b2e8 --- /dev/null +++ b/test/jdk/javax/swing/JTree/bug4237370.java @@ -0,0 +1,81 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4237370 + * @summary Tests that JTree calls TreeExpansionListener methods + * after it has been updated due to expanded/collapsed event + * @run main bug4237370 + */ + +import java.lang.reflect.InvocationTargetException; + +import javax.swing.JTree; +import javax.swing.SwingUtilities; +import javax.swing.event.TreeExpansionEvent; +import javax.swing.event.TreeExpansionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.TreeModel; + +public class bug4237370 { + static class TestTree extends JTree implements TreeExpansionListener { + int[] testMap = {1, 2}; + int testIndex = 0; + + private void testRowCount() { + int rows = getRowCount(); + if (rows != testMap[testIndex]) { + throw new RuntimeException("Bad row count: reported " + rows + + " instead of " + testMap[testIndex]); + } else { + testIndex++; + } + } + + public void treeExpanded(TreeExpansionEvent e) { + testRowCount(); + } + + public void treeCollapsed(TreeExpansionEvent e) { + testRowCount(); + } + + public TestTree() { + super((TreeModel)null); + DefaultMutableTreeNode top = new DefaultMutableTreeNode("Root"); + top.add(new DefaultMutableTreeNode("Sub 1")); + setModel(new DefaultTreeModel(top)); + addTreeExpansionListener(this); + } + } + + public static void main(String[] args) throws InterruptedException, + InvocationTargetException { + SwingUtilities.invokeAndWait(() -> { + TestTree tree = new TestTree(); + tree.collapseRow(0); + tree.expandRow(0); + }); + } +} diff --git a/test/jdk/javax/swing/JTree/bug4662505.java b/test/jdk/javax/swing/JTree/bug4662505.java new file mode 100644 index 00000000000..b231d8c2228 --- /dev/null +++ b/test/jdk/javax/swing/JTree/bug4662505.java @@ -0,0 +1,63 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4662505 + * @summary IllegalArgumentException with empty JTree and key event + * @run main bug4662505 + */ + +import java.awt.event.KeyEvent; +import java.util.Date; + +import javax.swing.JTree; +import javax.swing.SwingUtilities; + +public class bug4662505 { + static DummyTree tree; + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + tree = new DummyTree(); + + try { + tree.doTest(); + } catch (Exception e) { + throw new RuntimeException("Empty JTree shouldn't handle " + + "first letter navigation", e); + } + }); + } + + static class DummyTree extends JTree { + public DummyTree() { + super(new Object[]{}); + } + + public void doTest() { + KeyEvent key = new KeyEvent(tree, KeyEvent.KEY_TYPED, + new Date().getTime(), 0, KeyEvent.VK_UNDEFINED, 'a'); + processKeyEvent(key); + } + } +} diff --git a/test/jdk/javax/swing/JTree/bug4696499.java b/test/jdk/javax/swing/JTree/bug4696499.java new file mode 100644 index 00000000000..54e3aecd7cb --- /dev/null +++ b/test/jdk/javax/swing/JTree/bug4696499.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4696499 + * @summary new tree model asked about nodes of previous tree model + * @run main bug4696499 + */ + +import java.util.ArrayList; + +import javax.swing.JTree; +import javax.swing.event.TreeModelListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.TreeModel; +import javax.swing.tree.TreeNode; +import javax.swing.tree.TreePath; + +public class bug4696499 { + public static void main(String[] args) throws Exception { + JTree tree = new JTree(); + TreeModel model = new MyModel(); + tree.setModel(model); + + tree.setSelectionRow(1); + model = new MyModel(); + tree.setModel(model); + } +} + +class MyModel implements TreeModel { + private Object root = "Root"; + private ArrayList listeners = new ArrayList(); + private TreeNode ONE; + static int next = 1; + + MyModel() { + ONE = new DefaultMutableTreeNode(next); + next *= 2; + } + + public void addTreeModelListener(TreeModelListener l) { + listeners.add(l); + } + + public void removeTreeModelListener(TreeModelListener l) { + listeners.remove(l); + } + + public void valueForPathChanged(TreePath tp, Object newValue) { + } + + public Object getRoot() { + return root; + } + + public boolean isLeaf(Object o) { + return o == ONE; + } + + public int getIndexOfChild(Object parent, Object child) { + if (parent != root || child != ONE) { + throw new RuntimeException("This method is called with the child " + + "of the previous tree model"); + } + return 0; + } + + public int getChildCount(Object o) { + if (o == root) { + return 1; + } + if (o == ONE) { + return 0; + } + throw new IllegalArgumentException(o.toString()); + } + + public Object getChild(Object o, int index) { + if (o != root || index != 0) { + throw new IllegalArgumentException(o + ", " + index); + } + return ONE; + } +} diff --git a/test/jdk/java/util/Locale/Bug4316602.java b/test/jdk/javax/swing/JTree/bug5039542.java similarity index 65% rename from test/jdk/java/util/Locale/Bug4316602.java rename to test/jdk/javax/swing/JTree/bug5039542.java index 9b974a90d01..fd86bc9f65a 100644 --- a/test/jdk/java/util/Locale/Bug4316602.java +++ b/test/jdk/javax/swing/JTree/bug5039542.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -20,26 +20,23 @@ * or visit www.oracle.com if you need additional information or have any * questions. */ -/** - @test - @summary Locale constructor should allow language-only argument - @bug 4316602 - @author joconner -*/ -import java.util.Locale; +/* @test + * @bug 5039542 + * @summary JTree's setToolTipText() doesn't work + * @run main bug5039542 + */ -public class Bug4316602 { +import javax.swing.JTree; +public class bug5039542 { public static void main(String[] args) throws Exception { - String language = "ja"; - Locale aLocale = new Locale(language); - if (aLocale.toString().equals(language)) { - System.out.println("passed"); - } else { - System.out.println("Bug4316602 failed"); - throw new Exception("Bug4316602 failed"); + final String exampleStr = "TEST"; + JTree tree = new JTree(); + tree.setToolTipText(exampleStr); + if (tree.getToolTipText(null) != exampleStr) { + throw new RuntimeException("The default JTree tooltip text " + + "have to be used if renderer doesn't provide it."); } } - } diff --git a/test/jdk/javax/swing/JViewport/bug4546474.java b/test/jdk/javax/swing/JViewport/bug4546474.java new file mode 100644 index 00000000000..95e8fafef09 --- /dev/null +++ b/test/jdk/javax/swing/JViewport/bug4546474.java @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4546474 + * @summary JScrollPane's always-visible scrollbars not updated when + * viewport is replaced + * @run main bug4546474 + */ + +import javax.swing.JPanel; +import javax.swing.JScrollBar; +import javax.swing.JScrollPane; + +public class bug4546474 { + public static void main(String[] args) { + JPanel panel = new JPanel(); + JScrollPane scrollpane = new JScrollPane(panel, + JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, + JScrollPane.HORIZONTAL_SCROLLBAR_NEVER); + JScrollBar sbar = scrollpane.getVerticalScrollBar(); + + scrollpane.setViewportView(null); + + if (sbar.getVisibleAmount() > 0) { + throw new RuntimeException("Vertical scrollbar is not " + + "updated when viewport is replaced"); + } + } +} diff --git a/test/jdk/javax/swing/JViewport/bug4677611.java b/test/jdk/javax/swing/JViewport/bug4677611.java new file mode 100644 index 00000000000..c561ea0f164 --- /dev/null +++ b/test/jdk/javax/swing/JViewport/bug4677611.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4677611 + * @summary JViewport sets Opaque after UpdateUI (prevents UI delegates + * to determine look) + * @run main bug4677611 + */ + +import java.awt.Color; + +import javax.swing.JScrollPane; +import javax.swing.JViewport; + +public class bug4677611 { + public static void main(String[] args) throws Exception { + JScrollPane sp = new JScrollPane(); + JViewport vp = new MyViewport(); + vp.setBackground(Color.blue); + sp.setViewport(vp); + + if (vp.isOpaque()) { + throw new RuntimeException("JViewport shouldn't set Opaque " + + "after update the UI"); + } + } + + static class MyViewport extends JViewport { + public void updateUI() { + setOpaque(false); + super.updateUI(); + } + } +} diff --git a/test/jdk/javax/swing/KeyboardManager/bug4345798.java b/test/jdk/javax/swing/KeyboardManager/bug4345798.java new file mode 100644 index 00000000000..9fa2c3b49e1 --- /dev/null +++ b/test/jdk/javax/swing/KeyboardManager/bug4345798.java @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2000, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* @test + * @bug 4345798 + * @summary Tests if Pressing enter to dismiss menu works when a JRootPane + * has a default button. + * @key headful + * @run main bug4345798 + */ + +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.InputEvent; +import java.awt.event.KeyEvent; + +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JRootPane; +import javax.swing.SwingUtilities; + +public class bug4345798 { + private static JFrame f; + private static JButton b; + private static JMenu menu; + private static volatile boolean passed = true; + private static volatile Point p; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + f = new JFrame("bug4345798"); + JMenuBar mbar = new JMenuBar(); + JMenuItem item = new JMenuItem("Open..."); + menu = new JMenu("File"); + item.addActionListener(new TestActionListener()); + menu.add(item); + mbar.add(menu); + + f.setJMenuBar(mbar); + + b = new JButton("Default"); + b.addActionListener(new TestActionListener()); + f.getContentPane().add(b); + JRootPane rp = f.getRootPane(); + rp.setDefaultButton(b); + + f.setSize(200, 200); + f.setLocationRelativeTo(null); + f.setVisible(true); + b.requestFocus(); + }); + + Robot robot = new Robot(); + robot.setAutoDelay(100); + robot.waitForIdle(); + robot.delay(1000); + + SwingUtilities.invokeAndWait(() -> p = menu.getLocationOnScreen()); + robot.mouseMove(p.x, p.y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + + robot.keyPress(KeyEvent.VK_F10); + robot.keyRelease(KeyEvent.VK_F10); + + robot.keyPress(KeyEvent.VK_DOWN); + robot.keyRelease(KeyEvent.VK_DOWN); + + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } + + if (!passed) { + throw new RuntimeException("Test failed."); + } + } + + static class TestActionListener implements ActionListener { + @Override + public void actionPerformed(ActionEvent e) { + if (e.getSource() == b) { + passed = false; + } + } + } +} diff --git a/test/jdk/javax/swing/LookAndFeel/bug4306431.java b/test/jdk/javax/swing/LookAndFeel/bug4306431.java new file mode 100644 index 00000000000..f9b75bcb0ef --- /dev/null +++ b/test/jdk/javax/swing/LookAndFeel/bug4306431.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 2001, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4306431 + * @summary Tests that Metal themes allow font definition for JList + */ + +import java.awt.Font; +import javax.swing.LookAndFeel; +import javax.swing.plaf.FontUIResource; +import javax.swing.plaf.metal.DefaultMetalTheme; +import javax.swing.plaf.metal.MetalLookAndFeel; + +public class bug4306431 { + static final Font FONT = new Font(Font.MONOSPACED, Font.ITALIC, 24); + + public static void main(String[] argv) throws Exception { + MetalLookAndFeel.setCurrentTheme(new TestMetalTheme()); + LookAndFeel laf = new MetalLookAndFeel(); + Font font = laf.getDefaults().getFont("List.font"); + if (!font.equals(FONT)) { + throw new RuntimeException("Failed: font wasn't customized"); + } + } + + static class TestMetalTheme extends DefaultMetalTheme { + public FontUIResource getControlTextFont() { + return new FontUIResource(FONT); + } + } +} diff --git a/test/jdk/javax/swing/LookAndFeel/bug4736093.java b/test/jdk/javax/swing/LookAndFeel/bug4736093.java new file mode 100644 index 00000000000..522eb98ab3e --- /dev/null +++ b/test/jdk/javax/swing/LookAndFeel/bug4736093.java @@ -0,0 +1,167 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4736093 + * @requires (os.family == "windows") + * @summary REGRESSION: Menu and controls shortcuts are not visible in Win L&F in jdk1.4.1 + * @modules java.desktop/com.sun.java.swing.plaf.windows + * @key headful + */ + +import java.awt.Robot; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.MenuElement; +import javax.swing.MenuSelectionManager; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; + +import com.sun.java.swing.plaf.windows.WindowsLookAndFeel; + +public class bug4736093 { + static volatile boolean passed = true; + static volatile boolean done = false; + static volatile boolean winlaf = true; + static JFrame mainFrame = null; + static Robot robo; + + public static void main(String args[]) throws Exception { + try { + robo = new Robot(); + + SwingUtilities.invokeAndWait(() -> { + try { + UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); + } catch (Exception ex) { + winlaf = false; + } + + if (winlaf && WindowsLookAndFeel.isMnemonicHidden()) { + mainFrame = new JFrame("Bug 4736093"); + mainFrame.addWindowListener(new TestStateListener()); + mainFrame.setSize(200, 400); + mainFrame.setLocationRelativeTo(null); + mainFrame.setVisible(true); + } else { + System.out.println("Test is not for this system. Passed."); + } + }); + + robo.waitForIdle(); + robo.delay(1000); + + if (!passed) { + throw new RuntimeException("Test failed."); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (mainFrame != null) { + mainFrame.dispose(); + } + }); + } + } + + public static void addMenuBar() { + JMenuBar mbar = new JMenuBar(); + JMenu menu = new JMenu("File"); + for (int i = 1; i < 5; i++) { + menu.add(new JMenuItem("Menu Item " + i)); + } + mbar.add(menu); + mainFrame.setJMenuBar(mbar); + } + + + public static void checkForMnemonics(boolean expected) { + if (expected != WindowsLookAndFeel.isMnemonicHidden()) { + passed = false; + } + } + + public static class TestStateListener extends WindowAdapter { + public void windowOpened(WindowEvent ev) { + try { + new Thread(new RobotThread()).start(); + } catch (Exception ex) { + throw new RuntimeException("Thread Exception"); + } + } + } + + public static class RobotThread implements Runnable { + public void run() { + MenuElement[] path; + int altKey = java.awt.event.KeyEvent.VK_ALT; + robo.setAutoDelay(3000); // 3 seconds delay + robo.waitForIdle(); + + robo.keyPress(altKey); + robo.delay(1000); + + checkForMnemonics(false); // mnemonics should appear on press + robo.keyRelease(altKey); + robo.delay(1000); + + checkForMnemonics(true); // and disappear on release + robo.keyPress(java.awt.event.KeyEvent.VK_ESCAPE); + robo.keyRelease(java.awt.event.KeyEvent.VK_ESCAPE); + robo.delay(1000); + + addMenuBar(); + robo.delay(1000); + + robo.keyPress(altKey); + robo.delay(1000); + + checkForMnemonics(false); // mnemonics should appear on press + robo.keyRelease(altKey); + robo.delay(1000); + + checkForMnemonics(false); // and stay appeared in selected menu + path = MenuSelectionManager.defaultManager().getSelectedPath(); + if (path.length == 0) { + passed = false; // menu should be selected + } + robo.delay(1000); + + robo.keyPress(altKey); + robo.delay(1000); + + checkForMnemonics(true); // and only now disappear + path = MenuSelectionManager.defaultManager().getSelectedPath(); + if (path.length != 0) { + passed = false; // menu should be deselected + } + robo.keyRelease(altKey); + done = true; + robo.delay(1000); + } + } +} diff --git a/test/jdk/javax/swing/LookAndFeel/isJavaLAFLockedCorrectly.java b/test/jdk/javax/swing/LookAndFeel/isJavaLAFLockedCorrectly.java new file mode 100644 index 00000000000..70e21837bac --- /dev/null +++ b/test/jdk/javax/swing/LookAndFeel/isJavaLAFLockedCorrectly.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4236213 + * @summary Regression test isJavaLAFLockedCorrectly.java Failing with JDK-1.2.2-R + */ + +import javax.swing.LookAndFeel; + +public class isJavaLAFLockedCorrectly { + public static void main(String[] args) { + System.out.println(" === isJavaLAFLockedCorrectly === "); + + LookAndFeel newJLF; + try { + // try to make a version of the JLF + Class jlfClass = Class.forName("javax.swing.plaf.metal.MetalLookAndFeel"); + newJLF = (LookAndFeel) (jlfClass.newInstance()); + } catch (Exception e) { + // if any of these things didn't work, throw an exception + throw new RuntimeException("JLF not correctly (un)locked " + + "- Class files probably missing"); + } + + // see if the JLF is supported here + // it sure better be as it's supposed to be supported everywhere + if (newJLF.isSupportedLookAndFeel() == true) { + System.out.println("\t JLF correctly locked"); + } else { + throw new RuntimeException("JLF not correctly (un)locked"); + } + } +} diff --git a/test/jdk/javax/swing/LookAndFeel/isMultiLAFLockedCorrectly.java b/test/jdk/javax/swing/LookAndFeel/isMultiLAFLockedCorrectly.java new file mode 100644 index 00000000000..26596616fb1 --- /dev/null +++ b/test/jdk/javax/swing/LookAndFeel/isMultiLAFLockedCorrectly.java @@ -0,0 +1,53 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + */ + +import javax.swing.LookAndFeel; + +public class isMultiLAFLockedCorrectly { + public static void main(String[] args) { + System.out.println(" === isMultiLAFLockedCorrectly === "); + + LookAndFeel newMulti; + try { + // try to make a version of the Multi L&F + Class multiClass = Class.forName("javax.swing.plaf.multi.MultiLookAndFeel"); + newMulti = (LookAndFeel) (multiClass.newInstance()); + } catch (Exception e) { + // if any of these things didn't work, throw an exception + throw new RuntimeException("Multi L&F not correctly locked " + + "- Class files probably missing"); + } + + // see if the Multi L&F is supported here + // it sure better be as it's supposed to be supported everywhere + if (newMulti.isSupportedLookAndFeel() == true) { + System.out.println("\t Multi L&F correctly locked"); + } else { + throw new RuntimeException("Multi L&F not correctly locked"); + } + } +} diff --git a/test/jdk/javax/swing/MetalInternalFrameTitlePane/bug4221007.java b/test/jdk/javax/swing/MetalInternalFrameTitlePane/bug4221007.java new file mode 100644 index 00000000000..6bcce0d3712 --- /dev/null +++ b/test/jdk/javax/swing/MetalInternalFrameTitlePane/bug4221007.java @@ -0,0 +1,38 @@ +/* + * Copyright (c) 1999, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4221007 + * @summary Tests whether MetalInternalFrameTitlePane is public + */ + +import javax.swing.JInternalFrame; +import javax.swing.plaf.metal.MetalInternalFrameTitlePane; + +public class bug4221007 { + public static void main(String[] args) { + MetalInternalFrameTitlePane mitftp = + new MetalInternalFrameTitlePane(new JInternalFrame()); + } +} diff --git a/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java b/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java index afa28ad6bec..a3ddbac30dd 100644 --- a/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java +++ b/test/jdk/javax/swing/PopupFactory/6276087/NonOpaquePopupMenuTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -25,71 +25,88 @@ * @test * @key headful * @bug 6276087 - * @author Romain Guy * @summary Tests opacity of a popup menu. */ -import java.awt.*; -import java.awt.event.*; - -import javax.swing.*; +import java.awt.Point; +import java.awt.Dimension; +import java.awt.Robot; +import java.awt.event.InputEvent; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.SwingUtilities; import static javax.swing.UIManager.LookAndFeelInfo; import static javax.swing.UIManager.getInstalledLookAndFeels; import static javax.swing.UIManager.setLookAndFeel; -public class NonOpaquePopupMenuTest extends JFrame { +public class NonOpaquePopupMenuTest { private static JMenu fileMenu; + private static JFrame frame; private static final String AQUALAF="com.apple.laf.AquaLookAndFeel"; + private volatile static Point p; + private volatile static Dimension size; - public NonOpaquePopupMenuTest() { - getContentPane().setBackground(java.awt.Color.RED); + private static void createUI() { + frame = new JFrame(); + frame.getContentPane().setBackground(java.awt.Color.RED); JMenuBar menuBar = new JMenuBar(); fileMenu = new JMenu("File"); JMenuItem menuItem = new JMenuItem("New"); menuBar.add(fileMenu); - setJMenuBar(menuBar); + frame.setJMenuBar(menuBar); fileMenu.add(menuItem); fileMenu.getPopupMenu().setOpaque(false); - setSize(new Dimension(640, 480)); - setLocationRelativeTo(null); - setVisible(true); + frame.setSize(new Dimension(640, 480)); + frame.setLocationRelativeTo(null); + frame.setVisible(true); } public static void main(String[] args) throws Throwable { LookAndFeelInfo[] lookAndFeelInfoArray = getInstalledLookAndFeels(); + Robot robot = new Robot(); + robot.setAutoDelay(100); for (LookAndFeelInfo lookAndFeelInfo : lookAndFeelInfoArray) { - System.out.println(lookAndFeelInfo.getClassName()); - if ( AQUALAF == lookAndFeelInfo.getClassName()) { - System.out.println("This test scenario is not applicable for" + - " Aqua LookandFeel and hence skipping the validation"); - continue; - } - setLookAndFeel(lookAndFeelInfo.getClassName()); - Robot robot = new Robot(); - robot.setAutoDelay(250); - - SwingUtilities.invokeAndWait(new Runnable() { - - @Override - public void run() { - new NonOpaquePopupMenuTest(); + try { + System.out.println(lookAndFeelInfo.getClassName()); + if ( AQUALAF == lookAndFeelInfo.getClassName()) { + System.out.println("This test scenario is not applicable for" + + " Aqua LookandFeel and hence skipping the validation"); + continue; } - }); + robot.delay(1000); + setLookAndFeel(lookAndFeelInfo.getClassName()); + + SwingUtilities.invokeAndWait(() -> createUI()); - robot.waitForIdle(); + robot.waitForIdle(); + robot.delay(1000); - Point p = getMenuClickPoint(); - robot.mouseMove(p.x, p.y); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.mouseRelease(InputEvent.BUTTON1_MASK); + SwingUtilities.invokeAndWait(() -> { + p = fileMenu.getLocationOnScreen(); + size = fileMenu.getSize(); + }); + robot.mouseMove(p.x + size.width / 2, p.y + size.height / 2); + robot.waitForIdle(); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - robot.waitForIdle(); + robot.waitForIdle(); - if (isParentOpaque()) { - throw new RuntimeException("Popup menu parent is opaque"); + if (isParentOpaque()) { + throw new RuntimeException("Popup menu parent is opaque"); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (frame != null) { + frame.dispose(); + } + }); } } } @@ -107,23 +124,4 @@ public void run() { return result[0]; } - - private static Point getMenuClickPoint() throws Exception { - final Point[] result = new Point[1]; - - SwingUtilities.invokeAndWait(new Runnable() { - - @Override - public void run() { - Point p = fileMenu.getLocationOnScreen(); - Dimension size = fileMenu.getSize(); - - result[0] = new Point(p.x + size.width / 2, - p.y + size.height / 2); - } - }); - - return result[0]; - - } } diff --git a/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java b/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java index 4ea1f48ae7a..77fac43d262 100644 --- a/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java +++ b/test/jdk/javax/swing/ProgressMonitor/ProgressMonitorEscapeKeyPress.java @@ -29,66 +29,64 @@ * @run main ProgressMonitorEscapeKeyPress */ -import java.awt.AWTException; -import java.awt.EventQueue; -import java.awt.Robot; -import java.awt.event.KeyEvent; + import javax.swing.JFrame; import javax.swing.ProgressMonitor; import javax.swing.SwingUtilities; +import java.awt.Robot; +import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; public class ProgressMonitorEscapeKeyPress { + static volatile int counter = 0; static ProgressMonitor monitor; - static int counter = 0; - static TestThread robotThread; + static TestThread testThread; static JFrame frame; + static CountDownLatch progressLatch; + static Robot robot; public static void main(String[] args) throws Exception { - - createTestUI(); - - monitor = new ProgressMonitor(frame, "Progress", null, 0, 100); - - robotThread = new TestThread(); - robotThread.start(); - - for (counter = 0; counter <= 100; counter += 10) { - Thread.sleep(1000); - - EventQueue.invokeAndWait(new Runnable() { - @Override - public void run() { - if (!monitor.isCanceled()) { - monitor.setProgress(counter); - System.out.println("Progress bar is in progress"); - } - } - }); - - if (monitor.isCanceled()) { - break; + try { + progressLatch = new CountDownLatch(20); + createTestUI(); + robot = new Robot(); + robot.setAutoDelay(50); + robot.setAutoWaitForIdle(true); + testThread = new TestThread(); + testThread.start(); + Thread.sleep(100); + if (progressLatch.await(15, TimeUnit.SECONDS)) { + System.out.println("Progress monitor completed 20%, lets press Esc..."); + robot.keyPress(KeyEvent.VK_ESCAPE); + robot.keyRelease(KeyEvent.VK_ESCAPE); + System.out.println("ESC pressed...."); + } else { + System.out.println("Failure : No status available from Progress monitor..."); + throw new RuntimeException( + "Can't get the status from Progress monitor even after waiting too long.."); } - } - - disposeTestUI(); - if (counter >= monitor.getMaximum()) { - throw new RuntimeException("Escape key did not cancel the ProgressMonitor"); + if (counter >= monitor.getMaximum()) { + throw new RuntimeException("Escape key did not cancel the ProgressMonitor"); + } + System.out.println("Test Passed..."); + } finally { + disposeTestUI(); } } - private static void createTestUI() throws Exception { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - frame = new JFrame("Test"); - frame.setSize(300, 300); - frame.setLocationByPlatform(true); - frame.setVisible(true); - }}); - } + private static void createTestUI() throws Exception { + SwingUtilities.invokeAndWait(() -> { + frame = new JFrame("Test"); + frame.setSize(300, 300); + monitor = new ProgressMonitor(frame, "Progress", "1", 0, 100); + frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); + frame.setLocationByPlatform(true); + }); + } private static void disposeTestUI() throws Exception { @@ -100,26 +98,25 @@ private static void disposeTestUI() throws Exception { class TestThread extends Thread { - - Robot testRobot; - - TestThread() throws AWTException { - super(); - testRobot = new Robot(); - } - @Override public void run() { - try { - // Sleep for 5 seconds - so that the ProgressMonitor starts - Thread.sleep(5000); - - // Press and release Escape key - testRobot.keyPress(KeyEvent.VK_ESCAPE); - testRobot.delay(20); - testRobot.keyRelease(KeyEvent.VK_ESCAPE); - } catch (InterruptedException ex) { - throw new RuntimeException("Exception in TestThread"); + System.out.println("TestThread started........."); + for (ProgressMonitorEscapeKeyPress.counter = 0; + ProgressMonitorEscapeKeyPress.counter <= 100; + ProgressMonitorEscapeKeyPress.counter += 1) { + ProgressMonitorEscapeKeyPress.robot.delay(100); + ProgressMonitor monitor = ProgressMonitorEscapeKeyPress.monitor; + if (!monitor.isCanceled()) { + monitor.setNote("" + ProgressMonitorEscapeKeyPress.counter); + monitor.setProgress(ProgressMonitorEscapeKeyPress.counter); + ProgressMonitorEscapeKeyPress.progressLatch.countDown(); + System.out.println("Progress bar is in progress....." + + ProgressMonitorEscapeKeyPress.counter + "%"); + } + if (monitor.isCanceled()) { + System.out.println("$$$$$$$$$$$$$$$ Monitor canceled"); + break; + } } } } diff --git a/test/jdk/javax/swing/RootPaneChecking/RootPaneChecking.java b/test/jdk/javax/swing/RootPaneChecking/RootPaneChecking.java new file mode 100644 index 00000000000..52946b714e2 --- /dev/null +++ b/test/jdk/javax/swing/RootPaneChecking/RootPaneChecking.java @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4753342 + * @key headful + * @summary Makes sure add/remove/setLayout redirect to the contentpane + */ + +import java.awt.Container; +import java.awt.GridLayout; +import java.awt.LayoutManager; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JInternalFrame; +import javax.swing.JWindow; +import javax.swing.RootPaneContainer; +import javax.swing.SwingUtilities; + +public class RootPaneChecking { + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(() -> { + MyJFrame frame = new MyJFrame(); + frame.setTitle("RootPaneChecking"); + checkRootPaneCheckingEnabled(frame); + frame.setRootPaneCheckingEnabled(false); + checkRootPaneCheckingDisabled(frame); + + MyJWindow window = new MyJWindow(); + checkRootPaneCheckingEnabled(window); + window.setRootPaneCheckingEnabled(false); + checkRootPaneCheckingDisabled(window); + + MyJDialog dialog = new MyJDialog(); + checkRootPaneCheckingEnabled(dialog); + dialog.setRootPaneCheckingEnabled(false); + checkRootPaneCheckingDisabled(dialog); + + MyJInternalFrame iframe = new MyJInternalFrame(); + checkRootPaneCheckingEnabled(iframe); + iframe.setRootPaneCheckingEnabled(false); + checkRootPaneCheckingDisabled(iframe); + }); + } + + private static void checkRootPaneCheckingEnabled(RootPaneContainer rpc) { + Container parent = (Container) rpc; + Container cp = rpc.getContentPane(); + // Test add + JButton button = new JButton("RootPaneChecking"); + parent.add(button); + if (button.getParent() != cp) { + throw new RuntimeException("Add parent mismatch, want: " + + cp + " got " + button.getParent()); + } + + // Test remove + parent.remove(button); + if (button.getParent() != null) { + throw new RuntimeException("Remove mismatch, want null got " + + button.getParent()); + } + + // Test setLayout + LayoutManager manager = new GridLayout(); + parent.setLayout(manager); + if (manager != cp.getLayout()) { + throw new RuntimeException("LayoutManager mismatch, want: " + + manager + " got " + cp.getLayout()); + } + } + + private static void checkRootPaneCheckingDisabled(RootPaneContainer rpc) { + Container parent = (Container) rpc; + Container cp = rpc.getContentPane(); + + // Test add + JButton button = new JButton("RootPaneChecking"); + parent.add(button); + if (button.getParent() != parent) { + throw new RuntimeException("Add parent mismatch, want: " + + parent + " got " + button.getParent()); + } + + // Test setLayout + LayoutManager manager = new GridLayout(); + parent.setLayout(manager); + if (manager != parent.getLayout()) { + throw new RuntimeException("LayoutManager mismatch, want: " + + manager + " got " + cp.getLayout()); + } + } + + static class MyJFrame extends JFrame { + public void setRootPaneCheckingEnabled(boolean x) { + super.setRootPaneCheckingEnabled(x); + } + } + + static class MyJWindow extends JWindow { + public void setRootPaneCheckingEnabled(boolean x) { + super.setRootPaneCheckingEnabled(x); + } + } + + static class MyJDialog extends JDialog { + public void setRootPaneCheckingEnabled(boolean x) { + super.setRootPaneCheckingEnabled(x); + } + } + + static class MyJInternalFrame extends JInternalFrame { + public void setRootPaneCheckingEnabled(boolean x) { + super.setRootPaneCheckingEnabled(x); + } + } +} diff --git a/test/jdk/javax/swing/SpringLayout/bug4756178.java b/test/jdk/javax/swing/SpringLayout/bug4756178.java new file mode 100644 index 00000000000..037d7683a4a --- /dev/null +++ b/test/jdk/javax/swing/SpringLayout/bug4756178.java @@ -0,0 +1,93 @@ +/* + * Copyright (c) 2002, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4756178 + * @summary SpringLayout:applyDefaults() discards size information when right-aligning. + * @key headful + */ + +import java.awt.Dimension; +import java.awt.Robot; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.Spring; +import javax.swing.SpringLayout; +import javax.swing.SwingUtilities; + +public class bug4756178 { + static JFrame fr; + static JButton bt; + static volatile Dimension buttonPreferredSize; + static volatile Dimension actualSize; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4756178"); + JPanel p = (JPanel) fr.getContentPane(); + SpringLayout layout = new SpringLayout(); + p.setLayout(layout); + + SpringLayout.Constraints cc = new SpringLayout.Constraints(); + cc.setConstraint("East", + Spring.sum(Spring.constant(-20), + layout.getConstraint("East", p))); + cc.setConstraint("South", + Spring.sum(Spring.constant(-20), + layout.getConstraint("South", p))); + + bt = new JButton(); + + buttonPreferredSize = new Dimension(20, 20); + bt.setPreferredSize(buttonPreferredSize); + p.add(bt, cc); + + fr.setSize(200, 200); + fr.setLocationRelativeTo(null); + fr.setVisible(true); + }); + + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + actualSize = bt.getSize(); + }); + + if (!buttonPreferredSize.equals(actualSize)) { + throw new RuntimeException("Button size is " + actualSize + + ", should be " + buttonPreferredSize); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff --git a/test/jdk/javax/swing/SpringLayout/bug4803649.java b/test/jdk/javax/swing/SpringLayout/bug4803649.java new file mode 100644 index 00000000000..8b3c08548e8 --- /dev/null +++ b/test/jdk/javax/swing/SpringLayout/bug4803649.java @@ -0,0 +1,91 @@ +/* + * Copyright (c) 2003, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4803649 + * @summary setWidth() doesn't work on the container in a SpringLayout + * @key headful + */ + +import java.awt.Dimension; +import java.awt.Robot; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.Spring; +import javax.swing.SpringLayout; +import javax.swing.SwingUtilities; + +public class bug4803649 { + static JFrame fr; + static JPanel panel; + + public static void main(String[] args) throws Exception { + try { + SwingUtilities.invokeAndWait(() -> { + fr = new JFrame("bug4803649"); + + panel = new JPanel(); + SpringLayout layout = new SpringLayout(); + panel.setLayout(layout); + + JTextArea textArea = new JTextArea("asasddsa"); + textArea.setPreferredSize(new Dimension(200, 200)); + panel.add(textArea); + SpringLayout.Constraints cCons = layout.getConstraints(textArea); + cCons.setX(Spring.constant(10)); + cCons.setY(Spring.constant(10)); + + SpringLayout.Constraints pCons = layout.getConstraints(panel); + pCons.setWidth(Spring.sum(Spring.constant(10), + cCons.getConstraint("East"))); + pCons.setHeight(Spring.sum(Spring.constant(10), + cCons.getConstraint("South"))); + + fr.getContentPane().add(panel); + + fr.setLocationRelativeTo(null); + fr.pack(); + fr.setVisible(true); + }); + + Robot r = new Robot(); + r.waitForIdle(); + r.delay(1000); + + SwingUtilities.invokeAndWait(() -> { + Dimension d = panel.getSize(); + if (d.width < 220 || d.height < 220) { + throw new RuntimeException("JPanel with the SpringLayout is too small"); + } + }); + } finally { + SwingUtilities.invokeAndWait(() -> { + if (fr != null) { + fr.dispose(); + } + }); + } + } +} diff --git a/test/jdk/javax/swing/ToolTipManager/bug5078214.java b/test/jdk/javax/swing/ToolTipManager/bug5078214.java new file mode 100644 index 00000000000..cf4228a6258 --- /dev/null +++ b/test/jdk/javax/swing/ToolTipManager/bug5078214.java @@ -0,0 +1,136 @@ +/* + * Copyright (c) 2004, 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 5078214 + * @key headful + * @summary ToolTip is shown partially when the application is near the bottom of screen. + * @library /test/lib + * @build jtreg.SkippedException + * @run main bug5078214 + */ + +import java.awt.BorderLayout; +import java.awt.GraphicsConfiguration; +import java.awt.GraphicsDevice; +import java.awt.GraphicsEnvironment; +import java.awt.Insets; +import java.awt.Point; +import java.awt.Rectangle; +import java.awt.Robot; +import java.awt.Toolkit; +import java.awt.Window; +import java.awt.event.MouseEvent; +import javax.swing.JButton; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.ToolTipManager; + +import jtreg.SkippedException; + +public class bug5078214 { + static volatile boolean passed = false; + + static volatile JFrame mainFrame; + static volatile Rectangle bounds; + static volatile Insets insets; + static Robot robot; + + public static void main(String[] args) throws Exception { + try { + if (getGraphicsConfig() == null) { + throw new SkippedException("We need at least one screen " + + "with the taskbar at the bottom position."); + } + bounds = getGraphicsConfig().getBounds(); + + SwingUtilities.invokeAndWait(() -> { + mainFrame = new JFrame("bug5078214"); + mainFrame.setLayout(new BorderLayout()); + mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + JButton button = new JButton("Button with tooltip") { + public Point getToolTipLocation(MouseEvent ev) { + return new Point(100, 100); + } + }; + mainFrame.add(button, BorderLayout.CENTER); + button.setToolTipText("ToolTip for this button"); + + // Position frame + mainFrame.setSize(200, 200); + int x = bounds.x + 200; + int y = bounds.y + bounds.height - insets.bottom - 100; + mainFrame.setLocation(x, y); + mainFrame.setVisible(true); + }); + + robot = new Robot(); + robot.waitForIdle(); + robot.delay(1000); + + test(bounds, insets); + + if (!passed) { + throw new RuntimeException("ToolTip shown outside of the visible area. Test failed."); + } + } finally { + SwingUtilities.invokeAndWait(() -> { + if (mainFrame != null) { + mainFrame.dispose(); + } + }); + } + } + + public static void test(Rectangle b, Insets i) throws Exception { + SwingUtilities.invokeAndWait(() -> { + ToolTipManager.sharedInstance().setLightWeightPopupEnabled(false); + ToolTipManager.sharedInstance().setInitialDelay(100); + }); + + robot.mouseMove(b.x + 300, b.y + b.height - i.bottom - 10); + robot.delay(500); + Window[] ow = mainFrame.getOwnedWindows(); + if (ow == null || ow.length < 1) { + throw new RuntimeException("No owned windows for JFrame - no tooltip shown?"); + } + + Window ttwnd = ow[0]; + int wy = ttwnd.getBounds().y + ttwnd.getBounds().height - 1; + passed = wy < (b.y + b.height - i.bottom); + } + + public static GraphicsConfiguration getGraphicsConfig() { + GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment() + .getScreenDevices(); + for (GraphicsDevice device : devices) { + GraphicsConfiguration config = device.getDefaultConfiguration(); + insets = Toolkit.getDefaultToolkit().getScreenInsets(config); + if (insets.bottom != 0) { + return config; + } + } + return null; + } +} diff --git a/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java b/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java index 18f78d88f52..e495c929891 100644 --- a/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java +++ b/test/jdk/javax/swing/plaf/basic/BasicMenuUI/4983388/bug4983388.java @@ -26,28 +26,41 @@ * @key headful * @bug 4983388 8015600 * @summary shortcuts on menus do not work on JDS - * @author Oleg Mokhovikov * @library ../../../../regtesthelpers * @build Util * @run main bug4983388 */ -import java.awt.*; -import javax.swing.*; -import javax.swing.event.MenuListener; -import javax.swing.event.MenuEvent; +import java.awt.Robot; import java.awt.event.KeyEvent; +import java.util.concurrent.CountDownLatch; + +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.UnsupportedLookAndFeelException; +import javax.swing.event.MenuEvent; +import javax.swing.event.MenuListener; + +import static java.util.concurrent.TimeUnit.SECONDS; public class bug4983388 { - static volatile boolean bMenuSelected = false; static JFrame frame; + private static final CountDownLatch menuSelected = new CountDownLatch(1); + private static class TestMenuListener implements MenuListener { + @Override public void menuCanceled(MenuEvent e) {} + @Override public void menuDeselected(MenuEvent e) {} + + @Override public void menuSelected(MenuEvent e) { System.out.println("menuSelected"); - bMenuSelected = true; + menuSelected.countDown(); } } @@ -56,28 +69,24 @@ private static void createAndShowGUI() { JMenu menu = new JMenu("File"); menu.setMnemonic('F'); menuBar.add(menu); - frame = new JFrame(); + menu.addMenuListener(new TestMenuListener()); + + frame = new JFrame("bug4983388"); frame.setJMenuBar(menuBar); frame.setLocationRelativeTo(null); - frame.pack(); + frame.setSize(250, 100); frame.setVisible(true); - MenuListener listener = new TestMenuListener(); - menu.addMenuListener(listener); } public static void main(String[] args) throws Exception { - try { UIManager.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel"); } catch (UnsupportedLookAndFeelException | ClassNotFoundException ex) { - System.err.println("GTKLookAndFeel is not supported on this platform. Using defailt LaF for this platform."); + System.err.println("GTKLookAndFeel is not supported on this platform. " + + "Using default LaF for this platform."); } - SwingUtilities.invokeAndWait(new Runnable() { - public void run() { - createAndShowGUI(); - } - }); + SwingUtilities.invokeAndWait(bug4983388::createAndShowGUI); Robot robot = new Robot(); robot.setAutoDelay(50); @@ -85,13 +94,13 @@ public void run() { robot.delay(500); Util.hitMnemonics(robot, KeyEvent.VK_F); - robot.waitForIdle(); - robot.delay(500); - - SwingUtilities.invokeAndWait(() -> frame.dispose()); - if (!bMenuSelected) { - throw new RuntimeException("shortcuts on menus do not work"); + try { + if (!menuSelected.await(1, SECONDS)) { + throw new RuntimeException("shortcuts on menus do not work"); + } + } finally { + SwingUtilities.invokeAndWait(frame::dispose); } } } diff --git a/test/jdk/javax/swing/plaf/basic/BasicSliderUI/bug4419255.java b/test/jdk/javax/swing/plaf/basic/BasicSliderUI/bug4419255.java new file mode 100644 index 00000000000..eb23901f60d --- /dev/null +++ b/test/jdk/javax/swing/plaf/basic/BasicSliderUI/bug4419255.java @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2001, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import javax.swing.JColorChooser; +import javax.swing.UIManager; + +import jtreg.SkippedException; + +/* + * @test + * @bug 4419255 + * @library /java/awt/regtesthelpers /test/lib + * @build PassFailJFrame + * @summary Tests if Metal Slider's thumb isn't clipped + * @run main/manual bug4419255 + */ + +public class bug4419255 { + + public static void main(String[] args) throws Exception { + + // ColorChooser UI design is different for GTK L&F. + // There is no RGB tab available for GTK L&F, skip the testing. + if (UIManager.getLookAndFeel().getName().contains("GTK")) { + throw new SkippedException("Test not applicable for GTK L&F"); + } + String instructions = """ + Choose RGB tab. If sliders' thumbs are painted correctly + (top is not clipped, black line is visible), + then test passed. Otherwise it failed."""; + + PassFailJFrame.builder() + .title("bug4419255") + .instructions(instructions) + .columns(40) + .testUI(bug4419255::createColorChooser) + .build() + .awaitAndCheck(); + } + + private static JColorChooser createColorChooser() { + return new JColorChooser(Color.BLUE); + } +} diff --git a/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java b/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java index 6b2331f390d..a0a7269b205 100644 --- a/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java +++ b/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/HidingSelectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,10 +21,17 @@ * questions. */ -import javax.swing.*; -import java.awt.*; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JTextField; +import javax.swing.MenuSelectionManager; +import javax.swing.SwingUtilities; +import java.awt.FlowLayout; +import java.awt.Point; +import java.awt.Robot; import java.awt.event.InputEvent; -import java.awt.image.BufferedImage; /** * @test @@ -39,7 +46,6 @@ public class HidingSelectionTest { private static JTextField field1; private static JTextField field2; private static JFrame frame; - private static Rectangle bounds; private static JMenu menu; private static JTextField anotherWindow; private static Point menuLoc; @@ -67,17 +73,9 @@ public static void main(String[] args) throws Exception { Robot robot = new Robot(); robot.waitForIdle(); robot.delay(200); - SwingUtilities.invokeAndWait(() -> { - bounds = field2.getBounds(); - bounds.setLocation(field2.getLocationOnScreen()); - }); - BufferedImage nosel = robot.createScreenCapture(bounds); SwingUtilities.invokeAndWait(field2::requestFocus); SwingUtilities.invokeAndWait(field2::selectAll); - robot.waitForIdle(); - robot.delay(200); - BufferedImage sel = robot.createScreenCapture(bounds); SwingUtilities.invokeAndWait(() -> { menuLoc = menu.getLocationOnScreen(); @@ -89,7 +87,7 @@ public static void main(String[] args) throws Exception { robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); robot.waitForIdle(); robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), sel)) { + if (!field2.getCaret().isSelectionVisible()) { throw new RuntimeException("Test fails: menu hides selection"); } @@ -98,7 +96,7 @@ public static void main(String[] args) throws Exception { SwingUtilities.invokeAndWait(field1::requestFocus); robot.waitForIdle(); robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), nosel)) { + if (field2.getCaret().isSelectionVisible()) { throw new RuntimeException( "Test fails: focus lost doesn't hide selection"); } @@ -119,35 +117,12 @@ public static void main(String[] args) throws Exception { SwingUtilities.invokeAndWait(anotherWindow::requestFocus); robot.waitForIdle(); robot.delay(200); - if (biEqual(robot.createScreenCapture(bounds), nosel)) { + if (!field2.getCaret().isSelectionVisible()) { throw new RuntimeException( "Test fails: switch window hides selection"); } - SwingUtilities.invokeAndWait(anotherWindow::selectAll); - robot.waitForIdle(); - robot.delay(200); - if (biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException( - "Test fails: selection ownership is lost selection is shown"); - } - SwingUtilities.invokeLater(frame2::dispose); SwingUtilities.invokeLater(frame::dispose); } - - static boolean biEqual(BufferedImage i1, BufferedImage i2) { - if (i1.getWidth() == i2.getWidth() && - i1.getHeight() == i2.getHeight()) { - for (int x = 0; x < i1.getWidth(); x++) { - for (int y = 0; y < i1.getHeight(); y++) { - if (i1.getRGB(x, y) != i2.getRGB(x, y)) { - return false; - } - } - } - return true; - } - return false; - } } diff --git a/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java b/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java index c3cdafe8794..893afab5f4d 100644 --- a/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java +++ b/test/jdk/javax/swing/text/DefaultCaret/HidingSelection/MultiSelectionTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,10 +21,17 @@ * questions. */ -import javax.swing.*; -import java.awt.*; +import javax.swing.JFrame; +import javax.swing.JMenu; +import javax.swing.JMenuBar; +import javax.swing.JMenuItem; +import javax.swing.JTextField; +import javax.swing.MenuSelectionManager; +import javax.swing.SwingUtilities; +import java.awt.FlowLayout; +import java.awt.Point; +import java.awt.Robot; import java.awt.event.InputEvent; -import java.awt.image.BufferedImage; /** * @test @@ -40,131 +47,113 @@ public class MultiSelectionTest { private static JTextField field1; private static JTextField field2; private static JFrame frame; - private static Rectangle bounds; private static JMenu menu; private static JTextField anotherWindow; private static Point menuLoc; private static JFrame frame2; public static void main(String[] args) throws Exception { - SwingUtilities.invokeAndWait(() -> { - frame = new JFrame(); - field1 = new JTextField("field1 "); - field2 = new JTextField("field2 "); - field1.setEditable(false); - field2.setEditable(false); - frame.getContentPane().setLayout(new FlowLayout()); - frame.getContentPane().add(field1); - frame.getContentPane().add(field2); - JMenuBar menuBar = new JMenuBar(); - menu = new JMenu("menu"); - menu.add(new JMenuItem("item")); - menuBar.add(menu); - frame.setJMenuBar(menuBar); - frame.pack(); - frame.setVisible(true); - }); + try { + SwingUtilities.invokeAndWait(() -> { + frame = new JFrame(); + field1 = new JTextField("field1 "); + field2 = new JTextField("field2 "); + field1.setEditable(false); + field2.setEditable(false); + frame.getContentPane().setLayout(new FlowLayout()); + frame.getContentPane().add(field1); + frame.getContentPane().add(field2); + JMenuBar menuBar = new JMenuBar(); + menu = new JMenu("menu"); + menu.add(new JMenuItem("item")); + menuBar.add(menu); + frame.setJMenuBar(menuBar); + frame.pack(); + frame.setVisible(true); + }); - Robot robot = new Robot(); - robot.waitForIdle(); - robot.delay(200); - SwingUtilities.invokeAndWait(() -> { - bounds = field2.getBounds(); - bounds.setLocation(field2.getLocationOnScreen()); - }); - BufferedImage nosel = robot.createScreenCapture(bounds); + Robot robot = new Robot(); + robot.waitForIdle(); + robot.delay(200); - SwingUtilities.invokeAndWait(field2::requestFocus); - SwingUtilities.invokeAndWait(field2::selectAll); - robot.waitForIdle(); - robot.delay(200); - BufferedImage sel = robot.createScreenCapture(bounds); + SwingUtilities.invokeAndWait(field2::requestFocus); + SwingUtilities.invokeAndWait(field2::selectAll); + robot.waitForIdle(); + robot.delay(200); - SwingUtilities.invokeAndWait(() -> { - menuLoc = menu.getLocationOnScreen(); - menuLoc.translate(10, 10); - }); - robot.mouseMove(menuLoc.x, menuLoc.y); - robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); - robot.delay(50); - robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); - robot.waitForIdle(); - robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException("Test fails: menu hides selection"); - } - - SwingUtilities.invokeAndWait( - MenuSelectionManager.defaultManager()::clearSelectedPath); - SwingUtilities.invokeAndWait(field1::requestFocus); - robot.waitForIdle(); - robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException( - "Test fails: focus lost hides single selection"); - } - - SwingUtilities.invokeAndWait(field1::selectAll); - robot.waitForIdle(); - robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), nosel)) { - throw new RuntimeException( - "Test fails: focus lost doesn't hide selection upon multi selection"); - } + SwingUtilities.invokeAndWait(() -> { + menuLoc = menu.getLocationOnScreen(); + menuLoc.translate(10, 10); + }); + robot.mouseMove(menuLoc.x, menuLoc.y); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.delay(50); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.delay(200); + if (!field2.getCaret().isSelectionVisible()) { + throw new RuntimeException("Test fails: menu hides selection"); + } - SwingUtilities.invokeAndWait(field2::requestFocus); - robot.waitForIdle(); - robot.delay(200); - if (!biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException( - "Test fails: focus gain hides selection upon multi selection"); - } + SwingUtilities.invokeAndWait( + MenuSelectionManager.defaultManager()::clearSelectedPath); + SwingUtilities.invokeAndWait(field1::requestFocus); + robot.waitForIdle(); + robot.delay(200); + if (field2.getSelectedText() == null || field2.getSelectedText().length() == 0) { + throw new RuntimeException( + "Test fails: focus lost hides single selection"); + } - SwingUtilities.invokeAndWait(field2::requestFocus); - robot.waitForIdle(); - SwingUtilities.invokeAndWait(() ->{ - frame2 = new JFrame(); - Point loc = frame.getLocationOnScreen(); - loc.translate(0, frame.getHeight()); - frame2.setLocation(loc); - anotherWindow = new JTextField("textField3"); - frame2.add(anotherWindow); - frame2.pack(); - frame2.setVisible(true); - }); - robot.waitForIdle(); - SwingUtilities.invokeAndWait(anotherWindow::requestFocus); - robot.waitForIdle(); - robot.delay(200); - if (biEqual(robot.createScreenCapture(bounds), nosel)) { - throw new RuntimeException( - "Test fails: switch window hides selection"); - } + SwingUtilities.invokeAndWait(field1::selectAll); + robot.waitForIdle(); + robot.delay(200); + if (field2.getCaret().isSelectionVisible()) { + throw new RuntimeException( + "Test fails: focus lost doesn't hide selection upon multi selection"); + } - SwingUtilities.invokeAndWait(anotherWindow::selectAll); - robot.waitForIdle(); - robot.delay(200); - if (biEqual(robot.createScreenCapture(bounds), sel)) { - throw new RuntimeException( - "Test fails: selection ownership is lost selection is shown"); - } + SwingUtilities.invokeAndWait(field2::requestFocus); + robot.waitForIdle(); + robot.delay(200); + if (!field2.getCaret().isSelectionVisible()) { + throw new RuntimeException( + "Test fails: focus gain hides selection upon multi selection"); + } - SwingUtilities.invokeLater(frame2::dispose); - SwingUtilities.invokeLater(frame::dispose); - } + SwingUtilities.invokeAndWait(field2::requestFocus); + robot.waitForIdle(); + SwingUtilities.invokeAndWait(() -> { + frame2 = new JFrame(); + Point loc = frame.getLocationOnScreen(); + loc.translate(0, frame.getHeight()); + frame2.setLocation(loc); + anotherWindow = new JTextField("textField3"); + frame2.add(anotherWindow); + frame2.pack(); + frame2.setVisible(true); + }); + robot.waitForIdle(); + SwingUtilities.invokeAndWait(anotherWindow::requestFocus); + robot.waitForIdle(); + robot.delay(200); + if (!field2.getCaret().isSelectionVisible()) { + throw new RuntimeException( + "Test fails: switch window hides selection"); + } - static boolean biEqual(BufferedImage i1, BufferedImage i2) { - if (i1.getWidth() == i2.getWidth() && - i1.getHeight() == i2.getHeight()) { - for (int x = 0; x < i1.getWidth(); x++) { - for (int y = 0; y < i1.getHeight(); y++) { - if (i1.getRGB(x, y) != i2.getRGB(x, y)) { - return false; - } - } + SwingUtilities.invokeAndWait(anotherWindow::selectAll); + robot.waitForIdle(); + robot.delay(200); + if (field2.getCaret().isSelectionVisible()) { + throw new RuntimeException( + "Test fails: selection ownership is lost selection is shown"); + } + } finally { + if (frame2 != null) { + SwingUtilities.invokeLater(frame2::dispose); } - return true; + SwingUtilities.invokeLater(frame::dispose); } - return false; } } diff --git a/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.java b/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.java index e7c31a26d0f..1df40e5714e 100644 --- a/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.java +++ b/test/jdk/javax/swing/text/StyledEditorKit/4506788/bug4506788.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 @@ -29,98 +29,85 @@ * @run main bug4506788 */ -import java.awt.*; -import java.awt.event.*; -import java.lang.reflect.InvocationTargetException; -import javax.swing.*; -import javax.swing.event.*; -import javax.swing.text.*; +import java.awt.Dimension; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.KeyEvent; +import java.awt.event.InputEvent; +import javax.swing.JEditorPane; +import javax.swing.JFrame; +import javax.swing.SwingUtilities; +import javax.swing.event.CaretEvent; +import javax.swing.event.CaretListener; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.MutableAttributeSet; +import javax.swing.text.SimpleAttributeSet; +import javax.swing.text.StyleConstants; +import javax.swing.text.StyledEditorKit; public class bug4506788 { - private volatile boolean passed = false; - private JEditorPane jep; + private static volatile boolean passed; + private static volatile Point p; + private static volatile Dimension dim; + private static JEditorPane jep; + private static JFrame f; - public static void main(final String[] args) { - bug4506788 app = new bug4506788(); - app.init(); - app.start(); - } - - public void init() { - try { - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - createAndShowGUI(); - } - }); - } catch (InterruptedException | InvocationTargetException ex) { - ex.printStackTrace(); - throw new RuntimeException("FAILED: SwingUtilities.invokeAndWait method failed then creating and showing GUI"); - } - } - - public void start() { - Robot robot; + public static void main(final String[] args) throws Exception { try { - robot = new Robot(); + Robot robot = new Robot(); robot.setAutoDelay(100); - } catch (AWTException e) { - throw new RuntimeException("Robot could not be created"); - } - - robot.waitForIdle(); - - Point p; - try { - p = getJEPLocOnScreen(); - } catch (Exception e) { - throw new RuntimeException("Could not get JEditorPane location on screen"); - } - - robot.mouseMove(p.x, p.y); - robot.mousePress(InputEvent.BUTTON1_MASK); - robot.mouseRelease(InputEvent.BUTTON1_MASK); - robot.keyPress(KeyEvent.VK_HOME); - robot.keyRelease(KeyEvent.VK_HOME); - robot.keyPress(KeyEvent.VK_RIGHT); - robot.keyRelease(KeyEvent.VK_RIGHT); - robot.keyPress(KeyEvent.VK_X); - robot.keyRelease(KeyEvent.VK_X); - robot.keyPress(KeyEvent.VK_RIGHT); - robot.keyRelease(KeyEvent.VK_RIGHT); - - robot.waitForIdle(); - if (!passed) { - throw new RuntimeException("Test failed."); - } - } + SwingUtilities.invokeAndWait(() -> createAndShowGUI()); - private Point getJEPLocOnScreen() throws Exception { + robot.waitForIdle(); + robot.delay(1000); - final Point[] result = new Point[1]; + SwingUtilities.invokeAndWait(() -> { + p = jep.getLocationOnScreen(); + dim = jep.getSize(); + }); - SwingUtilities.invokeAndWait(new Runnable() { - @Override - public void run() { - result[0] = jep.getLocationOnScreen(); + robot.mouseMove(p.x + dim.width / 2, p.y + dim.height / 2); + robot.waitForIdle(); + robot.mousePress(InputEvent.BUTTON1_DOWN_MASK); + robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_HOME); + robot.keyRelease(KeyEvent.VK_HOME); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_RIGHT); + robot.keyRelease(KeyEvent.VK_RIGHT); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_X); + robot.keyRelease(KeyEvent.VK_X); + robot.waitForIdle(); + robot.keyPress(KeyEvent.VK_RIGHT); + robot.keyRelease(KeyEvent.VK_RIGHT); + robot.waitForIdle(); + + if (!passed) { + throw new RuntimeException("Test failed."); } - }); - - return result[0]; + } finally { + SwingUtilities.invokeAndWait(() -> { + if (f != null) { + f.dispose(); + } + }); + } } - private void createAndShowGUI() { + private static void createAndShowGUI() { jep = new JEditorPane(); String text = "abc"; - JFrame f = new JFrame(); + f = new JFrame("bug4506788"); jep.setEditorKit(new StyledEditorKit()); jep.setText(text); jep.addCaretListener(new CaretListener() { @Override public void caretUpdate(CaretEvent e) { + System.out.println("getDot " + e.getDot()); passed = (e.getDot() == 3); } }); diff --git a/test/jdk/jdk/incubator/vector/AbstractVectorTest.java b/test/jdk/jdk/incubator/vector/AbstractVectorTest.java index e7d66881d72..9352091bafc 100644 --- a/test/jdk/jdk/incubator/vector/AbstractVectorTest.java +++ b/test/jdk/jdk/incubator/vector/AbstractVectorTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -35,11 +35,13 @@ import java.util.stream.Stream; import java.util.stream.Collectors; +import jdk.test.lib.Utils; + import org.testng.Assert; public class AbstractVectorTest { - static final Random RAND = new Random(Integer.getInteger("jdk.incubator.vector.test.random-seed", 1337)); + static final Random RAND = Utils.getRandomInstance(); interface ToBoolF { boolean apply(int i); diff --git a/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java index ff8f2c16f10..86d00129cbe 100644 --- a/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Byte128VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Byte128VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Byte128VectorTests.java b/test/jdk/jdk/incubator/vector/Byte128VectorTests.java index 958d42db89a..93a74dcd112 100644 --- a/test/jdk/jdk/incubator/vector/Byte128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Byte128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Byte128VectorTests */ @@ -4253,7 +4256,7 @@ static byte[] sliceUnary(byte[] a, int origin, int idx) { static void sliceUnaryByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4281,7 +4284,7 @@ static void sliceBinaryByte128VectorTestsBinary(IntFunction fa, IntFunct byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4314,7 +4317,7 @@ static void sliceByte128VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4342,7 +4345,7 @@ static byte[] unsliceUnary(byte[] a, int origin, int idx) { static void unsliceUnaryByte128VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4379,8 +4382,8 @@ static void unsliceBinaryByte128VectorTestsBinary(IntFunction fa, IntFun byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4435,8 +4438,8 @@ static void unsliceByte128VectorTestsMasked(IntFunction fa, IntFunction< boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java index 84375800f08..1f49ad7cadc 100644 --- a/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Byte256VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Byte256VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Byte256VectorTests.java b/test/jdk/jdk/incubator/vector/Byte256VectorTests.java index 095bb03af62..8bd90ac3615 100644 --- a/test/jdk/jdk/incubator/vector/Byte256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Byte256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Byte256VectorTests */ @@ -4253,7 +4256,7 @@ static byte[] sliceUnary(byte[] a, int origin, int idx) { static void sliceUnaryByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4281,7 +4284,7 @@ static void sliceBinaryByte256VectorTestsBinary(IntFunction fa, IntFunct byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4314,7 +4317,7 @@ static void sliceByte256VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4342,7 +4345,7 @@ static byte[] unsliceUnary(byte[] a, int origin, int idx) { static void unsliceUnaryByte256VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4379,8 +4382,8 @@ static void unsliceBinaryByte256VectorTestsBinary(IntFunction fa, IntFun byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4435,8 +4438,8 @@ static void unsliceByte256VectorTestsMasked(IntFunction fa, IntFunction< boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java index e87bcba3c65..91816ac81ee 100644 --- a/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Byte512VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Byte512VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Byte512VectorTests.java b/test/jdk/jdk/incubator/vector/Byte512VectorTests.java index 543ab8ae96d..a8c28f48cd6 100644 --- a/test/jdk/jdk/incubator/vector/Byte512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Byte512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Byte512VectorTests */ @@ -4253,7 +4256,7 @@ static byte[] sliceUnary(byte[] a, int origin, int idx) { static void sliceUnaryByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4281,7 +4284,7 @@ static void sliceBinaryByte512VectorTestsBinary(IntFunction fa, IntFunct byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4314,7 +4317,7 @@ static void sliceByte512VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4342,7 +4345,7 @@ static byte[] unsliceUnary(byte[] a, int origin, int idx) { static void unsliceUnaryByte512VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4379,8 +4382,8 @@ static void unsliceBinaryByte512VectorTestsBinary(IntFunction fa, IntFun byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4435,8 +4438,8 @@ static void unsliceByte512VectorTestsMasked(IntFunction fa, IntFunction< boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java index 73f38468bae..c707b29a2e0 100644 --- a/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Byte64VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Byte64VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Byte64VectorTests.java b/test/jdk/jdk/incubator/vector/Byte64VectorTests.java index b489efe8653..3a6c665bf7f 100644 --- a/test/jdk/jdk/incubator/vector/Byte64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Byte64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Byte64VectorTests */ @@ -4253,7 +4256,7 @@ static byte[] sliceUnary(byte[] a, int origin, int idx) { static void sliceUnaryByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4281,7 +4284,7 @@ static void sliceBinaryByte64VectorTestsBinary(IntFunction fa, IntFuncti byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4314,7 +4317,7 @@ static void sliceByte64VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4342,7 +4345,7 @@ static byte[] unsliceUnary(byte[] a, int origin, int idx) { static void unsliceUnaryByte64VectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4379,8 +4382,8 @@ static void unsliceBinaryByte64VectorTestsBinary(IntFunction fa, IntFunc byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4435,8 +4438,8 @@ static void unsliceByte64VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java index f8c4d2ae417..bf546f120ac 100644 --- a/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/ByteMaxVectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation ByteMaxVectorLoadStoreTests diff --git a/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java b/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java index 5872a22bfe1..f79e7431c4b 100644 --- a/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/ByteMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation ByteMaxVectorTests */ @@ -4258,7 +4261,7 @@ static byte[] sliceUnary(byte[] a, int origin, int idx) { static void sliceUnaryByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4286,7 +4289,7 @@ static void sliceBinaryByteMaxVectorTestsBinary(IntFunction fa, IntFunct byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4319,7 +4322,7 @@ static void sliceByteMaxVectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4347,7 +4350,7 @@ static byte[] unsliceUnary(byte[] a, int origin, int idx) { static void unsliceUnaryByteMaxVectorTests(IntFunction fa) { byte[] a = fa.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4384,8 +4387,8 @@ static void unsliceBinaryByteMaxVectorTestsBinary(IntFunction fa, IntFun byte[] a = fa.apply(SPECIES.length()); byte[] b = fb.apply(SPECIES.length()); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); @@ -4440,8 +4443,8 @@ static void unsliceByteMaxVectorTestsMasked(IntFunction fa, IntFunction< boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); byte[] r = new byte[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ByteVector av = ByteVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java index b361734c8fa..52435a2ef5a 100644 --- a/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Double128VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Double128VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Double128VectorTests.java b/test/jdk/jdk/incubator/vector/Double128VectorTests.java index bf9c717cc59..5f6ea0c8893 100644 --- a/test/jdk/jdk/incubator/vector/Double128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Double128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Double128VectorTests */ @@ -3398,7 +3401,7 @@ static double[] sliceUnary(double[] a, int origin, int idx) { static void sliceUnaryDouble128VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3426,7 +3429,7 @@ static void sliceBinaryDouble128VectorTestsBinary(IntFunction fa, IntF double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3459,7 +3462,7 @@ static void sliceDouble128VectorTestsMasked(IntFunction fa, IntFunctio VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3487,7 +3490,7 @@ static double[] unsliceUnary(double[] a, int origin, int idx) { static void unsliceUnaryDouble128VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3524,8 +3527,8 @@ static void unsliceBinaryDouble128VectorTestsBinary(IntFunction fa, In double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3580,8 +3583,8 @@ static void unsliceDouble128VectorTestsMasked(IntFunction fa, IntFunct boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java index 0bff64fe5f5..1ec423d1b74 100644 --- a/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Double256VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Double256VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Double256VectorTests.java b/test/jdk/jdk/incubator/vector/Double256VectorTests.java index bb4694966d8..293a53fa211 100644 --- a/test/jdk/jdk/incubator/vector/Double256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Double256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Double256VectorTests */ @@ -3398,7 +3401,7 @@ static double[] sliceUnary(double[] a, int origin, int idx) { static void sliceUnaryDouble256VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3426,7 +3429,7 @@ static void sliceBinaryDouble256VectorTestsBinary(IntFunction fa, IntF double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3459,7 +3462,7 @@ static void sliceDouble256VectorTestsMasked(IntFunction fa, IntFunctio VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3487,7 +3490,7 @@ static double[] unsliceUnary(double[] a, int origin, int idx) { static void unsliceUnaryDouble256VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3524,8 +3527,8 @@ static void unsliceBinaryDouble256VectorTestsBinary(IntFunction fa, In double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3580,8 +3583,8 @@ static void unsliceDouble256VectorTestsMasked(IntFunction fa, IntFunct boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java index f022a8f7418..5b381b5ee0a 100644 --- a/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Double512VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Double512VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Double512VectorTests.java b/test/jdk/jdk/incubator/vector/Double512VectorTests.java index 72bb1a49c36..e39bf22ad5c 100644 --- a/test/jdk/jdk/incubator/vector/Double512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Double512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Double512VectorTests */ @@ -3398,7 +3401,7 @@ static double[] sliceUnary(double[] a, int origin, int idx) { static void sliceUnaryDouble512VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3426,7 +3429,7 @@ static void sliceBinaryDouble512VectorTestsBinary(IntFunction fa, IntF double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3459,7 +3462,7 @@ static void sliceDouble512VectorTestsMasked(IntFunction fa, IntFunctio VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3487,7 +3490,7 @@ static double[] unsliceUnary(double[] a, int origin, int idx) { static void unsliceUnaryDouble512VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3524,8 +3527,8 @@ static void unsliceBinaryDouble512VectorTestsBinary(IntFunction fa, In double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3580,8 +3583,8 @@ static void unsliceDouble512VectorTestsMasked(IntFunction fa, IntFunct boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java index a18318c5e2e..0d79e05f0fc 100644 --- a/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Double64VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Double64VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Double64VectorTests.java b/test/jdk/jdk/incubator/vector/Double64VectorTests.java index b445995543f..d246927bc96 100644 --- a/test/jdk/jdk/incubator/vector/Double64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Double64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Double64VectorTests */ @@ -3398,7 +3401,7 @@ static double[] sliceUnary(double[] a, int origin, int idx) { static void sliceUnaryDouble64VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3426,7 +3429,7 @@ static void sliceBinaryDouble64VectorTestsBinary(IntFunction fa, IntFu double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3459,7 +3462,7 @@ static void sliceDouble64VectorTestsMasked(IntFunction fa, IntFunction VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3487,7 +3490,7 @@ static double[] unsliceUnary(double[] a, int origin, int idx) { static void unsliceUnaryDouble64VectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3524,8 +3527,8 @@ static void unsliceBinaryDouble64VectorTestsBinary(IntFunction fa, Int double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3580,8 +3583,8 @@ static void unsliceDouble64VectorTestsMasked(IntFunction fa, IntFuncti boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java index 0a3b1391aa2..949ad39ed56 100644 --- a/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/DoubleMaxVectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation DoubleMaxVectorLoadStoreTests diff --git a/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java b/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java index 9db85a2f20e..4786d412b1c 100644 --- a/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/DoubleMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation DoubleMaxVectorTests */ @@ -3404,7 +3407,7 @@ static double[] sliceUnary(double[] a, int origin, int idx) { static void sliceUnaryDoubleMaxVectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3432,7 +3435,7 @@ static void sliceBinaryDoubleMaxVectorTestsBinary(IntFunction fa, IntF double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3465,7 +3468,7 @@ static void sliceDoubleMaxVectorTestsMasked(IntFunction fa, IntFunctio VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3493,7 +3496,7 @@ static double[] unsliceUnary(double[] a, int origin, int idx) { static void unsliceUnaryDoubleMaxVectorTests(IntFunction fa) { double[] a = fa.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3530,8 +3533,8 @@ static void unsliceBinaryDoubleMaxVectorTestsBinary(IntFunction fa, In double[] a = fa.apply(SPECIES.length()); double[] b = fb.apply(SPECIES.length()); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); @@ -3586,8 +3589,8 @@ static void unsliceDoubleMaxVectorTestsMasked(IntFunction fa, IntFunct boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); double[] r = new double[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { DoubleVector av = DoubleVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java index eb604c93545..30afaf48f05 100644 --- a/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Float128VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Float128VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Float128VectorTests.java b/test/jdk/jdk/incubator/vector/Float128VectorTests.java index c8a9aa4a80c..65fa472b668 100644 --- a/test/jdk/jdk/incubator/vector/Float128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Float128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Float128VectorTests */ @@ -3408,7 +3411,7 @@ static float[] sliceUnary(float[] a, int origin, int idx) { static void sliceUnaryFloat128VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3436,7 +3439,7 @@ static void sliceBinaryFloat128VectorTestsBinary(IntFunction fa, IntFun float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3469,7 +3472,7 @@ static void sliceFloat128VectorTestsMasked(IntFunction fa, IntFunction< VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3497,7 +3500,7 @@ static float[] unsliceUnary(float[] a, int origin, int idx) { static void unsliceUnaryFloat128VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3534,8 +3537,8 @@ static void unsliceBinaryFloat128VectorTestsBinary(IntFunction fa, IntF float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3590,8 +3593,8 @@ static void unsliceFloat128VectorTestsMasked(IntFunction fa, IntFunctio boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java index b76b499604d..03721f1b0e5 100644 --- a/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Float256VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Float256VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Float256VectorTests.java b/test/jdk/jdk/incubator/vector/Float256VectorTests.java index fcbf7df409b..2e0b12115db 100644 --- a/test/jdk/jdk/incubator/vector/Float256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Float256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Float256VectorTests */ @@ -3408,7 +3411,7 @@ static float[] sliceUnary(float[] a, int origin, int idx) { static void sliceUnaryFloat256VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3436,7 +3439,7 @@ static void sliceBinaryFloat256VectorTestsBinary(IntFunction fa, IntFun float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3469,7 +3472,7 @@ static void sliceFloat256VectorTestsMasked(IntFunction fa, IntFunction< VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3497,7 +3500,7 @@ static float[] unsliceUnary(float[] a, int origin, int idx) { static void unsliceUnaryFloat256VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3534,8 +3537,8 @@ static void unsliceBinaryFloat256VectorTestsBinary(IntFunction fa, IntF float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3590,8 +3593,8 @@ static void unsliceFloat256VectorTestsMasked(IntFunction fa, IntFunctio boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java index c264e497331..0570f218979 100644 --- a/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Float512VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Float512VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Float512VectorTests.java b/test/jdk/jdk/incubator/vector/Float512VectorTests.java index 597a590098a..e4553730e31 100644 --- a/test/jdk/jdk/incubator/vector/Float512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Float512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Float512VectorTests */ @@ -3408,7 +3411,7 @@ static float[] sliceUnary(float[] a, int origin, int idx) { static void sliceUnaryFloat512VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3436,7 +3439,7 @@ static void sliceBinaryFloat512VectorTestsBinary(IntFunction fa, IntFun float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3469,7 +3472,7 @@ static void sliceFloat512VectorTestsMasked(IntFunction fa, IntFunction< VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3497,7 +3500,7 @@ static float[] unsliceUnary(float[] a, int origin, int idx) { static void unsliceUnaryFloat512VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3534,8 +3537,8 @@ static void unsliceBinaryFloat512VectorTestsBinary(IntFunction fa, IntF float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3590,8 +3593,8 @@ static void unsliceFloat512VectorTestsMasked(IntFunction fa, IntFunctio boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java index b6d39590b7c..e8d2193fafd 100644 --- a/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Float64VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Float64VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Float64VectorTests.java b/test/jdk/jdk/incubator/vector/Float64VectorTests.java index b5877b9de46..134ea5ec762 100644 --- a/test/jdk/jdk/incubator/vector/Float64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Float64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Float64VectorTests */ @@ -3408,7 +3411,7 @@ static float[] sliceUnary(float[] a, int origin, int idx) { static void sliceUnaryFloat64VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3436,7 +3439,7 @@ static void sliceBinaryFloat64VectorTestsBinary(IntFunction fa, IntFunc float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3469,7 +3472,7 @@ static void sliceFloat64VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3497,7 +3500,7 @@ static float[] unsliceUnary(float[] a, int origin, int idx) { static void unsliceUnaryFloat64VectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3534,8 +3537,8 @@ static void unsliceBinaryFloat64VectorTestsBinary(IntFunction fa, IntFu float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3590,8 +3593,8 @@ static void unsliceFloat64VectorTestsMasked(IntFunction fa, IntFunction boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java index 0f60e9424e8..bcad40642b2 100644 --- a/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/FloatMaxVectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation FloatMaxVectorLoadStoreTests diff --git a/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java b/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java index 9a40694f869..2d90ed78328 100644 --- a/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/FloatMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation FloatMaxVectorTests */ @@ -3414,7 +3417,7 @@ static float[] sliceUnary(float[] a, int origin, int idx) { static void sliceUnaryFloatMaxVectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3442,7 +3445,7 @@ static void sliceBinaryFloatMaxVectorTestsBinary(IntFunction fa, IntFun float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3475,7 +3478,7 @@ static void sliceFloatMaxVectorTestsMasked(IntFunction fa, IntFunction< VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3503,7 +3506,7 @@ static float[] unsliceUnary(float[] a, int origin, int idx) { static void unsliceUnaryFloatMaxVectorTests(IntFunction fa) { float[] a = fa.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3540,8 +3543,8 @@ static void unsliceBinaryFloatMaxVectorTestsBinary(IntFunction fa, IntF float[] a = fa.apply(SPECIES.length()); float[] b = fb.apply(SPECIES.length()); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); @@ -3596,8 +3599,8 @@ static void unsliceFloatMaxVectorTestsMasked(IntFunction fa, IntFunctio boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); float[] r = new float[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { FloatVector av = FloatVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java index 3cb331816fe..792c09e00b5 100644 --- a/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Int128VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Int128VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Int128VectorTests.java b/test/jdk/jdk/incubator/vector/Int128VectorTests.java index 49e9f4eb25f..3335f957866 100644 --- a/test/jdk/jdk/incubator/vector/Int128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Int128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Int128VectorTests */ @@ -4218,7 +4221,7 @@ static int[] sliceUnary(int[] a, int origin, int idx) { static void sliceUnaryInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4246,7 +4249,7 @@ static void sliceBinaryInt128VectorTestsBinary(IntFunction fa, IntFunctio int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4279,7 +4282,7 @@ static void sliceInt128VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4307,7 +4310,7 @@ static int[] unsliceUnary(int[] a, int origin, int idx) { static void unsliceUnaryInt128VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4344,8 +4347,8 @@ static void unsliceBinaryInt128VectorTestsBinary(IntFunction fa, IntFunct int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4400,8 +4403,8 @@ static void unsliceInt128VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java index eb3f2f8c67d..7589a83a3cb 100644 --- a/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Int256VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Int256VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Int256VectorTests.java b/test/jdk/jdk/incubator/vector/Int256VectorTests.java index 570163c3d60..2893879a6e6 100644 --- a/test/jdk/jdk/incubator/vector/Int256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Int256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Int256VectorTests */ @@ -4218,7 +4221,7 @@ static int[] sliceUnary(int[] a, int origin, int idx) { static void sliceUnaryInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4246,7 +4249,7 @@ static void sliceBinaryInt256VectorTestsBinary(IntFunction fa, IntFunctio int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4279,7 +4282,7 @@ static void sliceInt256VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4307,7 +4310,7 @@ static int[] unsliceUnary(int[] a, int origin, int idx) { static void unsliceUnaryInt256VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4344,8 +4347,8 @@ static void unsliceBinaryInt256VectorTestsBinary(IntFunction fa, IntFunct int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4400,8 +4403,8 @@ static void unsliceInt256VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java index bf63016a445..6d3acdd6439 100644 --- a/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Int512VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Int512VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Int512VectorTests.java b/test/jdk/jdk/incubator/vector/Int512VectorTests.java index e462fefb9a5..40121dfe991 100644 --- a/test/jdk/jdk/incubator/vector/Int512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Int512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Int512VectorTests */ @@ -4218,7 +4221,7 @@ static int[] sliceUnary(int[] a, int origin, int idx) { static void sliceUnaryInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4246,7 +4249,7 @@ static void sliceBinaryInt512VectorTestsBinary(IntFunction fa, IntFunctio int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4279,7 +4282,7 @@ static void sliceInt512VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4307,7 +4310,7 @@ static int[] unsliceUnary(int[] a, int origin, int idx) { static void unsliceUnaryInt512VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4344,8 +4347,8 @@ static void unsliceBinaryInt512VectorTestsBinary(IntFunction fa, IntFunct int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4400,8 +4403,8 @@ static void unsliceInt512VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java index 8dd1d48fab4..360ac1cf8e4 100644 --- a/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Int64VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Int64VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Int64VectorTests.java b/test/jdk/jdk/incubator/vector/Int64VectorTests.java index 3bdad69e47b..20ade53e25d 100644 --- a/test/jdk/jdk/incubator/vector/Int64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Int64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Int64VectorTests */ @@ -4218,7 +4221,7 @@ static int[] sliceUnary(int[] a, int origin, int idx) { static void sliceUnaryInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4246,7 +4249,7 @@ static void sliceBinaryInt64VectorTestsBinary(IntFunction fa, IntFunction int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4279,7 +4282,7 @@ static void sliceInt64VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4307,7 +4310,7 @@ static int[] unsliceUnary(int[] a, int origin, int idx) { static void unsliceUnaryInt64VectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4344,8 +4347,8 @@ static void unsliceBinaryInt64VectorTestsBinary(IntFunction fa, IntFuncti int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4400,8 +4403,8 @@ static void unsliceInt64VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java index 0c16d119eb4..b0d0e6b00e0 100644 --- a/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/IntMaxVectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation IntMaxVectorLoadStoreTests diff --git a/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java b/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java index b4ab5c09989..799bc152e57 100644 --- a/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/IntMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation IntMaxVectorTests */ @@ -4223,7 +4226,7 @@ static int[] sliceUnary(int[] a, int origin, int idx) { static void sliceUnaryIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4251,7 +4254,7 @@ static void sliceBinaryIntMaxVectorTestsBinary(IntFunction fa, IntFunctio int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4284,7 +4287,7 @@ static void sliceIntMaxVectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4312,7 +4315,7 @@ static int[] unsliceUnary(int[] a, int origin, int idx) { static void unsliceUnaryIntMaxVectorTests(IntFunction fa) { int[] a = fa.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4349,8 +4352,8 @@ static void unsliceBinaryIntMaxVectorTestsBinary(IntFunction fa, IntFunct int[] a = fa.apply(SPECIES.length()); int[] b = fb.apply(SPECIES.length()); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); @@ -4405,8 +4408,8 @@ static void unsliceIntMaxVectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); int[] r = new int[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { IntVector av = IntVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java index 232ff397a11..d1b0cf11f6d 100644 --- a/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Long128VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Long128VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Long128VectorTests.java b/test/jdk/jdk/incubator/vector/Long128VectorTests.java index 07be948cdc7..e88ab6518da 100644 --- a/test/jdk/jdk/incubator/vector/Long128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Long128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Long128VectorTests */ @@ -4168,7 +4171,7 @@ static long[] sliceUnary(long[] a, int origin, int idx) { static void sliceUnaryLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4196,7 +4199,7 @@ static void sliceBinaryLong128VectorTestsBinary(IntFunction fa, IntFunct long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4229,7 +4232,7 @@ static void sliceLong128VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4257,7 +4260,7 @@ static long[] unsliceUnary(long[] a, int origin, int idx) { static void unsliceUnaryLong128VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4294,8 +4297,8 @@ static void unsliceBinaryLong128VectorTestsBinary(IntFunction fa, IntFun long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4350,8 +4353,8 @@ static void unsliceLong128VectorTestsMasked(IntFunction fa, IntFunction< boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java index cbb01fc336d..1c5d26d7a12 100644 --- a/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Long256VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Long256VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Long256VectorTests.java b/test/jdk/jdk/incubator/vector/Long256VectorTests.java index f2290709688..dbe3c4ae6e1 100644 --- a/test/jdk/jdk/incubator/vector/Long256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Long256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Long256VectorTests */ @@ -4168,7 +4171,7 @@ static long[] sliceUnary(long[] a, int origin, int idx) { static void sliceUnaryLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4196,7 +4199,7 @@ static void sliceBinaryLong256VectorTestsBinary(IntFunction fa, IntFunct long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4229,7 +4232,7 @@ static void sliceLong256VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4257,7 +4260,7 @@ static long[] unsliceUnary(long[] a, int origin, int idx) { static void unsliceUnaryLong256VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4294,8 +4297,8 @@ static void unsliceBinaryLong256VectorTestsBinary(IntFunction fa, IntFun long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4350,8 +4353,8 @@ static void unsliceLong256VectorTestsMasked(IntFunction fa, IntFunction< boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java index 695067a31c4..282096d8669 100644 --- a/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Long512VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Long512VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Long512VectorTests.java b/test/jdk/jdk/incubator/vector/Long512VectorTests.java index 77e2c79a32c..840b1bf5876 100644 --- a/test/jdk/jdk/incubator/vector/Long512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Long512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Long512VectorTests */ @@ -4168,7 +4171,7 @@ static long[] sliceUnary(long[] a, int origin, int idx) { static void sliceUnaryLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4196,7 +4199,7 @@ static void sliceBinaryLong512VectorTestsBinary(IntFunction fa, IntFunct long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4229,7 +4232,7 @@ static void sliceLong512VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4257,7 +4260,7 @@ static long[] unsliceUnary(long[] a, int origin, int idx) { static void unsliceUnaryLong512VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4294,8 +4297,8 @@ static void unsliceBinaryLong512VectorTestsBinary(IntFunction fa, IntFun long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4350,8 +4353,8 @@ static void unsliceLong512VectorTestsMasked(IntFunction fa, IntFunction< boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java index c574a76019f..0498a114e6c 100644 --- a/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Long64VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Long64VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Long64VectorTests.java b/test/jdk/jdk/incubator/vector/Long64VectorTests.java index da71833a50d..357e6b27ede 100644 --- a/test/jdk/jdk/incubator/vector/Long64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Long64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Long64VectorTests */ @@ -4168,7 +4171,7 @@ static long[] sliceUnary(long[] a, int origin, int idx) { static void sliceUnaryLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4196,7 +4199,7 @@ static void sliceBinaryLong64VectorTestsBinary(IntFunction fa, IntFuncti long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4229,7 +4232,7 @@ static void sliceLong64VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4257,7 +4260,7 @@ static long[] unsliceUnary(long[] a, int origin, int idx) { static void unsliceUnaryLong64VectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4294,8 +4297,8 @@ static void unsliceBinaryLong64VectorTestsBinary(IntFunction fa, IntFunc long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4350,8 +4353,8 @@ static void unsliceLong64VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java index 27712230bad..bb5eb78c536 100644 --- a/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/LongMaxVectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation LongMaxVectorLoadStoreTests diff --git a/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java b/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java index 3d3f1e526f1..731a2476bc9 100644 --- a/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/LongMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation LongMaxVectorTests */ @@ -4173,7 +4176,7 @@ static long[] sliceUnary(long[] a, int origin, int idx) { static void sliceUnaryLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4201,7 +4204,7 @@ static void sliceBinaryLongMaxVectorTestsBinary(IntFunction fa, IntFunct long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4234,7 +4237,7 @@ static void sliceLongMaxVectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4262,7 +4265,7 @@ static long[] unsliceUnary(long[] a, int origin, int idx) { static void unsliceUnaryLongMaxVectorTests(IntFunction fa) { long[] a = fa.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4299,8 +4302,8 @@ static void unsliceBinaryLongMaxVectorTestsBinary(IntFunction fa, IntFun long[] a = fa.apply(SPECIES.length()); long[] b = fb.apply(SPECIES.length()); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); @@ -4355,8 +4358,8 @@ static void unsliceLongMaxVectorTestsMasked(IntFunction fa, IntFunction< boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); long[] r = new long[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { LongVector av = LongVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java index f9ca627a6f6..63aeb1df79f 100644 --- a/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Short128VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Short128VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Short128VectorTests.java b/test/jdk/jdk/incubator/vector/Short128VectorTests.java index cf53e29c836..2a596016176 100644 --- a/test/jdk/jdk/incubator/vector/Short128VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Short128VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Short128VectorTests */ @@ -4243,7 +4246,7 @@ static short[] sliceUnary(short[] a, int origin, int idx) { static void sliceUnaryShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4271,7 +4274,7 @@ static void sliceBinaryShort128VectorTestsBinary(IntFunction fa, IntFun short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4304,7 +4307,7 @@ static void sliceShort128VectorTestsMasked(IntFunction fa, IntFunction< VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4332,7 +4335,7 @@ static short[] unsliceUnary(short[] a, int origin, int idx) { static void unsliceUnaryShort128VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4369,8 +4372,8 @@ static void unsliceBinaryShort128VectorTestsBinary(IntFunction fa, IntF short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4425,8 +4428,8 @@ static void unsliceShort128VectorTestsMasked(IntFunction fa, IntFunctio boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java index 056bad79c20..3d44ec9c7d3 100644 --- a/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Short256VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Short256VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Short256VectorTests.java b/test/jdk/jdk/incubator/vector/Short256VectorTests.java index 3c80891349f..50fa4c9c2c1 100644 --- a/test/jdk/jdk/incubator/vector/Short256VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Short256VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Short256VectorTests */ @@ -4243,7 +4246,7 @@ static short[] sliceUnary(short[] a, int origin, int idx) { static void sliceUnaryShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4271,7 +4274,7 @@ static void sliceBinaryShort256VectorTestsBinary(IntFunction fa, IntFun short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4304,7 +4307,7 @@ static void sliceShort256VectorTestsMasked(IntFunction fa, IntFunction< VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4332,7 +4335,7 @@ static short[] unsliceUnary(short[] a, int origin, int idx) { static void unsliceUnaryShort256VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4369,8 +4372,8 @@ static void unsliceBinaryShort256VectorTestsBinary(IntFunction fa, IntF short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4425,8 +4428,8 @@ static void unsliceShort256VectorTestsMasked(IntFunction fa, IntFunctio boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java index a1fe2e48749..d2602cb8dfa 100644 --- a/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Short512VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Short512VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Short512VectorTests.java b/test/jdk/jdk/incubator/vector/Short512VectorTests.java index ac97097f063..7fae4acaa65 100644 --- a/test/jdk/jdk/incubator/vector/Short512VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Short512VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Short512VectorTests */ @@ -4243,7 +4246,7 @@ static short[] sliceUnary(short[] a, int origin, int idx) { static void sliceUnaryShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4271,7 +4274,7 @@ static void sliceBinaryShort512VectorTestsBinary(IntFunction fa, IntFun short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4304,7 +4307,7 @@ static void sliceShort512VectorTestsMasked(IntFunction fa, IntFunction< VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4332,7 +4335,7 @@ static short[] unsliceUnary(short[] a, int origin, int idx) { static void unsliceUnaryShort512VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4369,8 +4372,8 @@ static void unsliceBinaryShort512VectorTestsBinary(IntFunction fa, IntF short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4425,8 +4428,8 @@ static void unsliceShort512VectorTestsMasked(IntFunction fa, IntFunctio boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java index 142fce0b536..76512a77443 100644 --- a/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/Short64VectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm -XX:-TieredCompilation Short64VectorLoadStoreTests * diff --git a/test/jdk/jdk/incubator/vector/Short64VectorTests.java b/test/jdk/jdk/incubator/vector/Short64VectorTests.java index 72860e07066..7df844c4eb4 100644 --- a/test/jdk/jdk/incubator/vector/Short64VectorTests.java +++ b/test/jdk/jdk/incubator/vector/Short64VectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation Short64VectorTests */ @@ -4243,7 +4246,7 @@ static short[] sliceUnary(short[] a, int origin, int idx) { static void sliceUnaryShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4271,7 +4274,7 @@ static void sliceBinaryShort64VectorTestsBinary(IntFunction fa, IntFunc short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4304,7 +4307,7 @@ static void sliceShort64VectorTestsMasked(IntFunction fa, IntFunction vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4332,7 +4335,7 @@ static short[] unsliceUnary(short[] a, int origin, int idx) { static void unsliceUnaryShort64VectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4369,8 +4372,8 @@ static void unsliceBinaryShort64VectorTestsBinary(IntFunction fa, IntFu short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4425,8 +4428,8 @@ static void unsliceShort64VectorTestsMasked(IntFunction fa, IntFunction boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java b/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java index 85c2a64b975..ffb146ac529 100644 --- a/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java +++ b/test/jdk/jdk/incubator/vector/ShortMaxVectorLoadStoreTests.java @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED * -XX:-TieredCompilation ShortMaxVectorLoadStoreTests diff --git a/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java b/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java index 96ec830e73d..d05b0b60f17 100644 --- a/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java +++ b/test/jdk/jdk/incubator/vector/ShortMaxVectorTests.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation ShortMaxVectorTests */ @@ -4248,7 +4251,7 @@ static short[] sliceUnary(short[] a, int origin, int idx) { static void sliceUnaryShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4276,7 +4279,7 @@ static void sliceBinaryShortMaxVectorTestsBinary(IntFunction fa, IntFun short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4309,7 +4312,7 @@ static void sliceShortMaxVectorTestsMasked(IntFunction fa, IntFunction< VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4337,7 +4340,7 @@ static short[] unsliceUnary(short[] a, int origin, int idx) { static void unsliceUnaryShortMaxVectorTests(IntFunction fa) { short[] a = fa.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4374,8 +4377,8 @@ static void unsliceBinaryShortMaxVectorTestsBinary(IntFunction fa, IntF short[] a = fa.apply(SPECIES.length()); short[] b = fb.apply(SPECIES.length()); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); @@ -4430,8 +4433,8 @@ static void unsliceShortMaxVectorTestsMasked(IntFunction fa, IntFunctio boolean[] mask = fm.apply(SPECIES.length()); VectorMask vmask = VectorMask.fromArray(SPECIES, mask, 0); short[] r = new short[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { ShortVector av = ShortVector.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template index 5d63264bc62..37dba9b6834 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-Masked-bop.template @@ -4,7 +4,7 @@ VectorMask<$Wideboxtype$> vmask = VectorMask.fromArray(SPECIES, mask, 0); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template index cb05df34431..5be74dc67ff 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-bop.template @@ -1,7 +1,7 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] b = fb.apply(SPECIES.length()); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template index ef313a90f94..82faf4afc91 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Slice-op.template @@ -1,6 +1,6 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template index d575f48c003..203b4ff8a2d 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-Masked-bop.template @@ -3,8 +3,8 @@ boolean[] mask = fm.apply(SPECIES.length()); VectorMask<$Wideboxtype$> vmask = VectorMask.fromArray(SPECIES, mask, 0); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template index 4f39f2fce6c..ab11cdb7d2e 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-bop.template @@ -1,8 +1,8 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] b = fb.apply(SPECIES.length()); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); - int part = (new java.util.Random()).nextInt(2); + int origin = RAND.nextInt(SPECIES.length()); + int part = RAND.nextInt(2); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template b/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template index b9cd6118f58..6394e4dd2e9 100644 --- a/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template +++ b/test/jdk/jdk/incubator/vector/templates/Kernel-Unslice-op.template @@ -1,6 +1,6 @@ $type$[] a = fa.apply(SPECIES.length()); $type$[] r = new $type$[a.length]; - int origin = (new java.util.Random()).nextInt(SPECIES.length()); + int origin = RAND.nextInt(SPECIES.length()); for (int ic = 0; ic < INVOC_COUNT; ic++) { for (int i = 0; i < a.length; i += SPECIES.length()) { $abstractvectortype$ av = $abstractvectortype$.fromArray(SPECIES, a, i); diff --git a/test/jdk/jdk/incubator/vector/templates/Unit-header.template b/test/jdk/jdk/incubator/vector/templates/Unit-header.template index 089f9fef8d2..389103ba931 100644 --- a/test/jdk/jdk/incubator/vector/templates/Unit-header.template +++ b/test/jdk/jdk/incubator/vector/templates/Unit-header.template @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.vector * @run testng/othervm/timeout=300 -ea -esa -Xbatch -XX:-TieredCompilation $vectorteststype$ */ diff --git a/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template b/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template index d88fd6fb284..618acbc3691 100644 --- a/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template +++ b/test/jdk/jdk/incubator/vector/templates/X-LoadStoreTest.java.template @@ -23,6 +23,9 @@ /* * @test + * @key randomness + * + * @library /test/lib * @modules jdk.incubator.foreign jdk.incubator.vector java.base/jdk.internal.vm.annotation #if[MaxBit] * @run testng/othervm --add-opens jdk.incubator.vector/jdk.incubator.vector=ALL-UNNAMED diff --git a/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java b/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java index 17def65a6ba..0e532497a46 100644 --- a/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java +++ b/test/jdk/jdk/internal/loader/URLClassPath/LargeClasspathWithPkgPrefix.java @@ -25,7 +25,6 @@ import java.nio.file.Files; import java.nio.file.Path; -import jdk.test.lib.JDKToolFinder; import jdk.test.lib.compiler.CompilerUtils; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; @@ -34,12 +33,12 @@ /* * @test * @bug 8308184 - * @summary Verify that an application can be launched when the classpath contains large number of - * jars and the java.protocol.handler.pkgs system property is set * @library /test/lib/ * @build jdk.test.lib.util.JarBuilder jdk.test.lib.compiler.CompilerUtils * jdk.test.lib.process.ProcessTools * @run driver LargeClasspathWithPkgPrefix + * @summary Verify that an application can be launched when the classpath contains large number of + * jars and the java.protocol.handler.pkgs system property is set */ public class LargeClasspathWithPkgPrefix { @@ -126,8 +125,7 @@ private static void compile(Path javaFile, Path destDir) throws Exception { // java -Djava.protocol.handler.pkgs=foo.bar.some.nonexistent.pkg -cp Foo private static void launchApplication(String classPath) throws Exception { - String java = JDKToolFinder.getJDKTool("java"); - ProcessBuilder pb = new ProcessBuilder(java, + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder( "-Djava.protocol.handler.pkgs=foo.bar.some.nonexistent.pkg", "-cp", classPath, "Foo"); diff --git a/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java b/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java index c48de900ec3..dbcb30255a8 100644 --- a/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java +++ b/test/jdk/jdk/internal/misc/VM/RuntimeArguments.java @@ -23,11 +23,12 @@ /** * @test - * @summary Basic test of VM::getRuntimeArguments + * @requires vm.flagless * @library /test/lib * @modules java.base/jdk.internal.misc * jdk.zipfs * @run testng RuntimeArguments + * @summary Basic test of VM::getRuntimeArguments */ import java.io.IOException; @@ -46,7 +47,6 @@ import static org.testng.Assert.*; public class RuntimeArguments { - static final String TEST_CLASSES = System.getProperty("test.classes"); static final List VM_OPTIONS = getInitialOptions(); /* @@ -112,11 +112,9 @@ public static void main(String... expected) { @Test(dataProvider = "options") public void test(List args, List expected) throws Exception { - // launch a test program - // $ java -classpath RuntimeArguments - Stream options = Stream.concat(args.stream(), - Stream.of("-classpath", TEST_CLASSES, "RuntimeArguments")); - + // launch a test program with classpath set by ProcessTools::createLimitedTestJavaProcessBuilder + // $ java RuntimeArguments + Stream options = Stream.concat(args.stream(), Stream.of("RuntimeArguments")); ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder( // The runtime image may be created with jlink --add-options // The initial VM options will be included in the result diff --git a/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java b/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java index 94383298ddc..58f23350dd0 100644 --- a/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java +++ b/test/jdk/jdk/jfr/api/consumer/filestream/TestOrdered.java @@ -29,6 +29,7 @@ import java.util.List; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import jdk.jfr.Event; @@ -88,69 +89,98 @@ public static void main(String... args) throws Exception { private static void testSetOrderedTrue(Path p) throws Exception { for (boolean reuse : BOOLEAN_STATES) { + System.out.println(); + System.out.println("Testing: testSetOrderedTrue reuse = " + reuse); AtomicReference timestamp = new AtomicReference<>(Instant.MIN); + AtomicBoolean unordered = new AtomicBoolean(false); try (EventStream es = EventStream.openFile(p)) { es.setReuse(reuse); es.setOrdered(true); es.onEvent(e -> { Instant endTime = e.getEndTime(); + printTimestamp(endTime); if (endTime.isBefore(timestamp.get())) { - throw new Error("Events are not ordered! Reuse = " + reuse); + unordered.set(true); } timestamp.set(endTime); }); es.start(); } + if (unordered.get()) { + throw new Exception("Events are not ordered! Reuse = " + reuse); + } } } private static void testSetOrderedFalse(Path p) throws Exception { for (boolean reuse : BOOLEAN_STATES) { + System.out.println(); + System.out.println("Testing: testSetOrderedFalse reuse = " + reuse); AtomicReference timestamp = new AtomicReference<>(Instant.MIN); - AtomicBoolean unoreded = new AtomicBoolean(false); + AtomicBoolean unordered = new AtomicBoolean(false); try (EventStream es = EventStream.openFile(p)) { es.setReuse(reuse); es.setOrdered(false); es.onEvent(e -> { Instant endTime = e.getEndTime(); - System.out.println("testSetOrderedFalse: endTime: " + endTime); + printTimestamp(endTime); if (endTime.isBefore(timestamp.get())) { - unoreded.set(true); - es.close(); + unordered.set(true); } timestamp.set(endTime); }); es.start(); - if (!unoreded.get()) { + if (!unordered.get()) { throw new Exception("Expected at least some events to be out of order! Reuse = " + reuse); } } } } + private static void printTimestamp(Instant timestamp) { + long seconds = timestamp.getEpochSecond(); + long nanos = timestamp.getNano(); + System.out.println(timestamp + " seconds = " + seconds + " nanos = " + nanos); + } + private static Path makeUnorderedRecording() throws Exception { - CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); - - try (Recording r = new Recording()) { - r.start(); - List emitters = new ArrayList<>(); - for (int i = 0; i < THREAD_COUNT; i++) { - Emitter e = new Emitter(barrier); - e.start(); - emitters.add(e); - } - // Thread buffers should now have one event each - barrier.await(); - // Add another event to each thread buffer, so - // events are bound to come out of order when they - // are flushed - for (Emitter e : emitters) { - e.join(); + while (true) { + CyclicBarrier barrier = new CyclicBarrier(THREAD_COUNT + 1); + try (Recording r = new Recording()) { + r.start(); + List emitters = new ArrayList<>(); + for (int i = 0; i < THREAD_COUNT; i++) { + Emitter e = new Emitter(barrier); + e.start(); + emitters.add(e); + } + // Thread buffers should now have one event each + barrier.await(); + // Add another event to each thread buffer, so + // events are bound to come out of order when they + // are flushed + for (Emitter e : emitters) { + e.join(); + } + r.stop(); + Path p = Utils.createTempFile("recording", ".jfr"); + r.dump(p); + // Order is only guaranteed within a segment. + int segments = countSegments(p); + if (segments < 2) { + return p; + } + System.out.println("File contains more than one segment (" + segments + "). Retrying."); } - r.stop(); - Path p = Utils.createTempFile("recording", ".jfr"); - r.dump(p); - return p; + } + } + + private static int countSegments(Path file) throws Exception { + AtomicInteger segments = new AtomicInteger(); + try (EventStream es = EventStream.openFile(file)) { + es.onFlush(segments::incrementAndGet); + es.start(); + return segments.get(); } } } diff --git a/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java b/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java index 5e3b56d2c86..c5dbcd2b42e 100644 --- a/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java +++ b/test/jdk/jdk/jfr/event/gc/stacktrace/AllocationStackTrace.java @@ -79,7 +79,7 @@ public void allocate() { class OldGenMemoryAllocator extends MemoryAllocator { private List list = new ArrayList(); - private int counter = 6000; + private int counter = 5000; @Override public void allocate() { @@ -87,7 +87,7 @@ public void allocate() { list.add(new byte[10 * KB]); } else { list = new ArrayList(); - counter = 6000; + counter = 5000; } garbage = list; diff --git a/test/jdk/jdk/jfr/startupargs/TestStartDuration.java b/test/jdk/jdk/jfr/startupargs/TestStartDuration.java index f9a99a973da..b8ea5326822 100644 --- a/test/jdk/jdk/jfr/startupargs/TestStartDuration.java +++ b/test/jdk/jdk/jfr/startupargs/TestStartDuration.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -37,6 +37,7 @@ * @summary Start a recording with duration. Verify recording stops. * @key jfr * @requires vm.hasJFR + * @requires vm.flagless * @library /test/lib /test/jdk * @run main jdk.jfr.startupargs.TestStartDuration */ diff --git a/test/jdk/jdk/modules/incubator/DefaultImage.java b/test/jdk/jdk/modules/incubator/DefaultImage.java index 25ff746529b..63bc46b26ad 100644 --- a/test/jdk/jdk/modules/incubator/DefaultImage.java +++ b/test/jdk/jdk/modules/incubator/DefaultImage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,11 +24,12 @@ /* * @test * @bug 8170859 - * @summary Ensure no incubator modules are resolved by default in the image + * @requires vm.flagless * @library /test/lib * @modules jdk.compiler * @build jdk.test.lib.compiler.CompilerUtils * @run testng DefaultImage + * @summary Ensure no incubator modules are resolved by default in the image */ import java.io.ByteArrayOutputStream; @@ -43,6 +44,7 @@ import java.util.stream.Stream; import jdk.test.lib.compiler.CompilerUtils; +import jdk.test.lib.process.ProcessTools; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; @@ -108,10 +110,8 @@ public void testAllSystem() throws Throwable { static ToolResult java(String... opts) throws Throwable { ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); - String[] options = Stream.concat(Stream.of(getJava()), Stream.of(opts)) - .toArray(String[]::new); - ProcessBuilder pb = new ProcessBuilder(options); + ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(opts); int exitValue = executeCommand(pb).outputTo(ps) .errorTo(ps) .getExitValue(); @@ -155,15 +155,6 @@ ToolResult assertOutputDoesNotContain(String subString) { } } - static String getJava() { - Path image = Paths.get(JAVA_HOME); - boolean isWindows = System.getProperty("os.name").startsWith("Windows"); - Path java = image.resolve("bin").resolve(isWindows ? "java.exe" : "java"); - if (Files.notExists(java)) - throw new RuntimeException(java + " not found"); - return java.toAbsolutePath().toString(); - } - static boolean isExplodedBuild() { Path modulesPath = Paths.get(JAVA_HOME).resolve("lib").resolve("modules"); return Files.notExists(modulesPath); diff --git a/test/jdk/jdk/modules/incubator/ImageModules.java b/test/jdk/jdk/modules/incubator/ImageModules.java index b69c4022f13..b48a969669e 100644 --- a/test/jdk/jdk/modules/incubator/ImageModules.java +++ b/test/jdk/jdk/modules/incubator/ImageModules.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2016, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,7 +24,7 @@ /* * @test * @bug 8170859 - * @summary Basic test for incubator modules in jmods and images + * @requires vm.flagless * @library /test/lib * @key intermittent * @modules jdk.compiler jdk.jartool jdk.jlink @@ -32,6 +32,7 @@ * jdk.test.lib.util.FileUtils * jdk.test.lib.compiler.CompilerUtils * @run testng/othervm ImageModules + * @summary Basic test for incubator modules in jmods and images */ import java.io.ByteArrayOutputStream; diff --git a/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java b/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java index 3511583e932..0e7c71083dc 100644 --- a/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java +++ b/test/jdk/sanity/client/lib/SwingSet2/src/DemoModule.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2018, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,6 @@ import javax.swing.BoxLayout; import javax.swing.Icon; import javax.swing.ImageIcon; -import javax.swing.JApplet; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.UIManager; @@ -42,10 +41,8 @@ /** * A generic SwingSet2 demo module - * - * @author Jeff Dinkins */ -public class DemoModule extends JApplet { +public class DemoModule extends JPanel { // The preferred size of the demo private int PREFERRED_WIDTH = 680; @@ -214,10 +211,6 @@ public static void main(String[] args) { demo.mainImpl(); } - public void init() { - getContentPane().setLayout(new BorderLayout()); - getContentPane().add(getDemoPanel(), BorderLayout.CENTER); - } - void updateDragEnabled(boolean dragEnabled) {} -} \ No newline at end of file +} + diff --git a/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java b/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java index 924f58cc80f..3f16717153b 100644 --- a/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java +++ b/test/jdk/security/infra/java/security/cert/CertPathValidator/certification/CAInterop.java @@ -635,20 +635,20 @@ private CATestURLs getTestURLs(String alias) { "https://revoked.sfig2.catest.starfieldtech.com"); case "globalsigneccrootcar4" -> - new CATestURLs("https://good.gsr4.demo.pki.goog", - "https://revoked.gsr4.demo.pki.goog"); + new CATestURLs("https://good.gsr4.demosite.pki.goog", + "https://revoked.gsr4.demosite.pki.goog"); case "gtsrootcar1" -> - new CATestURLs("https://good.gtsr1.demo.pki.goog", - "https://revoked.gtsr1.demo.pki.goog"); + new CATestURLs("https://good.gtsr1.demosite.pki.goog", + "https://revoked.gtsr1.demosite.pki.goog"); case "gtsrootcar2" -> - new CATestURLs("https://good.gtsr2.demo.pki.goog", - "https://revoked.gtsr2.demo.pki.goog"); + new CATestURLs("https://good.gtsr2.demosite.pki.goog", + "https://revoked.gtsr2.demosite.pki.goog"); case "gtsrootecccar3" -> - new CATestURLs("https://good.gtsr3.demo.pki.goog", - "https://revoked.gtsr3.demo.pki.goog"); + new CATestURLs("https://good.gtsr3.demosite.pki.goog", + "https://revoked.gtsr3.demosite.pki.goog"); case "gtsrootecccar4" -> - new CATestURLs("https://good.gtsr4.demo.pki.goog", - "https://revoked.gtsr4.demo.pki.goog"); + new CATestURLs("https://good.gtsr4.demosite.pki.goog", + "https://revoked.gtsr4.demosite.pki.goog"); case "microsoftecc2017" -> new CATestURLs("https://acteccroot2017.pki.microsoft.com", diff --git a/test/jdk/sun/java2d/pipe/DrawImageBgTest.java b/test/jdk/sun/java2d/pipe/DrawImageBgTest.java new file mode 100644 index 00000000000..962529dc956 --- /dev/null +++ b/test/jdk/sun/java2d/pipe/DrawImageBgTest.java @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2002, 2024, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 4532352 + * @summary This test verifies that the specified background color is rendered + * in the special case of: + * Graphics.drawImage(Image img, int dx1, int dy1, int dx2, int dy2, + * int sx1, int sy1, int sx2, int sy2, + * Color bgColor, ImageObserver observer) + * where no scaling takes place because the source and destination + * bounds have the same width and height. + */ + +import java.io.File; +import java.awt.Color; +import java.awt.Graphics2D; +import java.awt.image.BufferedImage; +import javax.imageio.ImageIO; + +public class DrawImageBgTest { + + public static void main(String argv[]) throws Exception { + + int dx, dy, dw, dh; + int sx, sy, sw, sh; + + int iw = 250, ih = 250; + String sep = System.getProperty("file.separator"); + String dir = System.getProperty("test.src", "."); + String prefix = dir+sep; + BufferedImage img = ImageIO.read(new File(prefix + "duke.gif")); + BufferedImage dest = new BufferedImage(iw, ih, BufferedImage.TYPE_INT_RGB); + + Graphics2D g = dest.createGraphics(); + g.setColor(Color.blue); + g.fillRect(0, 0, iw, ih); + + // source and destination dimensions are different, results in scaling + dx = 10; + dy = 10; + dw = 100; + dh = 200; + sx = 10; + sy = 10; + sw = 50; + sh = 100; + g.drawImage(img, + dx, dy, dx + dw, dy + dh, + sx, sy, sx + sw, sy + sh, + Color.yellow, null); + + int pix1 = dest.getRGB(dx + 1, dy + 1); + + // source and destination dimensions are the same, no scaling + dx = 120; + dy = 10; + sx = 10; + sy = 10; + sw = dw = 50; + sh = dh = 100; + g.drawImage(img, + dx, dy, dx + dw, dy + dh, + sx, sy, sx + sw, sy + sh, + Color.yellow, null); + + int pix2 = dest.getRGB(dx + 1, dy + 1); + int yellow = Color.yellow.getRGB(); + + if (pix1 != yellow || pix2 != yellow) { + ImageIO.write(dest, "gif", new File("op.gif")); + throw new RuntimeException("pix1=" + Integer.toHexString(pix1) + + " pix2=" + Integer.toHexString(pix2)); + } + } +} diff --git a/test/jdk/sun/java2d/pipe/duke.gif b/test/jdk/sun/java2d/pipe/duke.gif new file mode 100644 index 00000000000..ed32e0ff79b Binary files /dev/null and b/test/jdk/sun/java2d/pipe/duke.gif differ diff --git a/test/jdk/sun/security/pkcs11/PKCS11Test.java b/test/jdk/sun/security/pkcs11/PKCS11Test.java index 046e5558486..c969e566e12 100644 --- a/test/jdk/sun/security/pkcs11/PKCS11Test.java +++ b/test/jdk/sun/security/pkcs11/PKCS11Test.java @@ -53,9 +53,11 @@ import java.util.ServiceConfigurationError; import java.util.ServiceLoader; import java.util.Set; +import java.util.stream.Collectors; import java.util.stream.Stream; import jdk.test.lib.Platform; +import jdk.test.lib.Utils; import jdk.test.lib.artifacts.Artifact; import jdk.test.lib.artifacts.ArtifactResolver; import jdk.test.lib.artifacts.ArtifactResolverException; @@ -481,14 +483,13 @@ public static String getNssConfig() throws Exception { return null; } - String base = getBase(); - + String nssConfigDir = copyNssFiles(); String libfile = libdir + System.mapLibraryName(nss_library); String customDBdir = System.getProperty("CUSTOM_DB_DIR"); String dbdir = (customDBdir != null) ? customDBdir : - base + SEP + "nss" + SEP + "db"; + nssConfigDir + SEP + "db"; // NSS always wants forward slashes for the config path dbdir = dbdir.replace('\\', '/'); @@ -498,7 +499,7 @@ public static String getNssConfig() throws Exception { System.setProperty("pkcs11test.nss.db", dbdir); return (customConfig != null) ? customConfig : - base + SEP + "nss" + SEP + customConfigName; + nssConfigDir + SEP + customConfigName; } // Generate a vector of supported elliptic curves of a given provider @@ -725,6 +726,31 @@ private static Path findNSSLibrary(Path path, Path libraryName) throws IOExcepti } } + //Copy the nss config files to the current directory for tests. Returns the destination path + private static String copyNssFiles() throws Exception { + String nss = "nss"; + String db = "db"; + Path nssDirSource = Path.of(getBase()).resolve(nss); + Path nssDirDestination = Path.of(".").resolve(nss); + + // copy files from nss directory + copyFiles(nssDirSource, nssDirDestination); + // copy files from nss/db directory + copyFiles(nssDirSource.resolve(db), nssDirDestination.resolve(db)); + return nssDirDestination.toString(); + } + + private static void copyFiles(Path dirSource, Path dirDestination) throws IOException { + List sourceFiles = Arrays + .stream(dirSource.toFile().listFiles()) + .filter(File::isFile) + .map(File::toPath) + .collect(Collectors.toList()); + List destFiles = Utils.copyFiles(sourceFiles, dirDestination, + StandardCopyOption.REPLACE_EXISTING); + destFiles.forEach((Path file) -> file.toFile().setWritable(true)); + } + public abstract void main(Provider p) throws Exception; protected boolean skipTest(Provider p) { diff --git a/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh b/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh index b331f6f13f8..5ae606c793d 100644 --- a/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh +++ b/test/jdk/sun/security/pkcs11/Provider/MultipleLogins.sh @@ -1,5 +1,5 @@ # -# Copyright (c) 2021, 2023, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2021, 2024, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -27,6 +27,7 @@ # @library /test/lib/ # @build jdk.test.lib.util.ForceGC # jdk.test.lib.Platform +# jdk.test.lib.Utils # @run shell MultipleLogins.sh # set a few environment variables so that the shell-script can run stand-alone diff --git a/test/jdk/sun/security/provider/KeyStore/DKSTest.java b/test/jdk/sun/security/provider/KeyStore/DKSTest.java index 1d1943ec729..9c35a1c1dd9 100644 --- a/test/jdk/sun/security/provider/KeyStore/DKSTest.java +++ b/test/jdk/sun/security/provider/KeyStore/DKSTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -80,7 +80,7 @@ public class DKSTest { public static void main(String[] args) throws Exception { if (args.length == 0) { // Environment variable and system properties referred in domains.cfg used by this Test. - ProcessBuilder pb = ProcessTools.createLimitedTestJavaProcessBuilder(List.of( + ProcessBuilder pb = ProcessTools.createTestJavaProcessBuilder(List.of( "-Dtest.src=" + TEST_SRC , "-Duser.dir=" + USER_DIR, "DKSTest", "run")); pb.environment().putAll(System.getenv()); pb.environment().put("KEYSTORE_PWD", "test12"); diff --git a/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java b/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java index 7cf0d2ca072..9a50d72ea0c 100644 --- a/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java +++ b/test/jdk/sun/security/provider/PolicyParser/ExtDirs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,16 +26,15 @@ * @bug 4215035 * @summary standard extensions path is hard-coded in default * system policy file - * @run main/manual ExtDirs + * @run main ExtDirs */ /* - * Run this test manually with: - * java -Djava.security.manager \ - * -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \ - * -Djava.security.policy==./ExtDirs.policy \ - * -Djava.security.debug=parser \ - * ExtDirs + * @test + * @bug 4215035 + * @summary standard extensions path is hard-coded in default + * system policy file + * @run main/othervm/policy=ExtDirs.policy ExtDirs */ public class ExtDirs { diff --git a/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy b/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy index ea172d89566..086ccbb8d83 100644 --- a/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy +++ b/test/jdk/sun/security/provider/PolicyParser/ExtDirs.policy @@ -1,4 +1,4 @@ -grant codebase "${java.ext.dirs}" { +grant codebase "file:${test.classes}" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff --git a/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy b/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy index 7fe09732538..086ccbb8d83 100644 --- a/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy +++ b/test/jdk/sun/security/provider/PolicyParser/ExtDirs1.policy @@ -1,4 +1,4 @@ -grant codebase "file:${{java.ext.dirs}}/*" { +grant codebase "file:${test.classes}" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff --git a/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy b/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy index 10b4bc33566..9cc22d30d04 100644 --- a/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy +++ b/test/jdk/sun/security/provider/PolicyParser/ExtDirs2.policy @@ -1,4 +1,4 @@ -grant codebase "file:${{java.ext.dirs}}" { +grant codebase "file:${test.classes}/*" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff --git a/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy b/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy index 4b86743cbdf..9268094e707 100644 --- a/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy +++ b/test/jdk/sun/security/provider/PolicyParser/ExtDirs3.policy @@ -1,4 +1,4 @@ -grant codebase "${{java.ext.dirs}}" { +grant codebase "file:${test.classes}/-" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff --git a/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java b/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java index 1d0198e8295..da0dacff23d 100644 --- a/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java +++ b/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,30 +26,17 @@ * @bug 4993819 * @summary standard extensions path is hard-coded in default * system policy file - * @run main/manual ExtDirsChange + * @run main/othervm/policy=ExtDirsChange.policy ExtDirsChange */ -/* - * Run this test manually with: - * javac ExtDirChange - * rm ExtDirsA*.class ExtDirsB*.class - * java -Djava.security.manager \ - * -Dtest.src=. \ - * -Djava.security.policy=ExtDirsChange.policy \ - * -Djava.security.debug=parser \ - * -cp ExtDirsA/a.jar:ExtDirsB/b.jar:. \ - * ExtDirsChange - */ - -import java.io.File; import java.security.*; public class ExtDirsChange { public static void main(String args[]) throws Exception { - System.out.println("java.ext.dirs: " + - System.getProperty("java.ext.dirs")); + System.out.println("java.policy.dirs: " + + System.getProperty("java.policy.dirs")); - // Uses default security policy and java.ext.dirs + // Uses default security policy and java.policy.dirs try { ExtDirsA a = new ExtDirsA(); a.go(); @@ -58,14 +45,14 @@ public static void main(String args[]) throws Exception { System.out.println("Setup OK"); } - // Change java.ext.dirs and refresh policy + // Change java.policy.dirs and refresh policy AccessController.doPrivileged(new PrivilegedAction() { public Object run() { - // Change java.ext.dirs - System.setProperty("java.ext.dirs", - "ExtDirsA" + File.pathSeparator + "ExtDirsB"); - System.out.println("java.ext.dirs: " + - System.getProperty("java.ext.dirs")); + // Change java.policy.dirs + System.setProperty("java.policy.dirs", + System.getProperty("test.classes")); + System.out.println("java.policy.dirs: " + + System.getProperty("java.policy.dirs")); return null; } }); @@ -79,7 +66,7 @@ public Object run() { System.out.println("Setup before refresh OK"); } - // Refresh policy using updated java.ext.dirs + // Refresh policy using updated java.policy.dirs AccessController.doPrivileged(new PrivilegedAction() { public Object run() { Policy.getPolicy().refresh(); @@ -99,13 +86,13 @@ public Object run() { } // Test with blank java.ext.dir - // Change java.ext.dirs and refresh policy + // Change java.policy.dirs and refresh policy AccessController.doPrivileged(new PrivilegedAction() { public Object run() { - // Change java.ext.dirs - System.setProperty("java.ext.dirs", " "); - System.out.println("java.ext.dirs: " + - System.getProperty("java.ext.dirs")); + // Change java.policy.dirs + System.setProperty("java.policy.dirs", " "); + System.out.println("java.policy.dirs: " + + System.getProperty("java.policy.dirs")); Policy.getPolicy().refresh(); return null; } diff --git a/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy b/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy index 85efce38f73..a158c66251b 100644 --- a/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy +++ b/test/jdk/sun/security/provider/PolicyParser/ExtDirsChange.policy @@ -1,8 +1,16 @@ -grant codebase "file:${test.src}/*" { - permission java.security.AllPermission; +grant { + permission java.util.PropertyPermission "test.classes", "read"; + permission java.security.SecurityPermission "getPolicy"; + permission java.security.SecurityPermission "setPolicy"; }; -grant codebase "${java.ext.dirs}" { +grant codebase "file:${test.classes}/*" { + permission java.util.PropertyPermission "java.policy.dirs", "read, write"; + permission java.util.PropertyPermission "user.name", "write"; + permission java.util.PropertyPermission "user.home", "write"; +}; + +grant codebase "file:${java.policy.dirs}" { permission java.util.PropertyPermission "user.name", "read"; permission java.util.PropertyPermission "user.home", "read"; }; diff --git a/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java b/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java index e59a504bb00..30f570340e3 100644 --- a/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java +++ b/test/jdk/sun/security/provider/PolicyParser/ExtDirsDefaultPolicy.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,25 +26,34 @@ * @bug 4993819 * @summary standard extensions path is hard-coded in default * system policy file - * @run main/manual ExtDirsDefaultPolicy + * @run main ExtDirsDefaultPolicy */ /* - * Run this test manually with: - * java -Djava.security.manager \ - * -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \ - * -Djava.security.debug=parser \ - * ExtDirsDefaultPolicy + * @test + * @bug 4993819 + * @summary standard extensions path is hard-coded in default + * system policy file * - * To test other varients of the ${{java.ext.dirs}} protocol, remove - * the grant statement for java.ext.dirs in $JAVA_HOME/lib/security/java.policy - * and then run against the 3 different policy files. + * @run main/othervm/policy=ExtDirs1.policy ExtDirsDefaultPolicy + */ + +/* + * @test + * @bug 4993819 + * @summary standard extensions path is hard-coded in default + * system policy file + * + * @run main/othervm/policy=ExtDirs2.policy ExtDirsDefaultPolicy + */ + +/* + * @test + * @bug 4993819 + * @summary standard extensions path is hard-coded in default + * system policy file * - * java -Djava.security.manager \ - * -Djava.ext.dirs=./ExtDirsA:./ExtDirsB \ - * -Djava.security.debug=parser \ - * -Djava.security.policy=ExtDirs{1,2,3}.policy \ - * ExtDirsDefaultPolicy + * @run main/othervm/policy=ExtDirs3.policy ExtDirsDefaultPolicy */ public class ExtDirsDefaultPolicy { diff --git a/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java b/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java index 581dc54216b..01c3dfd06a1 100644 --- a/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java +++ b/test/jdk/sun/security/provider/SeedGenerator/SeedGeneratorChoice.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2010, 2022, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -26,7 +26,7 @@ * @bug 6998583 8141039 * @summary NativeSeedGenerator is making 8192 byte read requests from * entropy pool on each init. - * @run main/othervm -Djava.security.egd=file:/dev/random SeedGeneratorChoice + * @run main/othervm -Djava.security.egd=file:/dev/urandom SeedGeneratorChoice * @run main/othervm -Djava.security.egd=file:filename SeedGeneratorChoice */ diff --git a/test/jdk/sun/security/tools/jarsigner/AutoKeyStore.java b/test/jdk/sun/security/tools/jarsigner/AutoKeyStore.java new file mode 100644 index 00000000000..81b99a13098 --- /dev/null +++ b/test/jdk/sun/security/tools/jarsigner/AutoKeyStore.java @@ -0,0 +1,190 @@ +/* + * Copyright (c) 2022, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8281234 + * @summary The -protected option is not always checked in keytool and jarsigner + * @library /test/lib + * @modules java.base/sun.security.tools.keytool + * java.base/sun.security.x509 + */ + +import jdk.test.lib.Asserts; +import jdk.test.lib.SecurityTools; +import jdk.test.lib.util.JarUtils; +import sun.security.tools.keytool.CertAndKeyGen; +import sun.security.x509.X500Name; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.*; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Collections; +import java.util.Date; +import java.util.Enumeration; +import java.util.List; +import java.util.jar.JarFile; + +public class AutoKeyStore { + + public static void main(String[] args) throws Exception { + + JarUtils.createJarFile(Path.of("unsigned.jar"), Path.of("."), + Files.writeString(Path.of("file"), "hello")); + + SecurityTools.keytool(""" + -J--add-exports -Jjava.base/sun.security.tools.keytool=ALL-UNNAMED + -J--add-exports -Jjava.base/sun.security.x509=ALL-UNNAMED + -providerClass AutoKeyStore$AutoProvider + -providerPath $test.classes + -storetype AUTO -keystore NONE -protected + -list + """).shouldHaveExitValue(0) + .shouldContain("Keystore type: AUTO") + .shouldContain("Keystore provider: AUTO") + .shouldContain("PrivateKeyEntry"); + + SecurityTools.jarsigner(""" + -J--add-exports -Jjava.base/sun.security.tools.keytool=ALL-UNNAMED + -J--add-exports -Jjava.base/sun.security.x509=ALL-UNNAMED + -J-cp -J$test.classes + -providerClass AutoKeyStore$AutoProvider + -storetype AUTO -keystore NONE -protected + -signedJar signed.jar + unsigned.jar + one + """).shouldHaveExitValue(0) + .shouldContain("jar signed."); + + Asserts.assertTrue(new JarFile("signed.jar") + .getEntry("META-INF/ONE.EC") != null); + } + + public static class AutoProvider extends Provider { + public AutoProvider() { + super("AUTO", "1.1.1", "auto"); + put("KeyStore.AUTO", "AutoKeyStore$KeyStoreImpl"); + } + } + + // This keystore is not based on file. Whenever it's loaded + // a self-sign certificate is generated inside + public static class KeyStoreImpl extends KeyStoreSpi { + + private PrivateKey pri; + private PublicKey pub; + private X509Certificate cert; + + @Override + public Key engineGetKey(String alias, char[] password) { + return pri; + } + + @Override + public Certificate[] engineGetCertificateChain(String alias) { + return new Certificate[] { cert }; + } + + @Override + public Certificate engineGetCertificate(String alias) { + return cert; + } + + @Override + public Date engineGetCreationDate(String alias) { + return new Date(); + } + + @Override + public void engineSetKeyEntry(String alias, Key key, char[] password, Certificate[] chain) throws KeyStoreException { + throw new KeyStoreException("Not supported"); + } + + @Override + public void engineSetKeyEntry(String alias, byte[] key, Certificate[] chain) throws KeyStoreException { + throw new KeyStoreException("Not supported"); + } + + @Override + public void engineSetCertificateEntry(String alias, Certificate cert) throws KeyStoreException { + throw new KeyStoreException("Not supported"); + } + + @Override + public void engineDeleteEntry(String alias) throws KeyStoreException { + throw new KeyStoreException("Not supported"); + } + + @Override + public Enumeration engineAliases() { + return Collections.enumeration(List.of("one")); + } + + @Override + public boolean engineContainsAlias(String alias) { + return alias.equalsIgnoreCase("one"); + } + + @Override + public int engineSize() { + return 1; + } + + @Override + public boolean engineIsKeyEntry(String alias) { + return true; + } + + @Override + public boolean engineIsCertificateEntry(String alias) { + return false; + } + + @Override + public String engineGetCertificateAlias(Certificate cert) { + return "one"; + } + + @Override + public void engineStore(OutputStream stream, char[] password) { + } + + @Override + public void engineLoad(InputStream stream, char[] password) throws IOException { + try { + CertAndKeyGen cag = new CertAndKeyGen("EC", "SHA256withECDSA"); + cag.generate("secp256r1"); + pri = cag.getPrivateKey(); + pub = cag.getPublicKey(); + cert = cag.getSelfCertificate(new X500Name("CN=one"), 3600); + } catch (Exception e) { + throw new IOException("Not loaded"); + } + } + } +} diff --git a/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java b/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java index 85f185ebd0c..94b60f41867 100644 --- a/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java +++ b/test/jdk/sun/security/tools/jarsigner/PreserveRawManifestEntryAndDigest.java @@ -244,9 +244,8 @@ String[] fromFirstToSecondEmptyLine(String[] lines) { * @see "concise_jarsigner.sh" */ String[] getExpectedJarSignerOutputUpdatedContentNotValidatedBySignerA( - String jarFilename, String digestalg, String firstAddedFilename, String secondAddedFilename) { - final String TS = ".{28,29}"; // matches a timestamp + final String TS = ".{28,34}"; // matches a timestamp List expLines = new ArrayList<>(); expLines.add("s k *\\d+ " + TS + " META-INF/MANIFEST[.]MF"); expLines.add(" *\\d+ " + TS + " META-INF/B[.]SF"); @@ -348,7 +347,6 @@ String test(String name, assertMatchByLines( fromFirstToSecondEmptyLine(o.getStdout().split("\\R")), getExpectedJarSignerOutputUpdatedContentNotValidatedBySignerA( - jarFilename4, digestalg, firstAddedFilename, secondAddedFilename)); // double-check reading the files with a verifying JarFile diff --git a/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java b/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java index b01ad901479..82ace9c755f 100644 --- a/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java +++ b/test/jdk/sun/security/tools/jarsigner/compatibility/Compatibility.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2017, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2017, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -31,7 +31,7 @@ * its usages, please look through the README. * * @library /test/lib ../warnings - * @compile -source 1.7 -target 1.7 JdkUtils.java + * @compile -source 1.8 -target 1.8 JdkUtils.java * @run main/manual/othervm Compatibility */ @@ -67,7 +67,6 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; -import jdk.test.lib.Platform; import jdk.test.lib.process.OutputAnalyzer; import jdk.test.lib.process.ProcessTools; import jdk.test.lib.util.JarUtils; @@ -460,7 +459,7 @@ private static int[] keySizes(String keyAlgorithm) throws IOException { if (RSA.equals(keyAlgorithm) || DSA.equals(keyAlgorithm)) { return new int[] { 1024, 2048, 0 }; // 0 is no keysize specified } else if (EC.equals(keyAlgorithm)) { - return new int[] { 384, 571, 0 }; // 0 is no keysize specified + return new int[] { 384, 521, 0 }; // 0 is no keysize specified } else { throw new RuntimeException("problem determining key sizes"); } @@ -717,7 +716,7 @@ private static void verifying(SignItem signItem, VerifyItem verifyItem) try { String match = "^ (" + " Signature algorithm: " + signItem.certInfo. - expectedSigalg() + ", " + signItem.certInfo. + expectedSigalg(signItem) + ", " + signItem.certInfo. expectedKeySize() + "-bit key" + ")|(" + " Digest algorithm: " + signItem.expectedDigestAlg() @@ -845,6 +844,7 @@ private static Status verifyingStatus(SignItem signItem, VerifyItem if (isWeakAlg(signItem.expectedDigestAlg()) && line.contains(Test.WEAK_ALGORITHM_WARNING)) continue; + if (line.contains(Test.WEAK_KEY_WARNING)) continue; if (Test.CERTIFICATE_SELF_SIGNED.equals(line)) continue; if (Test.HAS_EXPIRED_CERT_VERIFYING_WARNING.equals(line) && signItem.certInfo.expired) continue; @@ -1036,15 +1036,9 @@ private static OutputAnalyzer execTool(String toolPath, String... args) long start = System.currentTimeMillis(); try { String[] cmd; - if (Platform.isWindows()) { - cmd = new String[args.length + 3]; - System.arraycopy(args, 0, cmd, 3, args.length); - } else { - cmd = new String[args.length + 4]; - cmd[3] = "-J-Djava.security.egd=file:/dev/./urandom"; - System.arraycopy(args, 0, cmd, 4, args.length); - } + cmd = new String[args.length + 3]; + System.arraycopy(args, 0, cmd, 3, args.length); cmd[0] = toolPath; cmd[1] = "-J-Duser.language=en"; cmd[2] = "-J-Duser.country=US"; @@ -1189,19 +1183,56 @@ private String sigalg() { } private String expectedSigalg() { - return (DEFAULT.equals(this.digestAlgorithm) ? this.digestAlgorithm - : "SHA-256").replace("-", "") + "with" + - keyAlgorithm + (EC.equals(keyAlgorithm) ? "DSA" : ""); + return "SHA256with" + keyAlgorithm + (EC.equals(keyAlgorithm) ? "DSA" : ""); + } + + private String expectedSigalg(SignItem signer) { + if (!DEFAULT.equals(digestAlgorithm)) { + return "SHA256with" + keyAlgorithm + (EC.equals(keyAlgorithm) ? "DSA" : ""); + + } else { + // default algorithms documented for jarsigner here: + // https://docs.oracle.com/en/java/javase/17/docs/specs/man/jarsigner.html#supported-algorithms + // https://docs.oracle.com/en/java/javase/20/docs/specs/man/jarsigner.html#supported-algorithms + int expectedKeySize = expectedKeySize(); + switch (keyAlgorithm) { + case DSA: + return "SHA256withDSA"; + case RSA: { + if ((signer.jdkInfo.majorVersion >= 20 && expectedKeySize < 624) + || (signer.jdkInfo.majorVersion < 20 && expectedKeySize <= 3072)) { + return "SHA256withRSA"; + } else if (expectedKeySize <= 7680) { + return "SHA384withRSA"; + } else { + return "SHA512withRSA"; + } + } + case EC: { + if (signer.jdkInfo.majorVersion < 20 && expectedKeySize < 384) { + return "SHA256withECDSA"; + } else if (expectedKeySize < 512) { + return "SHA384withECDSA"; + } else { + return "SHA512withECDSA"; + } + } + default: + throw new RuntimeException("Unsupported/expected key algorithm: " + keyAlgorithm); + } + } } private int expectedKeySize() { if (keySize != 0) return keySize; // defaults - if (RSA.equals(keyAlgorithm) || DSA.equals(keyAlgorithm)) { + if (RSA.equals(keyAlgorithm)) { + return jdkInfo.majorVersion >= 20 ? 3072 : 2048; + } else if (DSA.equals(keyAlgorithm)) { return 2048; } else if (EC.equals(keyAlgorithm)) { - return 256; + return jdkInfo.majorVersion >= 20 ? 384 : 256; } else { throw new RuntimeException("problem determining key size"); } @@ -1397,7 +1428,9 @@ private SignItem digestAlgorithm(String digestAlgorithm) { } String expectedDigestAlg() { - return digestAlgorithm != null ? digestAlgorithm : "SHA-256"; + return digestAlgorithm != null + ? digestAlgorithm + : jdkInfo.majorVersion >= 20 ? "SHA-384" : "SHA-256"; } private SignItem tsaDigestAlgorithm(String tsaDigestAlgorithm) { @@ -1546,7 +1579,7 @@ private static String reportRow(SignItem signItem, VerifyItem verifyItem) { s_values_add.accept(i -> i.unsignedJar + " -> " + i.signedJar); s_values_add.accept(i -> i.certInfo.toString()); s_values_add.accept(i -> i.jdkInfo.version); - s_values_add.accept(i -> i.certInfo.expectedSigalg()); + s_values_add.accept(i -> i.certInfo.expectedSigalg(i)); s_values_add.accept(i -> null2Default(i.digestAlgorithm, i.expectedDigestAlg())); s_values_add.accept(i -> i.tsaIndex == -1 ? "" : diff --git a/test/jdk/sun/security/tools/jarsigner/warnings/Test.java b/test/jdk/sun/security/tools/jarsigner/warnings/Test.java index c0a9c4a521b..71d4ee144b9 100644 --- a/test/jdk/sun/security/tools/jarsigner/warnings/Test.java +++ b/test/jdk/sun/security/tools/jarsigner/warnings/Test.java @@ -148,6 +148,9 @@ public abstract class Test { = "algorithm is considered a security risk. " + "This algorithm will be disabled in a future update."; + static final String WEAK_KEY_WARNING + = "This key size will be disabled in a future update."; + static final String JAR_SIGNED = "jar signed."; static final String JAR_VERIFIED = "jar verified."; diff --git a/test/jdk/sun/security/validator/samedn.sh b/test/jdk/sun/security/validator/samedn.sh index 68298d2bae6..912bbcd40c7 100644 --- a/test/jdk/sun/security/validator/samedn.sh +++ b/test/jdk/sun/security/validator/samedn.sh @@ -1,5 +1,5 @@ # -# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2010, 2024, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. # # This code is free software; you can redistribute it and/or modify it @@ -62,10 +62,11 @@ $KT -genkeypair -alias ca1 -dname CN=CA -keyalg rsa -sigalg md5withrsa -ext bc - $KT -genkeypair -alias ca2 -dname CN=CA -keyalg rsa -sigalg sha1withrsa -ext bc -startdate -1y $KT -genkeypair -alias user -dname CN=User -keyalg rsa -# 2. Signing: ca -> user +# 2. Signing: ca -> user. The startdate is set to 1 minute in the past to ensure the certificate +# is valid at the time of validation and to prevent any issues with timing discrepancies -$KT -certreq -alias user | $KT -gencert -rfc -alias ca1 > samedn1.certs -$KT -certreq -alias user | $KT -gencert -rfc -alias ca2 > samedn2.certs +$KT -certreq -alias user | $KT -gencert -rfc -alias ca1 -startdate -1M > samedn1.certs +$KT -certreq -alias user | $KT -gencert -rfc -alias ca2 -startdate -1M > samedn2.certs # 3. Append the ca file diff --git a/test/jdk/sun/security/x509/DNSName/LeadingPeriod.java b/test/jdk/sun/security/x509/DNSName/LeadingPeriod.java new file mode 100644 index 00000000000..2fa5eb6b8b5 --- /dev/null +++ b/test/jdk/sun/security/x509/DNSName/LeadingPeriod.java @@ -0,0 +1,69 @@ +/* + * Copyright (c) 2023, 2025, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8311546 + * @summary Adopt de-facto standards on x509 Name Constraints with leading dot. Certs + * can be generated by running generate-certs.sh + * @run main LeadingPeriod + */ + +import java.io.*; +import java.nio.file.*; +import java.util.*; +import java.security.Security; +import java.security.cert.*; + +public class LeadingPeriod { + + public static void main(String[] args) throws Exception { + String certs = System.getProperty("test.src", "./") + "/certs/"; + validate(certs + "withoutLeadingPeriod"); + validate(certs + "withLeadingPeriod"); + } + + public static void validate(String certPath) throws Exception { + byte[] targetCertBytes = Files.readAllBytes(Paths.get(certPath + "/leaf.pem")); + byte[] caCertBytes = Files.readAllBytes(Paths.get(certPath + "/ca.pem")); + + CertificateFactory cf = CertificateFactory.getInstance("X.509"); + Certificate caCert = cf.generateCertificate(new ByteArrayInputStream(caCertBytes)); + Certificate targetCert = cf.generateCertificate(new ByteArrayInputStream(targetCertBytes)); + + TrustAnchor anchor = new TrustAnchor((X509Certificate) caCert, null); + + PKIXParameters params = new PKIXParameters(Collections.singleton(anchor)); + + // Disable certificate revocation checking + params.setRevocationEnabled(false); + + // Set validity date, so that validation won't fail when cert expires + params.setDate(((X509Certificate)targetCert).getNotBefore()); + + CertPath path = cf.generateCertPath(List.of(targetCert, caCert)); + + CertPathValidator validator = CertPathValidator.getInstance("PKIX"); + validator.validate(path, params); + } +} diff --git a/test/jdk/sun/security/x509/DNSName/certs/generate-certs.sh b/test/jdk/sun/security/x509/DNSName/certs/generate-certs.sh new file mode 100644 index 00000000000..f000bfc9cda --- /dev/null +++ b/test/jdk/sun/security/x509/DNSName/certs/generate-certs.sh @@ -0,0 +1,91 @@ +#!/usr/bin/env bash + +set -e + +############################################################### +# CA with a leading period in the name constraint # +############################################################### +mkdir -p withLeadingPeriod + +openssl req \ + -newkey rsa:1024 \ + -keyout withLeadingPeriod/ca.key \ + -out withLeadingPeriod/ca.csr \ + -subj "/C=US/O=Example/CN=Example CA with period" \ + -nodes + +openssl x509 \ + -req \ + -in withLeadingPeriod/ca.csr \ + -extfile openssl.cnf \ + -extensions withLeadingPeriod \ + -signkey withLeadingPeriod/ca.key \ + -out withLeadingPeriod/ca.pem + +# leaf certificate +openssl req \ + -newkey rsa:1024 \ + -keyout withLeadingPeriod/leaf.key \ + -out withLeadingPeriod/leaf.csr \ + -subj '/CN=demo.example.com' \ + -addext 'subjectAltName = DNS:demo.example.com' \ + -nodes + +openssl x509 \ + -req \ + -in withLeadingPeriod/leaf.csr \ + -CAcreateserial \ + -CA withLeadingPeriod/ca.pem \ + -CAkey withLeadingPeriod/ca.key \ + -out withLeadingPeriod/leaf.pem + + +# ################################################################## +# # CA without a leading period in the name contraint # +# ################################################################## +mkdir -p withoutLeadingPeriod + +openssl req \ + -newkey rsa:1024 \ + -keyout withoutLeadingPeriod/ca.key \ + -out withoutLeadingPeriod/ca.csr \ + -subj "/C=US/O=Example/CN=Example CA without period" \ + -nodes + +openssl x509 \ + -req \ + -in withoutLeadingPeriod/ca.csr \ + -extfile openssl.cnf \ + -extensions withoutLeadingPeriod \ + -signkey withoutLeadingPeriod/ca.key \ + -out withoutLeadingPeriod/ca.pem + +# leaf certificate +openssl req \ + -newkey rsa:1024 \ + -keyout withoutLeadingPeriod/leaf.key \ + -out withoutLeadingPeriod/leaf.csr \ + -subj '/CN=demo.example.com' \ + -addext 'subjectAltName = DNS:demo.example.com' \ + -nodes + +openssl x509 \ + -req \ + -in withoutLeadingPeriod/leaf.csr \ + -CAcreateserial \ + -CA withoutLeadingPeriod/ca.pem \ + -CAkey withoutLeadingPeriod/ca.key \ + -out withoutLeadingPeriod/leaf.pem + + +# # Verify both leaf certificates + +set +e +openssl verify \ + -CAfile withLeadingPeriod/ca.pem \ + withLeadingPeriod/leaf.pem + +openssl verify \ + -CAfile withoutLeadingPeriod/ca.pem \ + withoutLeadingPeriod/leaf.pem + \ No newline at end of file diff --git a/test/jdk/sun/security/x509/DNSName/certs/openssl.cnf b/test/jdk/sun/security/x509/DNSName/certs/openssl.cnf new file mode 100644 index 00000000000..a69d206a5fc --- /dev/null +++ b/test/jdk/sun/security/x509/DNSName/certs/openssl.cnf @@ -0,0 +1,40 @@ +# +# OpenSSL configuration file. +# + +[ withLeadingPeriod ] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical,CA:true +keyUsage = critical,keyCertSign +nameConstraints = critical,permitted;DNS:.example.com + +[ withoutLeadingPeriod ] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical,CA:true +keyUsage = critical,keyCertSign +nameConstraints = critical,permitted;DNS:example.com + +[ v3_ca ] +subjectKeyIdentifier = hash +authorityKeyIdentifier = keyid:always,issuer +basicConstraints = critical,CA:true +keyUsage = critical,keyCertSign + + +[req] +distinguished_name = req_distinguished_name +x509_extensions = v3_ca # The extentions to add to self signed certs +req_extensions = v3_req # The extensions to add to req's + +prompt = no + +[req_distinguished_name] +C = US +O = Example +CN = example.com + +[v3_req] +keyUsage = keyEncipherment, dataEncipherment +extendedKeyUsage = serverAuth diff --git a/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/ca.pem b/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/ca.pem new file mode 100644 index 00000000000..535a8d9fc7e --- /dev/null +++ b/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/ca.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE----- +MIICgzCCAeygAwIBAgIJANBGv+BGZZHtMA0GCSqGSIb3DQEBCwUAMEAxCzAJBgNV +BAYTAlVTMRAwDgYDVQQKDAdFeGFtcGxlMR8wHQYDVQQDDBZFeGFtcGxlIENBIHdp +dGggcGVyaW9kMB4XDTIzMTAxOTIwNTE0NVoXDTIzMTExODIwNTE0NVowQDELMAkG +A1UEBhMCVVMxEDAOBgNVBAoMB0V4YW1wbGUxHzAdBgNVBAMMFkV4YW1wbGUgQ0Eg +d2l0aCBwZXJpb2QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAPfaISk+Dvzk +m3AY7IDZYrGWpwxHciacalrsrOFl3mj3FQ/kVhofDri3mE7bxNKWyHNcbt+Cteck +TsGKBH85QsIifju7hqlrR+UbYtQF9/REkxX72gzim4xGk9KmKkuGpT5aZgvTE5eg +ZumJ9XxCjGn5nbsdJoqAE/9B96GqXJvlAgMBAAGjgYQwgYEwHQYDVR0OBBYEFG8h +vtka47iFUsc+3wmQ3LQRXUv3MB8GA1UdIwQYMBaAFG8hvtka47iFUsc+3wmQ3LQR +XUv3MA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgIEMB4GA1UdHgEB/wQU +MBKgEDAOggwuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADgYEAkPeCbKokI067 +Dt2bommouO7LhTXivjMsByfZs8i9LZUVJz5Is+mDC36nLy4U3+QhofRLlEkWyOlE +033xBtm4YPsazpur79PJtvZemV0KwwMtKCoJYNlcy2llmdKjUwe4PsPnJPqH2KL5 +Cxios1gil8XL5OCmEUSCT9uBblh+9gk= +-----END CERTIFICATE----- diff --git a/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/leaf.pem b/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/leaf.pem new file mode 100644 index 00000000000..c587ca20c9a --- /dev/null +++ b/test/jdk/sun/security/x509/DNSName/certs/withLeadingPeriod/leaf.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB0jCCATsCCQCgOCS7vOUOXTANBgkqhkiG9w0BAQsFADBAMQswCQYDVQQGEwJV +UzEQMA4GA1UECgwHRXhhbXBsZTEfMB0GA1UEAwwWRXhhbXBsZSBDQSB3aXRoIHBl +cmlvZDAeFw0yMzEwMTkyMDUxNDVaFw0yMzExMTgyMDUxNDVaMBsxGTAXBgNVBAMM +EGRlbW8uZXhhbXBsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBALxi +O4r50rNBbHu/blOSRfo9Vqei+QFS7fPwme68FOcvG+uYXf7zluO59V+8O4RPO+ZJ +W6meZvtpOCWFvlSMhBLTRz350LuSPWF+/tnbiyEv487Vi6Tp7kxJytIcMtH/sWkw +hF0Og8YYt3Xm2aLYPxZHGkvOccjau5X1xG1YiULzAgMBAAEwDQYJKoZIhvcNAQEL +BQADgYEA8OXnFO3yZSVmQfYvC2o9amYa7tNUPHgvEjp7xDlPkvL5zF+n8k0hT0kt +pv4BXzRqVIWsZcNi3H1wk6LMeUXi8EWCOR6gclWI0wZkWBhtoh8SCd2VJRmcv+zG +EnInCapszNKN05KEzaFOQv0QayILBUGgHTTXOgbEmryLHXg6zik= +-----END CERTIFICATE----- diff --git a/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/ca.pem b/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/ca.pem new file mode 100644 index 00000000000..cb886c34a1d --- /dev/null +++ b/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/ca.pem @@ -0,0 +1,16 @@ +-----BEGIN CERTIFICATE----- +MIICiDCCAfGgAwIBAgIJALUX88nU2b75MA0GCSqGSIb3DQEBCwUAMEMxCzAJBgNV +BAYTAlVTMRAwDgYDVQQKDAdFeGFtcGxlMSIwIAYDVQQDDBlFeGFtcGxlIENBIHdp +dGhvdXQgcGVyaW9kMB4XDTIzMTAxOTIwNTE0NVoXDTIzMTExODIwNTE0NVowQzEL +MAkGA1UEBhMCVVMxEDAOBgNVBAoMB0V4YW1wbGUxIjAgBgNVBAMMGUV4YW1wbGUg +Q0Egd2l0aG91dCBwZXJpb2QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBANmH +HqVoDjgoS60aPhQisqEL3as81tPXxXgnp5M0TE+Lb0z/kXS2mkqYYhzcZneBhVyI +oGTnSnTSh6S1r/gE80x+hH4ZrLZR7jJMRDA9Q7RTOZBNgozS4XnE3AV/EjrIzHJ1 +IEt1ezoj2QNdVOv7UHprHGoARl9tdxre4MVUv4S3AgMBAAGjgYMwgYAwHQYDVR0O +BBYEFFG0Mvse4c5C01o8kvKiM4MKMJTCMB8GA1UdIwQYMBaAFFG0Mvse4c5C01o8 +kvKiM4MKMJTCMA8GA1UdEwEB/wQFMAMBAf8wDgYDVR0PAQH/BAQDAgIEMB0GA1Ud +HgEB/wQTMBGgDzANggtleGFtcGxlLmNvbTANBgkqhkiG9w0BAQsFAAOBgQC0CKS0 +JOR8hfUkZHBo52PrF3IKs33wczH5mfV+HLTdSeKtBD0Vj/7DoT0Yx2k5n6vpwA/x +LTSMC4wUo4hb5164ks45iloU0FrA+n9fWbeqwhQb+DW5MSOgoVLkW+rcdKbDatTO +ENcKZsqiG3aKM7pS7mQa+kUUpXWBUgVnhcsYtQ== +-----END CERTIFICATE----- diff --git a/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/leaf.pem b/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/leaf.pem new file mode 100644 index 00000000000..449176ff8a8 --- /dev/null +++ b/test/jdk/sun/security/x509/DNSName/certs/withoutLeadingPeriod/leaf.pem @@ -0,0 +1,12 @@ +-----BEGIN CERTIFICATE----- +MIIB1TCCAT4CCQDLscehyPPGXjANBgkqhkiG9w0BAQsFADBDMQswCQYDVQQGEwJV +UzEQMA4GA1UECgwHRXhhbXBsZTEiMCAGA1UEAwwZRXhhbXBsZSBDQSB3aXRob3V0 +IHBlcmlvZDAeFw0yMzEwMTkyMDUxNDVaFw0yMzExMTgyMDUxNDVaMBsxGTAXBgNV +BAMMEGRlbW8uZXhhbXBsZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGB +AMZM9Prp5DkAe4pkLqn4v8DFamMtWVqPlYacJacGzBkuzBn8VNQQw4qnf6wiVHBj +uXLHrUCbldtKFK4XdVukmVyYSLR5BBPxA20fjZcsrBZW7u/14qWmIZW7G0xphezg +6g33qNPq9CPqVHR+IrfEmjWnLjc2KrZ3OQElpJOGp48hAgMBAAEwDQYJKoZIhvcN +AQELBQADgYEAYbIuAQKTXsgaBP3pyMqxPHvklDI7wJjEapbKDsOXYmKMb33pmFSD +ntQFZuOKYNV2rAqQaV/3kiWKyR4vO/gsCfuFeW8kxkhZEXX9CNU0Z6mKcvy274A4 +K0gqYGki8hyCc5IMWTUAX2TLdq8W1hwfbjeiNqTY21e+6lIa3kcuLC0= +-----END CERTIFICATE----- diff --git a/test/jdk/sun/security/x509/URICertStore/AIACertTimeout.java b/test/jdk/sun/security/x509/URICertStore/AIACertTimeout.java new file mode 100644 index 00000000000..487f5e2471c --- /dev/null +++ b/test/jdk/sun/security/x509/URICertStore/AIACertTimeout.java @@ -0,0 +1,292 @@ +/* + * Copyright (c) 2023, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8179502 + * @summary Enhance OCSP, CRL and Certificate Fetch Timeouts + * @modules java.base/sun.security.x509 + * java.base/sun.security.util + * @library /test/lib ../../../../java/security/testlibrary + * @build CertificateBuilder + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=1 AIACertTimeout 5000 false + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=1s AIACertTimeout 5000 false + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=4 AIACertTimeout 1000 true + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=1500ms AIACertTimeout 5000 false + * @run main/othervm -Dcom.sun.security.enableAIAcaIssuers=true + * -Dcom.sun.security.cert.readtimeout=4500ms AIACertTimeout 1000 true + * @run main/othervm -Djava.security.debug=certpath + * -Dcom.sun.security.enableAIAcaIssuers=false + * -Dcom.sun.security.cert.readtimeout=20000ms AIACertTimeout 10000 false + */ + +import com.sun.net.httpserver.*; +import java.io.*; +import java.math.BigInteger; +import java.net.InetSocketAddress; +import java.security.cert.*; +import java.security.KeyPair; +import java.security.KeyPairGenerator; +import java.security.spec.*; +import java.util.*; +import java.util.concurrent.TimeUnit; + +import sun.security.testlibrary.CertificateBuilder; + +import sun.security.x509.*; +import sun.security.util.*; + +public class AIACertTimeout { + + private static final boolean logging = true; + + // PKI and server components we will need for this test + private static KeyPair rootKp; // Root CA keys + private static X509Certificate rootCert; + private static KeyPair intKp; // Intermediate CA keys + private static X509Certificate intCert; + private static KeyPair eeKp; // End-entity keys + private static X509Certificate eeCert; + + public static void main(String[] args) throws Exception { + int servTimeoutMsec = (args != null && args.length >= 1) ? + Integer.parseInt(args[0]) : -1; + boolean expectedPass = args != null && args.length >= 2 && + Boolean.parseBoolean(args[1]); + + createAuthorities(); + CaCertHttpServer aiaServer = new CaCertHttpServer(intCert, + servTimeoutMsec); + try { + aiaServer.start(); + createEE(aiaServer.getAddress()); + + X509CertSelector target = new X509CertSelector(); + target.setCertificate(eeCert); + PKIXParameters params = new PKIXBuilderParameters(Set.of( + new TrustAnchor(rootCert, null)), target); + params.setRevocationEnabled(false); + + try { + CertPathBuilder cpb = CertPathBuilder.getInstance("PKIX"); + CertPathBuilderResult result = cpb.build(params); + if (expectedPass) { + int pathLen = result.getCertPath().getCertificates().size(); + if (pathLen != 2) { + throw new RuntimeException("Expected 2 certificates " + + "in certpath, got " + pathLen); + } + } else { + throw new RuntimeException("Missing expected CertPathBuilderException"); + } + } catch (CertPathBuilderException cpve) { + if (!expectedPass) { + log("Cert path building failed as expected: " + cpve); + } else { + throw cpve; + } + } + } finally { + aiaServer.stop(); + } + } + + private static class CaCertHttpServer { + + private final X509Certificate caCert; + private final HttpServer server; + private final int timeout; + + public CaCertHttpServer(X509Certificate cert, int timeout) + throws IOException { + caCert = Objects.requireNonNull(cert, "Null CA cert disallowed"); + server = HttpServer.create(); + this.timeout = timeout; + if (timeout > 0) { + log("Created HttpServer with timeout of " + timeout + " msec."); + } else { + log("Created HttpServer with no timeout"); + } + } + + public void start() throws IOException { + server.bind(new InetSocketAddress("localhost", 0), 0); + server.createContext("/cacert", t -> { + try (InputStream is = t.getRequestBody()) { + is.readAllBytes(); + } + try { + if (timeout > 0) { + // Sleep in order to simulate network latency + log("Server sleeping for " + timeout + " msec."); + Thread.sleep(timeout); + } + + byte[] derCert = caCert.getEncoded(); + t.getResponseHeaders().add("Content-Type", + "application/pkix-cert"); + t.sendResponseHeaders(200, derCert.length); + try (OutputStream os = t.getResponseBody()) { + os.write(derCert); + } + } catch (InterruptedException | + CertificateEncodingException exc) { + throw new IOException(exc); + } + }); + server.setExecutor(null); + server.start(); + log("Started HttpServer: Listening on " + server.getAddress()); + } + + public void stop() { + server.stop(0); + } + + public InetSocketAddress getAddress() { + return server.getAddress(); + } + } + + + /** + * Creates the CA PKI components necessary for this test. + */ + private static void createAuthorities() throws Exception { + CertificateBuilder cbld = new CertificateBuilder(); + KeyPairGenerator keyGen = KeyPairGenerator.getInstance("EC"); + keyGen.initialize(new ECGenParameterSpec("secp256r1")); + + // Generate Root, IntCA, EE keys + rootKp = keyGen.genKeyPair(); + log("Generated Root CA KeyPair"); + intKp = keyGen.genKeyPair(); + log("Generated Intermediate CA KeyPair"); + eeKp = keyGen.genKeyPair(); + log("Generated End Entity Cert KeyPair"); + + // Make a 3 year validity starting from 60 days ago + long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(60); + long end = start + TimeUnit.DAYS.toMillis(1085); + + boolean[] kuBitSettings = {true, false, false, false, false, true, + true, false, false}; + + // Set up the Root CA Cert + cbld.setSubjectName("CN=Root CA Cert, O=SomeCompany"). + setPublicKey(rootKp.getPublic()). + setSerialNumber(new BigInteger("1")). + setValidity(new Date(start), new Date(end)). + addSubjectKeyIdExt(rootKp.getPublic()). + addAuthorityKeyIdExt(rootKp.getPublic()). + addBasicConstraintsExt(true, true, -1). + addKeyUsageExt(kuBitSettings); + + // Make our Root CA Cert! + rootCert = cbld.build(null, rootKp.getPrivate(), "SHA256withECDSA"); + log("Root CA Created:\n" + certInfo(rootCert)); + + // Make a 2 year validity starting from 30 days ago + start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(30); + end = start + TimeUnit.DAYS.toMillis(730); + + // Now that we have the root keystore we can create our + // intermediate CA. + cbld.reset(); + cbld.setSubjectName("CN=Intermediate CA Cert, O=SomeCompany"). + setPublicKey(intKp.getPublic()). + setSerialNumber(new BigInteger("100")). + setValidity(new Date(start), new Date(end)). + addSubjectKeyIdExt(intKp.getPublic()). + addAuthorityKeyIdExt(rootKp.getPublic()). + addBasicConstraintsExt(true, true, -1). + addKeyUsageExt(kuBitSettings); + + // Make our Intermediate CA Cert! + intCert = cbld.build(rootCert, rootKp.getPrivate(), "SHA256withECDSA"); + log("Intermediate CA Created:\n" + certInfo(intCert)); + } + + /** + * Creates the end entity certificate from the previously generated + * intermediate CA cert. + * + * @param aiaAddr the address/port of the server that will hold the issuer + * certificate. This will be used to create an AIA URI. + */ + private static void createEE(InetSocketAddress aiaAddr) throws Exception { + // Make a 1 year validity starting from 7 days ago + long start = System.currentTimeMillis() - TimeUnit.DAYS.toMillis(7); + long end = start + TimeUnit.DAYS.toMillis(365); + boolean[] kuBits = {true, false, false, false, false, false, + false, false, false}; + List ekuOids = List.of("1.3.6.1.5.5.7.3.1", + "1.3.6.1.5.5.7.3.2", "1.3.6.1.5.5.7.3.4"); + String aiaUri = String.format("http://%s:%d/cacert", + aiaAddr.getHostName(), aiaAddr.getPort()); + + CertificateBuilder cbld = new CertificateBuilder(); + cbld.setSubjectName("CN=Oscar T. Grouch, O=SomeCompany"). + setPublicKey(eeKp.getPublic()). + setSerialNumber(new BigInteger("4096")). + setValidity(new Date(start), new Date(end)). + addSubjectKeyIdExt(eeKp.getPublic()). + addAuthorityKeyIdExt(intKp.getPublic()). + addKeyUsageExt(kuBits).addExtendedKeyUsageExt(ekuOids). + addAIAExt(List.of("CAISSUER|" + aiaUri)); + + // Build the cert + eeCert = cbld.build(intCert, intKp.getPrivate(), "SHA256withECDSA"); + log("EE Certificate Created:\n" + certInfo(eeCert)); + } + + /** + * Helper routine that dumps only a few cert fields rather than + * the whole toString() output. + * + * @param cert an X509Certificate to be displayed + * + * @return the String output of the issuer, subject and + * serial number + */ + private static String certInfo(X509Certificate cert) { + StringBuilder sb = new StringBuilder(); + sb.append("Issuer: ").append(cert.getIssuerX500Principal()). + append("\n"); + sb.append("Subject: ").append(cert.getSubjectX500Principal()). + append("\n"); + sb.append("Serial: ").append(cert.getSerialNumber()).append("\n"); + return sb.toString(); + } + + private static void log(String str) { + if (logging) { + System.out.println("[" + Thread.currentThread().getName() + "] " + + str); + } + } +} diff --git a/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java b/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java index 05ec77b51e5..5018c844556 100644 --- a/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java +++ b/test/jdk/sun/security/x509/URICertStore/CRLReadTimeout.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2023, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,55 +23,70 @@ /* * @test - * @bug 8191808 + * @bug 8191808 8179502 * @summary check that CRL download is interrupted if it takes too long + * @modules java.base/sun.security.x509 + * java.base/sun.security.util * @library /test/lib - * @run main/othervm -Dcom.sun.security.crl.readtimeout=1 CRLReadTimeout + * @run main/othervm -Dcom.sun.security.crl.readtimeout=1 + * CRLReadTimeout 5000 false + * @run main/othervm -Dcom.sun.security.crl.readtimeout=1s + * CRLReadTimeout 5000 false + * @run main/othervm -Dcom.sun.security.crl.readtimeout=4 + * CRLReadTimeout 1000 true + * @run main/othervm -Dcom.sun.security.crl.readtimeout=1500ms + * CRLReadTimeout 5000 false + * @run main/othervm -Dcom.sun.security.crl.readtimeout=4500ms + * CRLReadTimeout 1000 true */ -import java.io.File; -import java.io.InputStream; -import java.io.IOException; +import java.io.*; +import java.math.BigInteger; import java.net.InetSocketAddress; import java.net.SocketTimeoutException; +import java.security.GeneralSecurityException; import java.security.KeyStore; -import java.security.cert.CertificateFactory; -import java.security.cert.CertPath; -import java.security.cert.CertPathValidator; -import java.security.cert.CertPathValidatorException; -import java.security.cert.PKIXParameters; -import java.security.cert.PKIXRevocationChecker; -import static java.security.cert.PKIXRevocationChecker.Option.*; -import java.security.cert.TrustAnchor; -import java.security.cert.X509Certificate; +import java.security.PrivateKey; +import java.security.cert.*; +import java.util.Date; import java.util.EnumSet; import java.util.List; import java.util.Set; -import com.sun.net.httpserver.HttpServer; +import java.util.concurrent.TimeUnit; + +import static java.security.cert.PKIXRevocationChecker.Option.*; +import com.sun.net.httpserver.HttpServer; import jdk.test.lib.SecurityTools; import jdk.test.lib.process.OutputAnalyzer; +import sun.security.util.SignatureUtil; +import sun.security.x509.*; public class CRLReadTimeout { + public static final String PASS = "changeit"; + public static X509CRL crl; + public static void main(String[] args) throws Exception { - String timeout = System.getProperty("com.sun.security.crl.readtimeout"); - if (timeout == null) { - timeout = "15"; - } - System.out.println("Testing timeout of " + timeout + " seconds"); + int serverTimeout = (args != null && args[0] != null) ? + Integer.parseInt(args[0]) : 15000; + boolean expectedPass = args != null && args[1] != null && + Boolean.parseBoolean(args[1]); + System.out.println("Server timeout is " + serverTimeout + " msec."); + System.out.println("Test is expected to " + (expectedPass ? "pass" : "fail")); - CrlHttpServer crlServer = new CrlHttpServer(Integer.parseInt(timeout)); + CrlHttpServer crlServer = new CrlHttpServer(serverTimeout); try { crlServer.start(); - testTimeout(crlServer.getPort()); + testTimeout(crlServer.getPort(), expectedPass); } finally { crlServer.stop(); } } - private static void testTimeout(int port) throws Exception { + private static void testTimeout(int port, boolean expectedPass) + throws Exception { // create certificate chain with two certs, root and end-entity keytool("-alias duke -dname CN=duke -genkey -keyalg RSA"); @@ -82,10 +97,10 @@ private static void testTimeout(int port) throws Exception { + "-ext crl=uri:http://localhost:" + port + "/crl"); keytool("-importcert -file duke.cert -alias duke"); - KeyStore ks = KeyStore.getInstance(new File("ks"), - "changeit".toCharArray()); + KeyStore ks = KeyStore.getInstance(new File("ks"), PASS.toCharArray()); X509Certificate cert = (X509Certificate)ks.getCertificate("duke"); X509Certificate root = (X509Certificate)ks.getCertificate("root"); + crl = genCrl(ks, "root", PASS); // validate chain CertPathValidator cpv = CertPathValidator.getInstance("PKIX"); @@ -100,28 +115,60 @@ private static void testTimeout(int port) throws Exception { cpv.validate(cp, params); // unwrap soft fail exceptions and check for SocketTimeoutException - boolean expected = false; - for (CertPathValidatorException softFail:prc.getSoftFailExceptions()) { - Throwable cause = softFail.getCause(); - while (cause != null) { - if (cause instanceof SocketTimeoutException) { - expected = true; + List softExc = prc.getSoftFailExceptions(); + if (expectedPass) { + if (softExc.size() > 0) { + throw new RuntimeException("Expected to pass, found " + + softExc.size() + " soft fail exceptions"); + } + } else { + boolean foundSockTOExc = false; + for (CertPathValidatorException softFail : softExc) { + Throwable cause = softFail.getCause(); + while (cause != null) { + if (cause instanceof SocketTimeoutException) { + foundSockTOExc = true; + break; + } + cause = cause.getCause(); + } + if (foundSockTOExc) { break; } - cause = cause.getCause(); } - if (expected) { - break; + if (!foundSockTOExc) { + throw new Exception("SocketTimeoutException not thrown"); } } - if (!expected) { - throw new Exception("SocketTimeoutException not thrown"); - } } private static OutputAnalyzer keytool(String cmd) throws Exception { - return SecurityTools.keytool("-storepass changeit " - + "-keystore ks " + cmd); + return SecurityTools.keytool("-storepass " + PASS + + " -keystore ks " + cmd); + } + + private static X509CRL genCrl(KeyStore ks, String issAlias, String pass) + throws GeneralSecurityException, IOException { + // Create an empty CRL with a 1-day validity period. + X509Certificate issuerCert = (X509Certificate)ks.getCertificate(issAlias); + PrivateKey issuerKey = (PrivateKey)ks.getKey(issAlias, pass.toCharArray()); + + long curTime = System.currentTimeMillis(); + Date thisUp = new Date(curTime - TimeUnit.SECONDS.toMillis(43200)); + Date nextUp = new Date(curTime + TimeUnit.SECONDS.toMillis(43200)); + CRLExtensions exts = new CRLExtensions(); + var aki = new AuthorityKeyIdentifierExtension(new KeyIdentifier( + issuerCert.getPublicKey()), null, null); + var crlNum = new CRLNumberExtension(BigInteger.ONE); + exts.set(aki.getId(), aki); + exts.set(crlNum.getId(), crlNum); + X509CRLImpl crl = new X509CRLImpl( + new X500Name(issuerCert.getSubjectX500Principal().toString()), + thisUp, nextUp, null, exts); + crl.sign(issuerKey, + SignatureUtil.getDefaultSigAlgForKey(issuerKey)); + System.out.println("ISSUED CRL:\n" + crl); + return crl; } private static class CrlHttpServer { @@ -136,15 +183,23 @@ public CrlHttpServer(int timeout) throws IOException { public void start() throws IOException { server.bind(new InetSocketAddress(0), 0); - server.createContext("/", t -> { + server.createContext("/crl", t -> { try (InputStream is = t.getRequestBody()) { is.readAllBytes(); } try { - // sleep for 2 seconds longer to force timeout - Thread.sleep((timeout + 2)*1000); - } catch (InterruptedException ie) { - throw new IOException(ie); + // Sleep in order to simulate network latency + Thread.sleep(timeout); + + byte[] derCrl = crl.getEncoded(); + t.getResponseHeaders().add("Content-Type", + "application/pkix-crl"); + t.sendResponseHeaders(200, derCrl.length); + try (OutputStream os = t.getResponseBody()) { + os.write(derCrl); + } + } catch (InterruptedException | CRLException exc) { + throw new IOException(exc); } }); server.setExecutor(null); diff --git a/test/jdk/sun/util/resources/TimeZone/IntlTest.java b/test/jdk/sun/util/resources/TimeZone/IntlTest.java deleted file mode 100644 index 137a610f3d9..00000000000 --- a/test/jdk/sun/util/resources/TimeZone/IntlTest.java +++ /dev/null @@ -1,228 +0,0 @@ -/* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.lang.reflect.*; -import java.util.Hashtable; -import java.util.Enumeration; -import java.util.Vector; -import java.io.*; -import java.text.*; - -/** - * IntlTest is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

    - * Sub-classes implement a set of methods named Test. Each - * of these methods performs some test. Test methods should indicate - * errors by calling either err or errln. This will increment the - * errorCount field and may optionally print a message to the log. - * Debugging information may also be added to the log via the log - * and logln methods. These methods will add their arguments to the - * log only if the test is being run in verbose mode. - */ -public class IntlTest { - - //------------------------------------------------------------------------ - // Everything below here is boilerplate code that makes it possible - // to add a new test by simply adding a function to an existing class - //------------------------------------------------------------------------ - - protected IntlTest() { - // Create a hashtable containing all the test methods. - testMethods = new Hashtable(); - Method[] methods = getClass().getDeclaredMethods(); - for( int i=0; i paths; if (contentsOnly) { - try (var pathStream = Files.walk(root, 0)) { + try (var pathStream = Files.list(root)) { paths = pathStream.collect(Collectors.toList()); } } else { @@ -664,26 +664,40 @@ public static void assertPathExists(Path path, boolean exists) { assertTrue(path.toFile().exists(), String.format( "Check [%s] path exists", path)); } else { - assertFalse(path.toFile().exists(), String.format( + assertTrue(!path.toFile().exists(), String.format( "Check [%s] path doesn't exist", path)); } } - public static void assertPathNotEmptyDirectory(Path path) { - if (Files.isDirectory(path)) { + public static void assertDirectoryNotEmpty(Path path) { + assertDirectoryExists(path, Optional.of(false)); + } + + public static void assertDirectoryEmpty(Path path) { + assertDirectoryExists(path, Optional.of(true)); + } + + public static void assertDirectoryExists(Path path, Optional isEmptyCheck) { + assertPathExists(path, true); + boolean isDirectory = Files.isDirectory(path); + if (isEmptyCheck.isEmpty() || !isDirectory) { + assertTrue(isDirectory, String.format("Check [%s] is a directory", path)); + } else { ThrowingRunnable.toRunnable(() -> { try (var files = Files.list(path)) { - TKit.assertFalse(files.findFirst().isEmpty(), String.format - ("Check [%s] is not an empty directory", path)); + boolean actualIsEmpty = files.findFirst().isEmpty(); + if (isEmptyCheck.get()) { + TKit.assertTrue(actualIsEmpty, String.format("Check [%s] is not an empty directory", path)); + } else { + TKit.assertTrue(!actualIsEmpty, String.format("Check [%s] is an empty directory", path)); + } } }).run(); - } + } } public static void assertDirectoryExists(Path path) { - assertPathExists(path, true); - assertTrue(path.toFile().isDirectory(), String.format( - "Check [%s] is a directory", path)); + assertDirectoryExists(path, Optional.empty()); } public static void assertFileExists(Path path) { diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java index 27da5a0a28c..bb699ba3b9c 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/TestBuilder.java @@ -392,6 +392,9 @@ private static Stream toMethodCalls(Object[] ctorArgs, Method method } private static Object fromString(String value, Class toType) { + if (toType.isEnum()) { + return Enum.valueOf(toType, value); + } Function converter = conv.get(toType); if (converter == null) { throw new RuntimeException(String.format( diff --git a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java index 1e6080101b3..a19b12ebf27 100644 --- a/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java +++ b/test/jdk/tools/jpackage/helpers/jdk/jpackage/test/WindowsHelper.java @@ -61,6 +61,22 @@ private static Path getInstallationSubDirectory(JPackageCommand cmd) { return Path.of(cmd.getArgumentValue("--install-dir", cmd::name)); } + // Tests have problems on windows where path in the temp dir are too long + // for the wix tools. We can't use a tempDir outside the TKit's WorkDir, so + // we minimize both the tempRoot directory name (above) and the tempDir name + // (below) to the extension part (which is necessary to differenciate between + // the multiple PackageTypes that will be run for one JPackageCommand). + // It might be beter if the whole work dir name was shortened from: + // jtreg_open_test_jdk_tools_jpackage_share_jdk_jpackage_tests_BasicTest_java. + public static Path getTempDirectory(JPackageCommand cmd, Path tempRoot) { + String ext = cmd.outputBundle().getFileName().toString(); + int i = ext.lastIndexOf("."); + if (i > 0 && i < (ext.length() - 1)) { + ext = ext.substring(i+1); + } + return tempRoot.resolve(ext); + } + private static void runMsiexecWithRetries(Executor misexec) { Executor.Result result = null; for (int attempt = 0; attempt < 8; ++attempt) { @@ -132,7 +148,9 @@ static PackageHandlers createExePackageHandlers() { BiConsumer installExe = (cmd, install) -> { cmd.verifyIsOfType(PackageType.WIN_EXE); Executor exec = new Executor().setExecutable(cmd.outputBundle()); - if (!install) { + if (install) { + exec.addArgument("/qn").addArgument("/norestart"); + } else { exec.addArgument("uninstall"); } runMsiexecWithRetries(exec); @@ -257,7 +275,7 @@ private void verifyStartMenuShortcut(Path shortcutsRoot, boolean exists) { Path shortcutPath = shortcutsRoot.resolve(startMenuShortcutPath); verifyShortcut(shortcutPath, exists); if (!exists) { - TKit.assertPathNotEmptyDirectory(shortcutPath.getParent()); + TKit.assertDirectoryNotEmpty(shortcutPath.getParent()); } } diff --git a/test/jdk/tools/jpackage/share/EmptyFolderBase.java b/test/jdk/tools/jpackage/share/EmptyFolderBase.java deleted file mode 100644 index 092996ad039..00000000000 --- a/test/jdk/tools/jpackage/share/EmptyFolderBase.java +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright (c) 2020, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.File; -import java.io.IOException; -import java.nio.file.Path; -import jdk.jpackage.test.TKit; - -public class EmptyFolderBase { - - // Note: To specify file use ".txt" extension. - // Note: createDirStrcture() will call mkdir() or createNewFile() for paths defined - // in dirStruct, so make sure paths are defined in order. - - // folder-empty - // folder-not-empty - // folder-not-empty/folder-empty - // folder-not-empty/another-folder-empty - // folder-not-empty/folder-non-empty2 - // folder-not-empty/folder-non-empty2/file.txt - private static final String [] DIR_STRUCT = { - "folder-empty", - "folder-not-empty", - "folder-not-empty" + File.separator + "folder-empty", - "folder-not-empty" + File.separator + "another-folder-empty", - "folder-not-empty" + File.separator + "folder-non-empty2", - "folder-not-empty" + File.separator + "folder-non-empty2" + File.separator + - "file.txt" - }; - - // See dirStruct - public static void createDirStrcture(Path inputPath) throws IOException { - File input = new File(inputPath.toString()); - input.mkdir(); - - for (String p : DIR_STRUCT) { - File f = new File(input, p); - if (p.endsWith(".txt")) { - f.createNewFile(); - } else { - f.mkdir(); - } - } - } - - public static void validateDirStrcture(Path appDirPath) { - for (String p : DIR_STRUCT) { - Path path = appDirPath.resolve(p); - TKit.assertPathExists(path, true); - } - } -} diff --git a/test/jdk/tools/jpackage/share/EmptyFolderPackageTest.java b/test/jdk/tools/jpackage/share/EmptyFolderPackageTest.java deleted file mode 100644 index c7af050c685..00000000000 --- a/test/jdk/tools/jpackage/share/EmptyFolderPackageTest.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.nio.file.Path; -import jdk.jpackage.internal.ApplicationLayout; -import jdk.jpackage.test.PackageTest; -import jdk.jpackage.test.PackageType; -import jdk.jpackage.test.Annotations.Test; - -/** - * Tests generation of packages with input folder containing empty folders. - */ - -/* - * @test - * @summary jpackage with input containing empty folders - * @library ../helpers - * @library /test/lib - * @key jpackagePlatformPackage - * @build EmptyFolderBase - * @build jdk.jpackage.test.* - * @build EmptyFolderPackageTest - * @modules jdk.jpackage/jdk.jpackage.internal - * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main - * --jpt-run=EmptyFolderPackageTest - */ -public class EmptyFolderPackageTest { - - @Test - public static void test() throws Exception { - new PackageTest().configureHelloApp() - .addInitializer(cmd -> { - Path input = cmd.inputDir(); - EmptyFolderBase.createDirStrcture(input); - }) - .addInstallVerifier(cmd -> { - if (cmd.packageType() == PackageType.WIN_MSI) { - if (cmd.isPackageUnpacked("Not running file " - + "structure check for empty folders")) { - return; - } - } - - ApplicationLayout appLayout = cmd.appLayout(); - Path appDir = appLayout.appDirectory(); - EmptyFolderBase.validateDirStrcture(appDir); - }) - .run(); - } -} diff --git a/test/jdk/tools/jpackage/share/EmptyFolderTest.java b/test/jdk/tools/jpackage/share/EmptyFolderTest.java index a41c4a66702..230d8a039ea 100644 --- a/test/jdk/tools/jpackage/share/EmptyFolderTest.java +++ b/test/jdk/tools/jpackage/share/EmptyFolderTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2021, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -21,44 +21,113 @@ * questions. */ +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; -import jdk.jpackage.test.JPackageCommand; +import jdk.jpackage.test.PackageTest; import jdk.jpackage.test.Annotations.Test; -import jdk.jpackage.internal.ApplicationLayout; +import jdk.jpackage.test.JPackageCommand; +import jdk.jpackage.test.PackageType; +import jdk.jpackage.test.TKit; /** - * Tests generation of app image with input folder containing empty folders. + * Tests generation of packages and app image with input folder containing empty folders. + */ + +/* + * @test + * @summary jpackage for package with input containing empty folders + * @library ../helpers + * @library /test/lib + * @key jpackagePlatformPackage + * @build jdk.jpackage.test.* + * @build EmptyFolderTest + * @modules jdk.jpackage/jdk.jpackage.internal + * @run main/othervm/timeout=720 -Xmx512m jdk.jpackage.test.Main + * --jpt-run=EmptyFolderTest.testPackage */ /* * @test - * @summary jpackage with input containing empty folders + * @summary jpackage for app image with input containing empty folders * @library ../helpers * @library /test/lib - * @build EmptyFolderBase * @build jdk.jpackage.test.* * @build EmptyFolderTest * @modules jdk.jpackage/jdk.jpackage.internal * @run main/othervm -Xmx512m jdk.jpackage.test.Main - * --jpt-run=EmptyFolderTest + * --jpt-run=EmptyFolderTest.testAppImage */ + public class EmptyFolderTest { @Test - public static void test() throws Exception { - JPackageCommand cmd = JPackageCommand.helloAppImage(); + public static void testPackage() { + new PackageTest() + .configureHelloApp() + .addInitializer(EmptyFolderTest::createDirTree) + .addInitializer(cmd -> { + cmd.setArgumentValue("--name", "EmptyFolderPackageTest"); + }) + .addInstallVerifier(EmptyFolderTest::validateDirTree) + .run(); + } + + @Test + public static void testAppImage() throws IOException { + var cmd = JPackageCommand.helloAppImage(); // Add more files into input folder - Path input = cmd.inputDir(); - EmptyFolderBase.createDirStrcture(input); + createDirTree(cmd); // Create app image cmd.executeAndAssertHelloAppImageCreated(); - // Verify directory strcture - ApplicationLayout appLayout = cmd.appLayout(); - Path appDir = appLayout.appDirectory(); - EmptyFolderBase.validateDirStrcture(appDir); + // Verify directory structure + validateDirTree(cmd); + } + + private static void createDirTree(JPackageCommand cmd) throws IOException { + var baseDir = cmd.inputDir(); + for (var path : DIR_STRUCT) { + path = baseDir.resolve(path); + if (isFile(path)) { + Files.createDirectories(path.getParent()); + Files.write(path, new byte[0]); + } else { + Files.createDirectories(path); + } + } + } + + private static void validateDirTree(JPackageCommand cmd) { + var outputBaseDir = cmd.appLayout().appDirectory(); + var inputBaseDir = cmd.inputDir(); + for (var path : DIR_STRUCT) { + Path outputPath = outputBaseDir.resolve(path); + if (isFile(outputPath)) { + TKit.assertFileExists(outputPath); + } else if (!PackageType.WINDOWS.contains(cmd.packageType())) { + TKit.assertDirectoryExists(outputPath); + } else if (inputBaseDir.resolve(path).toFile().list().length == 0) { + // MSI packages don't support empty folders + TKit.assertPathExists(outputPath, false); + } else { + TKit.assertDirectoryNotEmpty(outputPath); + } + } + } + + private static boolean isFile(Path path) { + return path.getFileName().toString().endsWith(".txt"); } + // Note: To specify file use ".txt" extension. + private static final Path [] DIR_STRUCT = { + Path.of("folder-empty"), + Path.of("folder-not-empty"), + Path.of("folder-not-empty", "folder-empty"), + Path.of("folder-not-empty", "another-folder-empty"), + Path.of("folder-not-empty", "folder-non-empty2", "file.txt") + }; } diff --git a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java b/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java index b240b8a5bde..72550fd365b 100644 --- a/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java +++ b/test/jdk/tools/jpackage/share/jdk/jpackage/tests/BasicTest.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2019, 2022, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2019, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -30,7 +30,6 @@ import java.util.ArrayList; import java.util.function.Function; import java.util.function.Predicate; -import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Stream; import jdk.jpackage.test.TKit; @@ -43,6 +42,8 @@ import jdk.jpackage.test.Annotations.Test; import jdk.jpackage.test.Annotations.Parameter; +import static jdk.jpackage.test.WindowsHelper.getTempDirectory; + /* * @test * @summary jpackage basic testing @@ -263,64 +264,64 @@ public void testAddModules(String... addModulesArg) { cmd.executeAndAssertHelloAppImageCreated(); } + public static enum TestTempType { + TEMPDIR_EMPTY, + TEMPDIR_NOT_EMPTY, + TEMPDIR_NOT_EXIST, + } + /** * Test --temp option. Doesn't make much sense for app image as temporary * directory is used only on Windows. Test it in packaging mode. - * @throws IOException */ @Test - @Parameter("true") - @Parameter("false") - public void testTemp(boolean withExistingTempDir) throws IOException { + @Parameter("TEMPDIR_EMPTY") + @Parameter("TEMPDIR_NOT_EMPTY") + @Parameter("TEMPDIR_NOT_EXIST") + public void testTemp(TestTempType type) throws IOException { final Path tempRoot = TKit.createTempDirectory("tmp"); - // This Test has problems on windows where path in the temp dir are too long - // for the wix tools. We can't use a tempDir outside the TKit's WorkDir, so - // we minimize both the tempRoot directory name (above) and the tempDir name - // (below) to the extension part (which is necessary to differenciate between - // the multiple PackageTypes that will be run for one JPackageCommand). - // It might be beter if the whole work dir name was shortened from: - // jtreg_open_test_jdk_tools_jpackage_share_jdk_jpackage_tests_BasicTest_java. - Function getTempDir = cmd -> { - String ext = cmd.outputBundle().getFileName().toString(); - int i = ext.lastIndexOf("."); - if (i > 0 && i < (ext.length() - 1)) { - ext = ext.substring(i+1); - } - return tempRoot.resolve(ext); - }; - Supplier createTest = () -> { - return new PackageTest() - .configureHelloApp() - // Force save of package bundle in test work directory. - .addInitializer(JPackageCommand::setDefaultInputOutput) - .addInitializer(cmd -> { - Path tempDir = getTempDir.apply(cmd); - if (withExistingTempDir) { - Files.createDirectories(tempDir); - } else { - Files.createDirectories(tempDir.getParent()); + var pkgTest = new PackageTest() + .configureHelloApp() + // Force save of package bundle in test work directory. + .addInitializer(JPackageCommand::setDefaultInputOutput) + .addInitializer(cmd -> { + Path tempDir = getTempDirectory(cmd, tempRoot); + switch (type) { + case TEMPDIR_EMPTY -> Files.createDirectories(tempDir); + case TEMPDIR_NOT_EXIST -> Files.createDirectories(tempDir.getParent()); + case TEMPDIR_NOT_EMPTY -> { + Files.createDirectories(tempDir); + TKit.createTextFile(tempDir.resolve("foo.txt"), List.of( + "Hello Duke!")); + } } cmd.addArguments("--temp", tempDir); + } + ); + + if (TestTempType.TEMPDIR_NOT_EMPTY.equals(type)) { + pkgTest.setExpectedExitCode(1).addBundleVerifier(cmd -> { + // Check jpackage didn't use the supplied directory. + Path tempDir = getTempDirectory(cmd, tempRoot); + String[] tempDirContents = tempDir.toFile().list(); + TKit.assertStringListEquals(List.of("foo.txt"), List.of( + tempDirContents), String.format( + "Check the contents of the supplied temporary directory [%s]", + tempDir)); + TKit.assertStringListEquals(List.of("Hello Duke!"), + Files.readAllLines(tempDir.resolve(tempDirContents[0])), + "Check the contents of the file in the supplied temporary directory"); }); - }; + } else { + pkgTest.addBundleVerifier(cmd -> { + // Check jpackage used the supplied directory. + Path tempDir = getTempDirectory(cmd, tempRoot); + TKit.assertDirectoryNotEmpty(tempDir); + }); + } - createTest.get() - .addBundleVerifier(cmd -> { - // Check jpackage actually used the supplied directory. - Path tempDir = getTempDir.apply(cmd); - TKit.assertNotEquals(0, tempDir.toFile().list().length, - String.format( - "Check jpackage wrote some data in the supplied temporary directory [%s]", - tempDir)); - }) - .run(PackageTest.Action.CREATE); - - createTest.get() - // Temporary directory should not be empty, - // jpackage should exit with error. - .setExpectedExitCode(1) - .run(PackageTest.Action.CREATE); + pkgTest.run(PackageTest.Action.CREATE); } @Test diff --git a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java index 84b0e2e93be..c3ec71e3fa7 100644 --- a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java +++ b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/SampleApi.java @@ -22,10 +22,6 @@ */ package sampleapi; -import com.sun.source.util.JavacTask; -import com.sun.tools.javac.api.JavacTaskImpl; -import com.sun.tools.javac.api.JavacTool; -import com.sun.tools.javac.util.Context; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; @@ -34,17 +30,22 @@ import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; -import java.util.Optional; -import static java.util.stream.Collectors.toList; + import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; + +import com.sun.source.util.JavacTask; +import com.sun.tools.javac.api.JavacTaskImpl; +import com.sun.tools.javac.api.JavacTool; +import com.sun.tools.javac.util.Context; + import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; -import sampleapi.generator.ModuleGenerator; +import sampleapi.generator.ModuleGenerator; import sampleapi.generator.PackageGenerator; public class SampleApi { diff --git a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java index d1378560749..0a97c0b7524 100644 --- a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java +++ b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/DocCommentGenerator.java @@ -23,17 +23,23 @@ package sampleapi.generator; -import java.io.File; -import java.io.BufferedInputStream; -import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import java.util.Set; + import javax.lang.model.element.Modifier; import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.*; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCIdent; +import com.sun.tools.javac.tree.JCTree.JCLiteral; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCNewArray; +import com.sun.tools.javac.tree.JCTree.JCNewClass; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; import com.sun.tools.javac.util.List; -import java.util.HashMap; -import java.util.Map; class DocCommentGenerator { diff --git a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java index 2f7a974bb06..12f902cf1b8 100644 --- a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java +++ b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/Documentifier.java @@ -23,22 +23,25 @@ package sampleapi.generator; -import java.util.ArrayList; import java.util.Set; + import javax.lang.model.element.Modifier; -import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.*; -import com.sun.tools.javac.tree.DocCommentTable; -import com.sun.tools.javac.parser.ScannerFactory; +import com.sun.source.tree.Tree.Kind; import com.sun.tools.javac.parser.Scanner; -import com.sun.tools.javac.parser.Tokens.Token; +import com.sun.tools.javac.parser.ScannerFactory; import com.sun.tools.javac.parser.Tokens.Comment; import com.sun.tools.javac.parser.Tokens.Comment.CommentStyle; -import com.sun.source.tree.Tree.Kind; +import com.sun.tools.javac.parser.Tokens.Token; +import com.sun.tools.javac.tree.DocCommentTable; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.util.Context; -import sampleapi.util.*; +import sampleapi.util.PoorDocCommentTable; class Documentifier { diff --git a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java index 76345638fa1..ccc32720f6a 100644 --- a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java +++ b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/ModuleGenerator.java @@ -22,31 +22,26 @@ */ package sampleapi.generator; +import java.io.IOException; +import java.io.OutputStream; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.List; + import com.sun.source.tree.ModuleTree.ModuleKind; import com.sun.tools.javac.code.Symbol; -import com.sun.tools.javac.parser.Scanner; -import com.sun.tools.javac.parser.ScannerFactory; -import com.sun.tools.javac.parser.Tokens; import com.sun.tools.javac.tree.JCTree; import com.sun.tools.javac.tree.JCTree.JCDirective; import com.sun.tools.javac.tree.JCTree.JCExpression; import com.sun.tools.javac.tree.TreeMaker; -import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.util.Names; import com.sun.tools.javac.util.ListBuffer; -import java.io.IOException; -import java.io.OutputStream; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.List; -import java.util.ArrayList; +import com.sun.tools.javac.util.Names; + import org.w3c.dom.Element; import org.w3c.dom.NodeList; import sampleapi.SampleApi; -import sampleapi.util.PoorDocCommentTable; - -import static com.sun.tools.javac.parser.Tokens.Comment.CommentStyle.JAVADOC; /** * diff --git a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java index a0fcd71804f..6576467aef8 100644 --- a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java +++ b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/generator/PackageGenerator.java @@ -26,33 +26,45 @@ import java.io.File; import java.io.FileWriter; import java.io.IOException; +import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; + import javax.xml.parsers.DocumentBuilderFactory; -import org.w3c.dom.Element; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; import com.sun.source.util.JavacTask; -import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.api.JavacTaskImpl; -import com.sun.tools.javac.util.Context; -import com.sun.tools.javac.util.Name; -import com.sun.tools.javac.util.Names; -import com.sun.tools.javac.util.List; -import com.sun.tools.javac.util.ListBuffer; -import com.sun.tools.javac.tree.TreeMaker; -import com.sun.tools.javac.tree.JCTree; -import com.sun.tools.javac.tree.JCTree.*; +import com.sun.tools.javac.api.JavacTool; import com.sun.tools.javac.code.Flags; -import com.sun.tools.javac.code.Type; -import com.sun.tools.javac.code.TypeTag; import com.sun.tools.javac.code.Symbol; import com.sun.tools.javac.code.Symtab; -import java.nio.file.Path; +import com.sun.tools.javac.code.Type; +import com.sun.tools.javac.code.TypeTag; +import com.sun.tools.javac.tree.JCTree; +import com.sun.tools.javac.tree.JCTree.JCAnnotation; +import com.sun.tools.javac.tree.JCTree.JCBlock; +import com.sun.tools.javac.tree.JCTree.JCClassDecl; +import com.sun.tools.javac.tree.JCTree.JCCompilationUnit; +import com.sun.tools.javac.tree.JCTree.JCExpression; +import com.sun.tools.javac.tree.JCTree.JCFieldAccess; +import com.sun.tools.javac.tree.JCTree.JCMethodDecl; +import com.sun.tools.javac.tree.JCTree.JCPackageDecl; +import com.sun.tools.javac.tree.JCTree.JCStatement; +import com.sun.tools.javac.tree.JCTree.JCTypeParameter; +import com.sun.tools.javac.tree.JCTree.JCVariableDecl; +import com.sun.tools.javac.tree.TreeMaker; +import com.sun.tools.javac.util.Context; +import com.sun.tools.javac.util.List; +import com.sun.tools.javac.util.ListBuffer; +import com.sun.tools.javac.util.Name; +import com.sun.tools.javac.util.Names; + +import org.w3c.dom.Element; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; -import sampleapi.util.*; +import sampleapi.util.SimpleMultiplier; public class PackageGenerator { diff --git a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java index 545e671c640..711644c0614 100644 --- a/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java +++ b/test/langtools/jdk/javadoc/tool/sampleapi/lib/sampleapi/util/SimpleMultiplier.java @@ -23,8 +23,8 @@ package sampleapi.util; -import java.util.StringTokenizer; import java.util.ArrayList; +import java.util.StringTokenizer; /* * The class implements unknown number of nested loops. The number of modifiers diff --git a/test/langtools/tools/javac/newlines/NewLineTest.java b/test/langtools/tools/javac/newlines/NewLineTest.java index b1567d363b0..35c60e59653 100644 --- a/test/langtools/tools/javac/newlines/NewLineTest.java +++ b/test/langtools/tools/javac/newlines/NewLineTest.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 @@ -58,8 +58,9 @@ public static void main(String args[]) throws Exception { .options("-J-Dline.separator='@'") .run(Task.Expect.FAIL); - List lines = Files.readAllLines(javacOutput.toPath(), - Charset.defaultCharset()); + String encoding = System.getProperty("native.encoding"); + Charset cs = (encoding != null) ? Charset.forName(encoding) : Charset.defaultCharset(); + List lines = Files.readAllLines(javacOutput.toPath(), cs); if (lines.size() != 1) { throw new AssertionError("The compiler output should have one line only"); } diff --git a/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java b/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java index 85a6f6af9d8..d4540107022 100644 --- a/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java +++ b/test/langtools/tools/javac/processing/model/type/BasicAnnoTests.java @@ -40,6 +40,8 @@ import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.ArrayList; @@ -405,6 +407,12 @@ R scan(Iterable iter, P p) { int value(); } + @Target(ElementType.TYPE_USE) + @Retention(RetentionPolicy.RUNTIME) + public @interface TD { + int value(); + } + // Test cases // TODO: add more cases for arrays @@ -527,6 +535,10 @@ public class Inner6 {} @Test(posn=1, annoType=TA.class, expect="23") public Set<@TA(23) ? super Object> f9; + @Test(posn=0, annoType=TA.class, expect="1") + @Test(posn=0, annoType=TD.class, expect="2") + public @TA(1) @TD(2) int f10; + // Test type use annotations on uses of type variables @Test(posn=5, annoType = TA.class, expect = "25") @Test(posn=5, annoType = TB.class, expect = "26") diff --git a/test/lib/jdk/test/lib/Platform.java b/test/lib/jdk/test/lib/Platform.java index bb1bb64bab0..c8f7dca8c1d 100644 --- a/test/lib/jdk/test/lib/Platform.java +++ b/test/lib/jdk/test/lib/Platform.java @@ -41,6 +41,7 @@ import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static java.util.Locale.ROOT; public class Platform { public static final String vmName = privilegedGetProperty("java.vm.name"); @@ -144,7 +145,7 @@ public static boolean isWindows() { } private static boolean isOs(String osname) { - return osName.toLowerCase().startsWith(osname.toLowerCase()); + return osName.toLowerCase(ROOT).startsWith(osname.toLowerCase(ROOT)); } public static String getOsName() { @@ -185,15 +186,15 @@ public static int getOsVersionMinor() { } public static boolean isDebugBuild() { - return (jdkDebug.toLowerCase().contains("debug")); + return (jdkDebug.toLowerCase(ROOT).contains("debug")); } public static boolean isSlowDebugBuild() { - return (jdkDebug.toLowerCase().equals("slowdebug")); + return (jdkDebug.toLowerCase(ROOT).equals("slowdebug")); } public static boolean isFastDebugBuild() { - return (jdkDebug.toLowerCase().equals("fastdebug")); + return (jdkDebug.toLowerCase(ROOT).equals("fastdebug")); } public static String getVMVersion() { @@ -356,8 +357,8 @@ private static boolean isArch(String archnameRE) { } public static boolean isOracleLinux7() { - if (System.getProperty("os.name").toLowerCase().contains("linux") && - System.getProperty("os.version").toLowerCase().contains("el")) { + if (System.getProperty("os.name").toLowerCase(ROOT).contains("linux") && + System.getProperty("os.version").toLowerCase(ROOT).contains("el")) { Pattern p = Pattern.compile("el(\\d+)"); Matcher m = p.matcher(System.getProperty("os.version")); if (m.find()) { diff --git a/test/lib/jdk/test/lib/SecurityTools.java b/test/lib/jdk/test/lib/SecurityTools.java index ee786eb365c..bc198a712b8 100644 --- a/test/lib/jdk/test/lib/SecurityTools.java +++ b/test/lib/jdk/test/lib/SecurityTools.java @@ -40,9 +40,8 @@ /** * Run security tools (including jarsigner and keytool) in a new process. * The en_US locale is always used so a test can always match output to - * English text. {@code /dev/urandom} is used as entropy source so tool will - * not block because of entropy scarcity. {@code -Jvm-options} is supported - * as an argument. + * English text. An argument can be a normal string, + * {@code -Jvm-options}, {@code $sysProp} or {@code -J$sysProp}. */ public class SecurityTools { @@ -58,15 +57,19 @@ public static ProcessBuilder getProcessBuilder(String tool, List args) { JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK(tool) .addVMArg("-Duser.language=en") .addVMArg("-Duser.country=US"); - if (!Platform.isWindows()) { - launcher.addVMArg("-Djava.security.egd=file:/dev/./urandom"); - } for (String arg : args) { if (arg.startsWith("-J")) { - launcher.addVMArg(arg.substring(2)); + String jarg = arg.substring(2); + if (jarg.length() > 1 && jarg.charAt(0) == '$') { + launcher.addVMArg(System.getProperty(jarg.substring(1))); + } else { + launcher.addVMArg(jarg); + } } else if (Platform.isWindows() && arg.isEmpty()) { // JDK-6518827: special handling for empty argument on Windows launcher.addToolArg("\"\""); + } else if (arg.length() > 1 && arg.charAt(0) == '$') { + launcher.addToolArg(System.getProperty(arg.substring(1))); } else { launcher.addToolArg(arg); } diff --git a/test/lib/jdk/test/lib/util/ForceGC.java b/test/lib/jdk/test/lib/util/ForceGC.java index 19bbef1f7e4..e3587b9a2be 100644 --- a/test/lib/jdk/test/lib/util/ForceGC.java +++ b/test/lib/jdk/test/lib/util/ForceGC.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2020, 2023, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2020, 2024, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -78,29 +78,30 @@ public static boolean waitFor(BooleanSupplier booleanSupplier, long timeout) { ReferenceQueue queue = new ReferenceQueue<>(); Object obj = new Object(); PhantomReference ref = new PhantomReference<>(obj, queue); - obj = null; - Reference.reachabilityFence(obj); - Reference.reachabilityFence(ref); + try { + obj = null; - int retries = (int)(timeout / 200); - for (; retries >= 0; retries--) { - if (booleanSupplier.getAsBoolean()) { - return true; - } + int retries = (int) (timeout / 200); + for (; retries >= 0; retries--) { + if (booleanSupplier.getAsBoolean()) { + return true; + } - System.gc(); + System.gc(); - try { - // The remove() will always block for the specified milliseconds - // if the reference has already been removed from the queue. - // But it is fine. For most cases, the 1st GC is sufficient - // to trigger and complete the cleanup. - queue.remove(200L); - } catch (InterruptedException ie) { - // ignore, the loop will try again + try { + // The remove() will always block for the specified milliseconds + // if the reference has already been removed from the queue. + // But it is fine. For most cases, the 1st GC is sufficient + // to trigger and complete the cleanup. + queue.remove(200L); + } catch (InterruptedException ie) { + // ignore, the loop will try again + } } + } finally { + Reference.reachabilityFence(ref); } - return booleanSupplier.getAsBoolean(); } } diff --git a/test/micro/org/openjdk/bench/java/security/Signatures.java b/test/micro/org/openjdk/bench/java/security/Signatures.java new file mode 100644 index 00000000000..7a14cb24b88 --- /dev/null +++ b/test/micro/org/openjdk/bench/java/security/Signatures.java @@ -0,0 +1,197 @@ +/* + * Copyright (C) 2022 THL A29 Limited, a Tencent company. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package org.openjdk.bench.java.security; + +import org.openjdk.jmh.annotations.*; + +import java.security.*; +import java.security.spec.*; +import java.util.Random; +import java.util.concurrent.TimeUnit; + +@BenchmarkMode(Mode.Throughput) +@OutputTimeUnit(TimeUnit.SECONDS) +@State(Scope.Thread) +@Warmup(iterations = 5, time = 1) +@Measurement(iterations = 5, time = 1) +@Fork(jvmArgsAppend = {"-Xms1024m", "-Xmx1024m", "-Xmn768m", "-XX:+UseParallelGC"}, value = 3) +public class Signatures { + private static Signature signer; + + @Param({"64", "512", "2048", "16384"}) + private static int messageLength; + + @Param({"secp256r1", "secp384r1", "secp521r1"}) + private String algorithm; + + private static byte[] message; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + String signName = switch (algorithm) { + case "secp256r1" -> "SHA256withECDSA"; + case "secp384r1" -> "SHA384withECDSA"; + case "secp521r1" -> "SHA512withECDSA"; + default -> throw new RuntimeException(); + }; + + AlgorithmParameters params = + AlgorithmParameters.getInstance("EC", "SunEC"); + params.init(new ECGenParameterSpec(algorithm)); + ECGenParameterSpec ecParams = + params.getParameterSpec(ECGenParameterSpec.class); + + KeyPairGenerator kpg = + KeyPairGenerator.getInstance("EC", "SunEC"); + kpg.initialize(ecParams); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance(signName, "SunEC"); + signer.initSign(kp.getPrivate()); + } + + @Benchmark + public byte[] sign() throws SignatureException { + signer.update(message); + return signer.sign(); + } + + public static class EdDSA extends Signatures { + @Param({"Ed25519", "Ed448"}) + private String algorithm; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + KeyPairGenerator kpg = + KeyPairGenerator.getInstance(algorithm, "SunEC"); + NamedParameterSpec spec = new NamedParameterSpec(algorithm); + kpg.initialize(spec); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance(algorithm, "SunEC"); + signer.initSign(kp.getPrivate()); + } + } + + public static class DSA extends Signatures { + @Param({"SHA256withDSA", "SHA384withDSA", "SHA512withDSA"}) + private String algorithm; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + int keyLength = switch (algorithm) { + case "SHA256withDSA" -> 2048; + case "SHA384withDSA" -> 3072; + case "SHA512withDSA" -> 3072; + default -> throw new RuntimeException(); + }; + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA"); + kpg.initialize(keyLength); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance(algorithm); + signer.initSign(kp.getPrivate()); + } + } + + public static class RSA extends Signatures { + @Param({"SHA256withRSA", "SHA384withRSA", "SHA512withRSA"}) + private String algorithm; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + int keyLength = switch (algorithm) { + case "SHA256withRSA" -> 2048; + case "SHA384withRSA" -> 3072; + case "SHA512withRSA" -> 4096; + default -> throw new RuntimeException(); + }; + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); + kpg.initialize(keyLength); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance(algorithm); + signer.initSign(kp.getPrivate()); + } + } + + public static class RSASSAPSS extends Signatures { + @Param({"SHA256", "SHA384", "SHA512"}) + private String algorithm; + + @Setup + public void setup() throws Exception { + message = new byte[messageLength]; + (new Random(System.nanoTime())).nextBytes(message); + + int keyLength = switch (algorithm) { + case "SHA256" -> 2048; + case "SHA384" -> 3072; + case "SHA512" -> 4096; + default -> throw new RuntimeException(); + }; + + PSSParameterSpec spec = switch (algorithm) { + case "SHA256" -> + new PSSParameterSpec( + "SHA-256", "MGF1", + MGF1ParameterSpec.SHA256, + 32, PSSParameterSpec.TRAILER_FIELD_BC); + case "SHA384" -> + new PSSParameterSpec( + "SHA-384", "MGF1", + MGF1ParameterSpec.SHA384, + 48, PSSParameterSpec.TRAILER_FIELD_BC); + case "SHA512" -> + new PSSParameterSpec( + "SHA-512", "MGF1", + MGF1ParameterSpec.SHA512, + 64, PSSParameterSpec.TRAILER_FIELD_BC); + default -> throw new RuntimeException(); + }; + + KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSASSA-PSS"); + kpg.initialize(keyLength); + KeyPair kp = kpg.generateKeyPair(); + + signer = Signature.getInstance("RSASSA-PSS"); + signer.setParameter(spec); + signer.initSign(kp.getPrivate()); + } + } +} +