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
- * 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
-
-
-
-
* 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
* Any lines starting with {@code '#'} are comment lines and ignored.
*/
-public class FormatIteratorTest extends IntlTest {
+public class FormatIteratorTest {
+
+ /*
+ * Change JVM default Locale and TimeZone.
+ * The current tests are only appropriate for US. If tests are
+ * added for other locales are added, then a property should be
+ * added to each file (test) to be able to specify the locale.
+ */
+ @BeforeAll
+ static void initAll() {
+ Locale.setDefault(Locale.US);
+ TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
+ }
+
private Format format;
private Object value;
private String text;
- public static final Object ARG0_FIELD_ID = MessageFormat.
- Field.ARGUMENT;
- public static final Object ARG1_FIELD_ID = MessageFormat.
- Field.ARGUMENT;
- public static final Object ARG2_FIELD_ID = MessageFormat.
- Field.ARGUMENT;
- public static final Object ARG3_FIELD_ID = MessageFormat.
- Field.ARGUMENT;
-
- public static void main(String[] args) throws Exception {
- Locale reservedLocale = Locale.getDefault();
- TimeZone reservedTimeZone = TimeZone.getDefault();
- try {
- // The current tests are only appropriate for US. If tests are
- // added for other locales are added, then a property should be
- // added to each file (test) to be able to specify the locale.
- Locale.setDefault(Locale.US);
- TimeZone.setDefault(TimeZone.getTimeZone("America/Los_Angeles"));
- new FormatIteratorTest().run(args);
- } finally {
- // restore the reserved locale and time zone
- Locale.setDefault(reservedLocale);
- TimeZone.setDefault(reservedTimeZone);
- }
- }
-
public FormatIteratorTest() {
}
+ @Test
public void testDecimalFormat() {
_test(new File(System.getProperty("test.src", "."),
"decimalFormat.props"));
}
+ @Test
public void testMessageFormat() {
_test(new File(System.getProperty("test.src", "."),
"messageFormat.props"));
}
+ @Test
public void testDateFormat() {
_test(new File(System.getProperty("test.src", "."),
"dateFormat.props"));
@@ -146,23 +140,23 @@ public void testDateFormat() {
@SuppressWarnings("unchecked")
private void _test(File file) {
try {
- logln("testing: " + file);
+ System.out.println("testing: " + file);
PParser parser = new PParser();
Map contents = parser.parse(new BufferedReader(
new FileReader(file)));
List