# HG changeset patch # User duke # Date 1499286652 -7200 # Node ID f4e854a77aa38749bd90f722b06974a56e7233d5 # Parent 9bb854a11a6521c8cb2f3d58d2c4a0ce1a2f45bb# Parent 183ae2332dd9e8f831e5490444dde5f1e0f7a14f Merge diff -r 183ae2332dd9 -r f4e854a77aa3 .hgtags-top-repo --- a/.hgtags-top-repo Wed Jul 05 22:29:12 2017 +0200 +++ b/.hgtags-top-repo Wed Jul 05 22:30:52 2017 +0200 @@ -388,3 +388,4 @@ 1fc62b1c629fb80fdaa639d3b59452a184f0d705 jdk-9+143 8d337fd6333e28c48aa87880144b840aad82baaf jdk-9+144 ff98aa9ec9fae991e426ce5926fc9036d25f5562 jdk-9+145 +a22e2671d88f6b22a4aa82e3966986542ed2a381 jdk-9+146 diff -r 183ae2332dd9 -r f4e854a77aa3 common/autoconf/basics.m4 --- a/common/autoconf/basics.m4 Wed Jul 05 22:29:12 2017 +0200 +++ b/common/autoconf/basics.m4 Wed Jul 05 22:30:52 2017 +0200 @@ -1048,7 +1048,9 @@ # These tools might not be installed by default, # need hint on how to install them. BASIC_REQUIRE_PROGS(UNZIP, unzip) - BASIC_REQUIRE_PROGS(ZIP, zip) + # Since zip uses "ZIP" as a environment variable for passing options, we need + # to name our variable differently, hence ZIPEXE. + BASIC_REQUIRE_PROGS(ZIPEXE, zip) # Non-required basic tools diff -r 183ae2332dd9 -r f4e854a77aa3 common/autoconf/flags.m4 --- a/common/autoconf/flags.m4 Wed Jul 05 22:29:12 2017 +0200 +++ b/common/autoconf/flags.m4 Wed Jul 05 22:30:52 2017 +0200 @@ -311,7 +311,11 @@ SET_SHARED_LIBRARY_MAPFILE='-Wl,-version-script=[$]1' fi elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then - PICFLAG="-KPIC" + if test "x$OPENJDK_TARGET_CPU" = xsparcv9; then + PICFLAG="-xcode=pic32" + else + PICFLAG="-KPIC" + fi C_FLAG_REORDER='-xF' CXX_FLAG_REORDER='-xF' SHARED_LIBRARY_FLAGS="-G" @@ -838,7 +842,6 @@ fastdebug | slowdebug ) $2CFLAGS_JDK="[$]$2CFLAGS_JDK $CFLAGS_DEBUG_SYMBOLS $CFLAGS_DEBUG_OPTIONS" $2CXXFLAGS_JDK="[$]$2CXXFLAGS_JDK $CXXFLAGS_DEBUG_SYMBOLS $CXXFLAGS_DEBUG_OPTIONS" - JAVAC_FLAGS="$JAVAC_FLAGS -g" ;; release ) ;; @@ -894,12 +897,12 @@ # Set some additional per-OS defines. if test "x$OPENJDK_$1_OS" = xlinux; then $2JVM_CFLAGS="[$]$2JVM_CFLAGS -DLINUX" - $2JVM_CFLAGS="[$]$2JVM_CFLAGS -pipe -fPIC -fno-rtti -fno-exceptions \ + $2JVM_CFLAGS="[$]$2JVM_CFLAGS -pipe $PICFLAG -fno-rtti -fno-exceptions \ -fvisibility=hidden -fno-strict-aliasing -fno-omit-frame-pointer" elif test "x$OPENJDK_$1_OS" = xsolaris; then $2JVM_CFLAGS="[$]$2JVM_CFLAGS -DSOLARIS" $2JVM_CFLAGS="[$]$2JVM_CFLAGS -template=no%extdef -features=no%split_init \ - -D_Crun_inline_placement -library=%none -KPIC -mt -features=no%except" + -D_Crun_inline_placement -library=%none $PICFLAG -mt -features=no%except" elif test "x$OPENJDK_$1_OS" = xmacosx; then $2COMMON_CCXXFLAGS_JDK="[$]$2COMMON_CCXXFLAGS_JDK -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT" $2JVM_CFLAGS="[$]$2JVM_CFLAGS -D_ALLBSD_SOURCE" @@ -1310,7 +1313,7 @@ AC_MSG_CHECKING([if both compilers support "ARG_ARGUMENT"]) supports=no if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi - + AC_MSG_RESULT([$supports]) if test "x$supports" = "xyes" ; then : diff -r 183ae2332dd9 -r f4e854a77aa3 common/autoconf/generated-configure.sh --- a/common/autoconf/generated-configure.sh Wed Jul 05 22:29:12 2017 +0200 +++ b/common/autoconf/generated-configure.sh Wed Jul 05 22:30:52 2017 +0200 @@ -945,7 +945,7 @@ READELF OTOOL LDD -ZIP +ZIPEXE UNZIP TAR_SUPPORTS_TRANSFORM TAR_INCLUDE_PARAM @@ -1292,7 +1292,7 @@ NICE MAKE UNZIP -ZIP +ZIPEXE LDD OTOOL READELF @@ -2236,7 +2236,7 @@ NICE Override default value for NICE MAKE Override default value for MAKE UNZIP Override default value for UNZIP - ZIP Override default value for ZIP + ZIPEXE Override default value for ZIPEXE LDD Override default value for LDD OTOOL Override default value for OTOOL READELF Override default value for READELF @@ -5093,7 +5093,7 @@ #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1479120453 +DATE_WHEN_GENERATED=1479997904 ############################################################################### # @@ -21373,13 +21373,15 @@ fi - - - - # Publish this variable in the help. - - - if [ -z "${ZIP+x}" ]; then + # Since zip uses "ZIP" as a environment variable for passing options, we need + # to name our variable differently, hence ZIPEXE. + + + + # Publish this variable in the help. + + + if [ -z "${ZIPEXE+x}" ]; then # The variable is not set by user, try to locate tool using the code snippet for ac_prog in zip do @@ -21387,56 +21389,56 @@ set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_path_ZIP+:} false; then : - $as_echo_n "(cached) " >&6 -else - case $ZIP in - [\\/]* | ?:[\\/]*) - ac_cv_path_ZIP="$ZIP" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_path_ZIP="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ZIP=$ac_cv_path_ZIP -if test -n "$ZIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIP" >&5 -$as_echo "$ZIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$ZIP" && break -done - - else - # The variable is set, but is it from the command line or the environment? - - # Try to remove the string !ZIP! from our list. - try_remove_var=${CONFIGURE_OVERRIDDEN_VARIABLES//!ZIP!/} - if test "x$try_remove_var" = "x$CONFIGURE_OVERRIDDEN_VARIABLES"; then - # If it failed, the variable was not from the command line. Ignore it, - # but warn the user (except for BASH, which is always set by the calling BASH). - if test "xZIP" != xBASH; then - { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Ignoring value of ZIP from the environment. Use command line variables instead." >&5 -$as_echo "$as_me: WARNING: Ignoring value of ZIP from the environment. Use command line variables instead." >&2;} +if ${ac_cv_path_ZIPEXE+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ZIPEXE in + [\\/]* | ?:[\\/]*) + ac_cv_path_ZIPEXE="$ZIPEXE" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ZIPEXE="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ZIPEXE=$ac_cv_path_ZIPEXE +if test -n "$ZIPEXE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIPEXE" >&5 +$as_echo "$ZIPEXE" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ZIPEXE" && break +done + + else + # The variable is set, but is it from the command line or the environment? + + # Try to remove the string !ZIPEXE! from our list. + try_remove_var=${CONFIGURE_OVERRIDDEN_VARIABLES//!ZIPEXE!/} + if test "x$try_remove_var" = "x$CONFIGURE_OVERRIDDEN_VARIABLES"; then + # If it failed, the variable was not from the command line. Ignore it, + # but warn the user (except for BASH, which is always set by the calling BASH). + if test "xZIPEXE" != xBASH; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: Ignoring value of ZIPEXE from the environment. Use command line variables instead." >&5 +$as_echo "$as_me: WARNING: Ignoring value of ZIPEXE from the environment. Use command line variables instead." >&2;} fi # Try to locate tool using the code snippet for ac_prog in zip @@ -21445,135 +21447,135 @@ set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_path_ZIP+:} false; then : - $as_echo_n "(cached) " >&6 -else - case $ZIP in - [\\/]* | ?:[\\/]*) - ac_cv_path_ZIP="$ZIP" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_path_ZIP="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ZIP=$ac_cv_path_ZIP -if test -n "$ZIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIP" >&5 -$as_echo "$ZIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - test -n "$ZIP" && break -done - - else - # If it succeeded, then it was overridden by the user. We will use it - # for the tool. - - # First remove it from the list of overridden variables, so we can test - # for unknown variables in the end. - CONFIGURE_OVERRIDDEN_VARIABLES="$try_remove_var" - - # Check if we try to supply an empty value - if test "x$ZIP" = x; then - { $as_echo "$as_me:${as_lineno-$LINENO}: Setting user supplied tool ZIP= (no value)" >&5 -$as_echo "$as_me: Setting user supplied tool ZIP= (no value)" >&6;} - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ZIP" >&5 -$as_echo_n "checking for ZIP... " >&6; } - { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5 -$as_echo "disabled" >&6; } - else - # Check if the provided tool contains a complete path. - tool_specified="$ZIP" - tool_basename="${tool_specified##*/}" - if test "x$tool_basename" = "x$tool_specified"; then - # A command without a complete path is provided, search $PATH. - { $as_echo "$as_me:${as_lineno-$LINENO}: Will search for user supplied tool ZIP=$tool_basename" >&5 -$as_echo "$as_me: Will search for user supplied tool ZIP=$tool_basename" >&6;} - # Extract the first word of "$tool_basename", so it can be a program name with args. -set dummy $tool_basename; ac_word=$2 -{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 -$as_echo_n "checking for $ac_word... " >&6; } -if ${ac_cv_path_ZIP+:} false; then : - $as_echo_n "(cached) " >&6 -else - case $ZIP in - [\\/]* | ?:[\\/]*) - ac_cv_path_ZIP="$ZIP" # Let the user override the test with a path. - ;; - *) - as_save_IFS=$IFS; IFS=$PATH_SEPARATOR -for as_dir in $PATH -do - IFS=$as_save_IFS - test -z "$as_dir" && as_dir=. - for ac_exec_ext in '' $ac_executable_extensions; do - if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then - ac_cv_path_ZIP="$as_dir/$ac_word$ac_exec_ext" - $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 - break 2 - fi -done - done -IFS=$as_save_IFS - - ;; -esac -fi -ZIP=$ac_cv_path_ZIP -if test -n "$ZIP"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIP" >&5 -$as_echo "$ZIP" >&6; } -else - { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 -$as_echo "no" >&6; } -fi - - - if test "x$ZIP" = x; then - as_fn_error $? "User supplied tool $tool_basename could not be found" "$LINENO" 5 - fi - else - # Otherwise we believe it is a complete path. Use it as it is. - { $as_echo "$as_me:${as_lineno-$LINENO}: Will use user supplied tool ZIP=$tool_specified" >&5 -$as_echo "$as_me: Will use user supplied tool ZIP=$tool_specified" >&6;} - { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ZIP" >&5 -$as_echo_n "checking for ZIP... " >&6; } - if test ! -x "$tool_specified"; then - { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 -$as_echo "not found" >&6; } - as_fn_error $? "User supplied tool ZIP=$tool_specified does not exist or is not executable" "$LINENO" 5 - fi - { $as_echo "$as_me:${as_lineno-$LINENO}: result: $tool_specified" >&5 -$as_echo "$tool_specified" >&6; } - fi - fi - fi - - fi - - - - if test "x$ZIP" = x; then - as_fn_error $? "Could not find required tool for ZIP" "$LINENO" 5 +if ${ac_cv_path_ZIPEXE+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ZIPEXE in + [\\/]* | ?:[\\/]*) + ac_cv_path_ZIPEXE="$ZIPEXE" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ZIPEXE="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ZIPEXE=$ac_cv_path_ZIPEXE +if test -n "$ZIPEXE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIPEXE" >&5 +$as_echo "$ZIPEXE" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ZIPEXE" && break +done + + else + # If it succeeded, then it was overridden by the user. We will use it + # for the tool. + + # First remove it from the list of overridden variables, so we can test + # for unknown variables in the end. + CONFIGURE_OVERRIDDEN_VARIABLES="$try_remove_var" + + # Check if we try to supply an empty value + if test "x$ZIPEXE" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: Setting user supplied tool ZIPEXE= (no value)" >&5 +$as_echo "$as_me: Setting user supplied tool ZIPEXE= (no value)" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ZIPEXE" >&5 +$as_echo_n "checking for ZIPEXE... " >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: result: disabled" >&5 +$as_echo "disabled" >&6; } + else + # Check if the provided tool contains a complete path. + tool_specified="$ZIPEXE" + tool_basename="${tool_specified##*/}" + if test "x$tool_basename" = "x$tool_specified"; then + # A command without a complete path is provided, search $PATH. + { $as_echo "$as_me:${as_lineno-$LINENO}: Will search for user supplied tool ZIPEXE=$tool_basename" >&5 +$as_echo "$as_me: Will search for user supplied tool ZIPEXE=$tool_basename" >&6;} + # Extract the first word of "$tool_basename", so it can be a program name with args. +set dummy $tool_basename; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_path_ZIPEXE+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $ZIPEXE in + [\\/]* | ?:[\\/]*) + ac_cv_path_ZIPEXE="$ZIPEXE" # Let the user override the test with a path. + ;; + *) + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_path_ZIPEXE="$as_dir/$ac_word$ac_exec_ext" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + + ;; +esac +fi +ZIPEXE=$ac_cv_path_ZIPEXE +if test -n "$ZIPEXE"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ZIPEXE" >&5 +$as_echo "$ZIPEXE" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + if test "x$ZIPEXE" = x; then + as_fn_error $? "User supplied tool $tool_basename could not be found" "$LINENO" 5 + fi + else + # Otherwise we believe it is a complete path. Use it as it is. + { $as_echo "$as_me:${as_lineno-$LINENO}: Will use user supplied tool ZIPEXE=$tool_specified" >&5 +$as_echo "$as_me: Will use user supplied tool ZIPEXE=$tool_specified" >&6;} + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ZIPEXE" >&5 +$as_echo_n "checking for ZIPEXE... " >&6; } + if test ! -x "$tool_specified"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: not found" >&5 +$as_echo "not found" >&6; } + as_fn_error $? "User supplied tool ZIPEXE=$tool_specified does not exist or is not executable" "$LINENO" 5 + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $tool_specified" >&5 +$as_echo "$tool_specified" >&6; } + fi + fi + fi + + fi + + + + if test "x$ZIPEXE" = x; then + as_fn_error $? "Could not find required tool for ZIPEXE" "$LINENO" 5 fi @@ -49101,7 +49103,11 @@ SET_SHARED_LIBRARY_MAPFILE='-Wl,-version-script=$1' fi elif test "x$TOOLCHAIN_TYPE" = xsolstudio; then - PICFLAG="-KPIC" + if test "x$OPENJDK_TARGET_CPU" = xsparcv9; then + PICFLAG="-xcode=pic32" + else + PICFLAG="-KPIC" + fi C_FLAG_REORDER='-xF' CXX_FLAG_REORDER='-xF' SHARED_LIBRARY_FLAGS="-G" @@ -50020,7 +50026,6 @@ fastdebug | slowdebug ) CFLAGS_JDK="$CFLAGS_JDK $CFLAGS_DEBUG_SYMBOLS $CFLAGS_DEBUG_OPTIONS" CXXFLAGS_JDK="$CXXFLAGS_JDK $CXXFLAGS_DEBUG_SYMBOLS $CXXFLAGS_DEBUG_OPTIONS" - JAVAC_FLAGS="$JAVAC_FLAGS -g" ;; release ) ;; @@ -50076,12 +50081,12 @@ # Set some additional per-OS defines. if test "x$OPENJDK_TARGET_OS" = xlinux; then JVM_CFLAGS="$JVM_CFLAGS -DLINUX" - JVM_CFLAGS="$JVM_CFLAGS -pipe -fPIC -fno-rtti -fno-exceptions \ + JVM_CFLAGS="$JVM_CFLAGS -pipe $PICFLAG -fno-rtti -fno-exceptions \ -fvisibility=hidden -fno-strict-aliasing -fno-omit-frame-pointer" elif test "x$OPENJDK_TARGET_OS" = xsolaris; then JVM_CFLAGS="$JVM_CFLAGS -DSOLARIS" JVM_CFLAGS="$JVM_CFLAGS -template=no%extdef -features=no%split_init \ - -D_Crun_inline_placement -library=%none -KPIC -mt -features=no%except" + -D_Crun_inline_placement -library=%none $PICFLAG -mt -features=no%except" elif test "x$OPENJDK_TARGET_OS" = xmacosx; then COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT" JVM_CFLAGS="$JVM_CFLAGS -D_ALLBSD_SOURCE" @@ -50844,7 +50849,6 @@ fastdebug | slowdebug ) OPENJDK_BUILD_CFLAGS_JDK="$OPENJDK_BUILD_CFLAGS_JDK $CFLAGS_DEBUG_SYMBOLS $CFLAGS_DEBUG_OPTIONS" OPENJDK_BUILD_CXXFLAGS_JDK="$OPENJDK_BUILD_CXXFLAGS_JDK $CXXFLAGS_DEBUG_SYMBOLS $CXXFLAGS_DEBUG_OPTIONS" - JAVAC_FLAGS="$JAVAC_FLAGS -g" ;; release ) ;; @@ -50900,12 +50904,12 @@ # Set some additional per-OS defines. if test "x$OPENJDK_BUILD_OS" = xlinux; then OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -DLINUX" - OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -pipe -fPIC -fno-rtti -fno-exceptions \ + OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -pipe $PICFLAG -fno-rtti -fno-exceptions \ -fvisibility=hidden -fno-strict-aliasing -fno-omit-frame-pointer" elif test "x$OPENJDK_BUILD_OS" = xsolaris; then OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -DSOLARIS" OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -template=no%extdef -features=no%split_init \ - -D_Crun_inline_placement -library=%none -KPIC -mt -features=no%except" + -D_Crun_inline_placement -library=%none $PICFLAG -mt -features=no%except" elif test "x$OPENJDK_BUILD_OS" = xmacosx; then OPENJDK_BUILD_COMMON_CCXXFLAGS_JDK="$OPENJDK_BUILD_COMMON_CCXXFLAGS_JDK -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT" OPENJDK_BUILD_JVM_CFLAGS="$OPENJDK_BUILD_JVM_CFLAGS -D_ALLBSD_SOURCE" diff -r 183ae2332dd9 -r f4e854a77aa3 common/autoconf/spec.gmk.in --- a/common/autoconf/spec.gmk.in Wed Jul 05 22:29:12 2017 +0200 +++ b/common/autoconf/spec.gmk.in Wed Jul 05 22:30:52 2017 +0200 @@ -657,8 +657,7 @@ UNIQ:=@UNIQ@ WC:=@WC@ XARGS:=@XARGS@ -ZIPEXE:=@ZIP@ -ZIP:=@ZIP@ +ZIPEXE:=@ZIPEXE@ UNZIP:=@UNZIP@ MT:=@FIXPATH@ @MT@ RC:=@FIXPATH@ @RC@ diff -r 183ae2332dd9 -r f4e854a77aa3 corba/.hgtags --- a/corba/.hgtags Wed Jul 05 22:29:12 2017 +0200 +++ b/corba/.hgtags Wed Jul 05 22:30:52 2017 +0200 @@ -388,3 +388,4 @@ 6211236ef15ec796806357608b1dd1b70c258ece jdk-9+143 d4f1dae174098e799c48948e866054c52e11a186 jdk-9+144 a44b156ae7f06bf41b9bece30df7775e482395dd jdk-9+145 +ecd74b41ab65bf228837b5bdf99690638d55425c jdk-9+146 diff -r 183ae2332dd9 -r f4e854a77aa3 hotspot/.hgtags --- a/hotspot/.hgtags Wed Jul 05 22:29:12 2017 +0200 +++ b/hotspot/.hgtags Wed Jul 05 22:30:52 2017 +0200 @@ -548,3 +548,4 @@ d87d5d430c42342f0320ca7f5cbe0cbd1f9d62ba jdk-9+143 6187b582d02aee38341dc8ce4011906e9b364e9f jdk-9+144 61e7ea56312351657e69198c503a6f7bf865af83 jdk-9+145 +a82cb5350cad96a0b4de496afebe3ded89f27efa jdk-9+146 diff -r 183ae2332dd9 -r f4e854a77aa3 hotspot/make/gensrc/GensrcJvmti.gmk --- a/hotspot/make/gensrc/GensrcJvmti.gmk Wed Jul 05 22:29:12 2017 +0200 +++ b/hotspot/make/gensrc/GensrcJvmti.gmk Wed Jul 05 22:30:52 2017 +0200 @@ -130,8 +130,6 @@ TARGETS += $(JVMTI_OUTPUTDIR)/jvmtiEnvRecommended.cpp ################################################################################ -# Disable copy of jvmti.h from hotspot until this has been cleared up. The file -# is currently being copied from the jdk repository. See JDK-8167078. # Copy jvmti.h to include dir # The file is the same regardless of jvm variant. Only let one do the copy. diff -r 183ae2332dd9 -r f4e854a77aa3 hotspot/make/lib/CompileLibjsig.gmk --- a/hotspot/make/lib/CompileLibjsig.gmk Wed Jul 05 22:29:12 2017 +0200 +++ b/hotspot/make/lib/CompileLibjsig.gmk Wed Jul 05 22:30:52 2017 +0200 @@ -129,7 +129,7 @@ ifeq ($(ZIP_EXTERNAL_DEBUG_SYMBOLS), true) $(LIB_OUTPUTDIR)/$1/$(LIBRARY_PREFIX)jsig.diz: \ $(LIB_OUTPUTDIR)/$1/$(LIBRARY_PREFIX)jsig$(DEBUG_INFO_SUFFIX) - $(CD) $$(@D) && $(ZIP) -q -y $$@ $$(basename $$(@F))$(DEBUG_INFO_SUFFIX) + $(CD) $$(@D) && $(ZIPEXE) -q -y $$@ $$(basename $$(@F))$(DEBUG_INFO_SUFFIX) TARGETS += $(LIB_OUTPUTDIR)/$1/$(LIBRARY_PREFIX)jsig.diz endif diff -r 183ae2332dd9 -r f4e854a77aa3 hotspot/test/Makefile --- a/hotspot/test/Makefile Wed Jul 05 22:29:12 2017 +0200 +++ b/hotspot/test/Makefile Wed Jul 05 22:30:52 2017 +0200 @@ -50,7 +50,7 @@ UNAME = uname UNIQ = uniq WC = wc -ZIP = zip +ZIPEXE = zip define NEWLINE @@ -213,7 +213,7 @@ ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \ && $(CD) $(ABS_TEST_OUTPUT_DIR) \ && $(CHMOD) -R a+r . \ - && $(ZIP) -q -r $(ARCHIVE_BUNDLE) . ) + && $(ZIPEXE) -q -r $(ARCHIVE_BUNDLE) . ) # important results files SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt") @@ -327,7 +327,7 @@ else ifeq ($(shell expr $(CONCURRENCY) \> 12), 1) CONCURRENCY := 12 endif -else +else CONCURRENCY := 1 endif JTREG_BASIC_OPTIONS += -concurrency:$(CONCURRENCY) diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/.hgtags --- a/jaxp/.hgtags Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/.hgtags Wed Jul 05 22:30:52 2017 +0200 @@ -388,3 +388,4 @@ ce81d03ad7320dca3d673374c1a33bc0efd9136a jdk-9+143 99be33734ff62b75116b1202d49a4d4e1bda4226 jdk-9+144 71558b38bad786f11350790cef7d2c6409813e91 jdk-9+145 +09eda28b98e4b9cae1d29e94f0cf1a01cc42c207 jdk-9+146 diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java Wed Jul 05 22:30:52 2017 +0200 @@ -530,6 +530,10 @@ XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se); } + // try setting other JDK-impl properties, ignore if not supported + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE, + _xsltc.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), false); + return(parse(reader, input)); } catch (ParserConfigurationException e) { @@ -1342,12 +1346,14 @@ } else { SyntaxTreeNode parent = _parentStack.peek(); + if (element.getClass().isAssignableFrom(Import.class) && parent.notTypeOf(Import.class)) { ErrorMsg err = new ErrorMsg(ErrorMsg.IMPORT_PRECEDE_OTHERS_ERR, prefix+':'+localname); throw new SAXException(err.toString()); } + parent.addElement(element); element.setParent(parent); } diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java Wed Jul 05 22:30:52 2017 +0200 @@ -43,12 +43,14 @@ import java.util.Objects; import java.util.Properties; import java.util.Vector; +import java.util.jar.Attributes; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.jar.Manifest; import javax.xml.XMLConstants; import javax.xml.catalog.CatalogFeatures; import jdk.xml.internal.JdkXmlFeatures; +import jdk.xml.internal.JdkXmlUtils; import org.xml.sax.InputSource; import org.xml.sax.XMLReader; @@ -116,8 +118,8 @@ private File _destDir = null; // -d private int _outputType = FILE_OUTPUT; // by default - private Vector _classes; - private Vector _bcelClasses; + private ArrayList _classes; + private ArrayList _bcelClasses; private boolean _callsNodeset = false; private boolean _multiDocument = false; private boolean _hasIdCall = false; @@ -160,7 +162,7 @@ /** * HashMap with the loaded classes */ - private final Map _externalExtensionFunctions; + private final Map> _externalExtensionFunctions; /** * Catalog features @@ -168,6 +170,11 @@ CatalogFeatures _catalogFeatures; /** + * CDATA chunk size + */ + int _cdataChunkSize; + + /** * XSLTC compiler constructor */ public XSLTC(boolean useServicesMechanism, JdkXmlFeatures featureManager) { @@ -230,6 +237,8 @@ return _extensionClassLoader; } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { return _catalogFeatures; + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + return _cdataChunkSize; } return null; } @@ -254,6 +263,8 @@ _externalExtensionFunctions.clear(); } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { _catalogFeatures = (CatalogFeatures)value; + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + _cdataChunkSize = Integer.parseInt((String)value); } } @@ -284,11 +295,11 @@ public void init() { reset(); _reader = null; - _classes = new Vector(); - _bcelClasses = new Vector(); + _classes = new ArrayList<>(); + _bcelClasses = new ArrayList<>(); } - private void setExternalExtensionFunctions(String name, Class clazz) { + private void setExternalExtensionFunctions(String name, Class clazz) { if (_isSecureProcessing && clazz != null && !_externalExtensionFunctions.containsKey(name)) { _externalExtensionFunctions.put(name, clazz); } @@ -319,7 +330,7 @@ * Returns unmodifiable view of HashMap with loaded external extension * functions - will be needed for the TransformerImpl */ - public Map getExternalExtensionFunctions() { + public Map> getExternalExtensionFunctions() { return Collections.unmodifiableMap(_externalExtensionFunctions); } @@ -563,7 +574,7 @@ final int count = _classes.size(); final byte[][] result = new byte[count][1]; for (int i = 0; i < count; i++) - result[i] = (byte[])_classes.elementAt(i); + result[i] = _classes.get(i).toByteArray(); return result; } @@ -907,7 +918,7 @@ getOutputFile(clazz.getClassName())))); break; case JAR_OUTPUT: - _bcelClasses.addElement(clazz); + _bcelClasses.add(clazz); break; case BYTEARRAY_OUTPUT: case BYTEARRAY_AND_FILE_OUTPUT: @@ -915,13 +926,13 @@ case CLASSLOADER_OUTPUT: ByteArrayOutputStream out = new ByteArrayOutputStream(2048); clazz.dump(out); - _classes.addElement(out.toByteArray()); + _classes.add(out); if (_outputType == BYTEARRAY_AND_FILE_OUTPUT) clazz.dump(new BufferedOutputStream( new FileOutputStream(getOutputFile(clazz.getClassName())))); else if (_outputType == BYTEARRAY_AND_JAR_OUTPUT) - _bcelClasses.addElement(clazz); + _bcelClasses.add(clazz); break; } @@ -945,30 +956,24 @@ // create the manifest final Manifest manifest = new Manifest(); final java.util.jar.Attributes atrs = manifest.getMainAttributes(); - atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION,"1.2"); + atrs.put(java.util.jar.Attributes.Name.MANIFEST_VERSION, "1.2"); - final Map map = manifest.getEntries(); + final Map map = manifest.getEntries(); // create manifest - Enumeration classes = _bcelClasses.elements(); final String now = (new Date()).toString(); final java.util.jar.Attributes.Name dateAttr = new java.util.jar.Attributes.Name("Date"); - while (classes.hasMoreElements()) { - final JavaClass clazz = (JavaClass)classes.nextElement(); - final String className = clazz.getClassName().replace('.','/'); - final java.util.jar.Attributes attr = new java.util.jar.Attributes(); - attr.put(dateAttr, now); - map.put(className+".class", attr); - } final File jarFile = new File(_destDir, _jarFileName); final JarOutputStream jos = new JarOutputStream(new FileOutputStream(jarFile), manifest); - classes = _bcelClasses.elements(); - while (classes.hasMoreElements()) { - final JavaClass clazz = (JavaClass)classes.nextElement(); - final String className = clazz.getClassName().replace('.','/'); - jos.putNextEntry(new JarEntry(className+".class")); + + for (JavaClass clazz : _bcelClasses) { + final String className = clazz.getClassName().replace('.', '/'); + final java.util.jar.Attributes attr = new java.util.jar.Attributes(); + attr.put(dateAttr, now); + map.put(className + ".class", attr); + jos.putNextEntry(new JarEntry(className + ".class")); final ByteArrayOutputStream out = new ByteArrayOutputStream(2048); clazz.dump(out); // dump() closes it's output stream out.writeTo(jos); diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -165,14 +165,14 @@ }; static final class TransletClassLoader extends ClassLoader { - private final Map _loadedExternalExtensionFunctions; + private final Map> _loadedExternalExtensionFunctions; TransletClassLoader(ClassLoader parent) { super(parent); _loadedExternalExtensionFunctions = null; } - TransletClassLoader(ClassLoader parent,Map mapEF) { + TransletClassLoader(ClassLoader parent, Map> mapEF) { super(parent); _loadedExternalExtensionFunctions = mapEF; } @@ -215,7 +215,7 @@ /** * Create an XSLTC template object from the translet class definition(s). */ - protected TemplatesImpl(Class[] transletClasses, String transletName, + protected TemplatesImpl(Class[] transletClasses, String transletName, Properties outputProperties, int indentNumber, TransformerFactoryImpl tfactory) { @@ -481,6 +481,7 @@ // the module needs access to runtime classes Module thisModule = TemplatesImpl.class.getModule(); + Arrays.asList(Constants.PKGS_USED_BY_TRANSLET_CLASSES).forEach(p -> { thisModule.addExports(p, m); }); diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -222,7 +222,8 @@ private boolean _useServicesMechanism; /** - * protocols allowed for external references set by the stylesheet processing instruction, Import and Include element. + * protocols allowed for external references set by the stylesheet + * processing instruction, Import and Include element. */ private String _accessExternalStylesheet = XalanConstants.EXTERNAL_ACCESS_DEFAULT; /** @@ -240,7 +241,7 @@ // Unmodifiable view of external extension function from xslt compiler // It will be populated by user-specified extension functions during the // type checking - private Map _xsltcExtensionFunctions; + private Map> _xsltcExtensionFunctions; CatalogResolver _catalogUriResolver; CatalogFeatures _catalogFeatures; @@ -251,6 +252,8 @@ String _catalogPrefer = null; String _catalogResolve = null; + int _cdataChunkSize = JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT; + /** * javax.xml.transform.sax.TransformerFactory implementation. */ @@ -283,7 +286,7 @@ _xsltcExtensionFunctions = null; } - public Map getExternalExtensionsMap() { + public Map> getExternalExtensionsMap() { return _xsltcExtensionFunctions; } @@ -367,6 +370,8 @@ return _catalogResolve; } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { return buildCatalogFeatures(); + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + return _cdataChunkSize; } /** Check to see if the property is managed by the security manager **/ @@ -507,6 +512,9 @@ _catalogResolve = (String) value; cfBuilder = CatalogFeatures.builder().with(Feature.RESOLVE, _catalogResolve); return; + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + _cdataChunkSize = JdkXmlUtils.getValue(value, _cdataChunkSize); + return; } if (_xmlSecurityManager != null && @@ -896,10 +904,10 @@ transletName = _packageName + "." + transletName; try { - final Class clazz = ObjectFactory.findProviderClass(transletName, true); + final Class clazz = ObjectFactory.findProviderClass(transletName, true); resetTransientAttributes(); - templates = new TemplatesImpl(new Class[]{clazz}, transletName, null, _indentNumber, this); + templates = new TemplatesImpl(new Class[]{clazz}, transletName, null, _indentNumber, this); if (_uriResolver != null) { templates.setURIResolver(_uriResolver); } diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -230,6 +230,7 @@ // Catalog is enabled by default boolean _useCatalog = true; + int _cdataChunkSize = JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT; /** * This class wraps an ErrorListener into a MessageHandler in order to @@ -284,6 +285,9 @@ _readerManager.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD); _readerManager.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, _isSecureProcessing); _readerManager.setProperty(XalanConstants.SECURITY_MANAGER, _securityManager); + _cdataChunkSize = JdkXmlUtils.getValue(_tfactory.getAttribute(JdkXmlUtils.CDATA_CHUNK_SIZE), + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); + _readerManager.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, _cdataChunkSize); _useCatalog = _tfactory.getFeature(XMLConstants.USE_CATALOG); if (_useCatalog) { diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/Util.java Wed Jul 05 22:30:52 2017 +0200 @@ -137,13 +137,11 @@ reader.setFeature ("http://xml.org/sax/features/namespace-prefixes",false); - try { - reader.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, - xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD)); - } catch (SAXNotRecognizedException e) { - XMLSecurityManager.printWarning(reader.getClass().getName(), - XMLConstants.ACCESS_EXTERNAL_DTD, e); - } + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD, + xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true); + + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE, + xsltc.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), false); String lastProperty = ""; try { diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/dom/DOMConfigurationImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -292,7 +292,8 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -368,6 +369,8 @@ for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { setProperty(f.getPropertyName(), null); } + + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } // (SymbolTable) diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/PropertyManager.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/PropertyManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/PropertyManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -144,6 +144,8 @@ for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { supportedProps.put(f.getPropertyName(), null); } + + supportedProps.put(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } private void initWriterProps(){ diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java Wed Jul 05 22:30:52 2017 +0200 @@ -1041,14 +1041,14 @@ * * @param delimiter The string that signifies the end of the character * data to be scanned. - * @param data The data structure to fill. + * @param buffer The data structure to fill. + * @param chunkLimit the size limit of the data to be scanned * * @return Returns true if there is more data to scan, false otherwise. * * @throws IOException Thrown if i/o error occurs. - * @throws EOFException Thrown on end of file. */ - protected boolean scanData(String delimiter, XMLStringBuffer buffer) + protected boolean scanData(String delimiter, XMLStringBuffer buffer, int chunkLimit) throws IOException { boolean done = false; @@ -1152,82 +1152,50 @@ } // iterate over buffer looking for delimiter - if (external) { - OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { - c = fCurrentEntity.ch[fCurrentEntity.position++]; - if (c == charAt0) { - // looks like we just hit the delimiter - int delimOffset = fCurrentEntity.position - 1; - for (int i = 1; i < delimLen; i++) { - if (fCurrentEntity.position == fCurrentEntity.count) { - fCurrentEntity.position -= i; - break OUTER; - } - c = fCurrentEntity.ch[fCurrentEntity.position++]; - if (delimiter.charAt(i) != c) { - fCurrentEntity.position--; - break; - } - } - if (fCurrentEntity.position == delimOffset + delimLen) { - done = true; + OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { + c = fCurrentEntity.ch[fCurrentEntity.position++]; + if (c == charAt0) { + // looks like we just hit the delimiter + int delimOffset = fCurrentEntity.position - 1; + for (int i = 1; i < delimLen; i++) { + if (fCurrentEntity.position == fCurrentEntity.count) { + fCurrentEntity.position -= i; + break OUTER; + } + c = fCurrentEntity.ch[fCurrentEntity.position++]; + if (delimiter.charAt(i) != c) { + fCurrentEntity.position--; break; - } - } - else if (c == '\n' || c == '\r' || c == 0x85 || c == 0x2028) { - fCurrentEntity.position--; + } + } + if (fCurrentEntity.position == delimOffset + delimLen) { + done = true; break; - } - // In external entities control characters cannot appear - // as literals so do not skip over them. - else if (!XML11Char.isXML11ValidLiteral(c)) { - fCurrentEntity.position--; - int length = fCurrentEntity.position - offset; - fCurrentEntity.columnNumber += length - newlines; - checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); - buffer.append(fCurrentEntity.ch, offset, length); - return true; - } + } + } + else if ((external && (c == '\n' || c == '\r' || c == 0x85 || c == 0x2028)) + || (!external && c == '\n')) { + fCurrentEntity.position--; + break; + } + // In external entities control characters cannot appear + // as literals so do not skip over them. + else if ((external && !XML11Char.isXML11ValidLiteral(c)) + // Control characters are allowed to appear as literals in internal entities. + || (!external && !XML11Char.isXML11Valid(c))) { + fCurrentEntity.position--; + int length = fCurrentEntity.position - offset; + fCurrentEntity.columnNumber += length - newlines; + checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); + buffer.append(fCurrentEntity.ch, offset, length); + return true; + } + if (chunkLimit > 0 && + (buffer.length + fCurrentEntity.position - offset) >= chunkLimit) { + break; } } - else { - OUTER: while (fCurrentEntity.position < fCurrentEntity.count) { - c = fCurrentEntity.ch[fCurrentEntity.position++]; - if (c == charAt0) { - // looks like we just hit the delimiter - int delimOffset = fCurrentEntity.position - 1; - for (int i = 1; i < delimLen; i++) { - if (fCurrentEntity.position == fCurrentEntity.count) { - fCurrentEntity.position -= i; - break OUTER; - } - c = fCurrentEntity.ch[fCurrentEntity.position++]; - if (delimiter.charAt(i) != c) { - fCurrentEntity.position--; - break; - } - } - if (fCurrentEntity.position == delimOffset + delimLen) { - done = true; - break; - } - } - else if (c == '\n') { - fCurrentEntity.position--; - break; - } - // Control characters are allowed to appear as literals - // in internal entities. - else if (!XML11Char.isXML11Valid(c)) { - fCurrentEntity.position--; - int length = fCurrentEntity.position - offset; - fCurrentEntity.columnNumber += length - newlines; - checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); - buffer.append(fCurrentEntity.ch, offset, length); - return true; - } - } - } + int length = fCurrentEntity.position - offset; fCurrentEntity.columnNumber += length - newlines; checkEntityLimit(NameType.COMMENT, fCurrentEntity, offset, length); @@ -1236,8 +1204,10 @@ } buffer.append(fCurrentEntity.ch, offset, length); - // return true if string was skipped - } while (!done); + if (chunkLimit > 0 && buffer.length >= chunkLimit) { + break; + } + } while (!done && chunkLimit == 0); return !done; } // scanData(String,XMLString) diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -388,7 +388,7 @@ return false; fStringBuffer.clear(); - while (fEntityScanner.scanData("]", fStringBuffer)) { + while (fEntityScanner.scanData("]", fStringBuffer, 0)) { int c = fEntityScanner.peekChar(); if (c != -1) { if (XMLChar.isHighSurrogate(c)) { diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -200,7 +200,8 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; /** Property defaults. */ @@ -212,7 +213,8 @@ null, null, null, - null + null, + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT }; @@ -269,6 +271,9 @@ /** SubScanner state: inside scanContent method. */ protected boolean fInScanContent = false; protected boolean fLastSectionWasCData = false; + protected boolean fCDataStart = false; + protected boolean fInCData = false; + protected boolean fCDataEnd = false; protected boolean fLastSectionWasEntityReference = false; protected boolean fLastSectionWasCharacterData = false; @@ -319,6 +324,11 @@ protected boolean fDisallowDoctype = false; /** + * CDATA chunk size limit + */ + private int fChunkSize; + + /** * comma-delimited list of protocols that are allowed for the purpose * of accessing external dtd or entity references */ @@ -490,12 +500,18 @@ //therefore we don't need to take care of anything here. So Just break; break; case XMLStreamConstants.CDATA: - fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity); - fDocumentHandler.startCDATA(null); - //xxx: check if CDATA values comes from getCharacterData() function + fEntityScanner.checkNodeCount(fEntityScanner.fCurrentEntity); + if (fCDataStart) { + fDocumentHandler.startCDATA(null); + fCDataStart = false; + fInCData = true; + } + fDocumentHandler.characters(getCharacterData(),null); - fDocumentHandler.endCDATA(null); - //System.out.println(" in CDATA of the XMLNSDocumentScannerImpl"); + if (fCDataEnd) { + fDocumentHandler.endCDATA(null); + fCDataEnd = false; + } break; case XMLStreamConstants.NOTATION_DECLARATION : break; @@ -603,6 +619,8 @@ fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); fStrictURI = componentManager.getFeature(STANDARD_URI_CONFORMANT, false); + fChunkSize = JdkXmlUtils.getValue(componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); resetCommon(); //fEntityManager.test(); @@ -647,6 +665,8 @@ fAccessExternalDTD = spm.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); fSecurityManager = (XMLSecurityManager)propertyManager.getProperty(Constants.SECURITY_MANAGER); + fChunkSize = JdkXmlUtils.getValue(propertyManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE), + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); resetCommon(); } // reset(XMLComponentManager) @@ -1665,34 +1685,11 @@ while (true) { //scanData will fill the contentBuffer - if (!fEntityScanner.scanData("]]>", contentBuffer)) { + if (!fEntityScanner.scanData("]]>", contentBuffer, fChunkSize)) { + fInCData = false; + fCDataEnd = true; + fMarkupDepth--; break ; - /** We dont need all this code if we pass ']]>' as delimeter.. - * int brackets = 2; - * while (fEntityScanner.skipChar(']')) { - * brackets++; - * } - * - * //When we find more than 2 square brackets - * if (fDocumentHandler != null && brackets > 2) { - * //we dont need to clear the buffer.. - * //contentBuffer.clear(); - * for (int i = 2; i < brackets; i++) { - * contentBuffer.append(']'); - * } - * fDocumentHandler.characters(contentBuffer, null); - * } - * - * if (fEntityScanner.skipChar('>')) { - * break; - * } - * if (fDocumentHandler != null) { - * //we dont need to clear the buffer now.. - * //contentBuffer.clear(); - * contentBuffer.append("]]"); - * fDocumentHandler.characters(contentBuffer, null); - * } - **/ } else { int c = fEntityScanner.peekChar(); if (c != -1 && isInvalidLiteral(c)) { @@ -1705,6 +1702,9 @@ new Object[]{Integer.toString(c,16)}); fEntityScanner.scanChar(null); } + } else { + //CData partially returned due to the size limit + break; } //by this time we have also read surrogate contents if any... if (fDocumentHandler != null) { @@ -1712,16 +1712,6 @@ } } } - fMarkupDepth--; - - if (fDocumentHandler != null && contentBuffer.length > 0) { - //fDocumentHandler.characters(contentBuffer, null); - } - - // call handler - if (fDocumentHandler != null) { - //fDocumentHandler.endCDATA(null); - } return true; @@ -2635,6 +2625,7 @@ } setScannerState(SCANNER_STATE_COMMENT); } else if (fEntityScanner.skipString(cdata)) { + fCDataStart = true; setScannerState(SCANNER_STATE_CDATA ); } else if (!scanForDoctypeHook()) { reportFatalError("MarkupNotRecognizedInContent", @@ -3015,9 +3006,11 @@ //xxx: What if CDATA is the first event //<>]]>append - //we should not clear the buffer only when the last state was either SCANNER_STATE_REFERENCE or + //we should not clear the buffer only when the last state was + //either SCANNER_STATE_REFERENCE or //SCANNER_STATE_CHARACTER_DATA or SCANNER_STATE_REFERENCE - if(fIsCoalesce && ( fLastSectionWasEntityReference || fLastSectionWasCData || fLastSectionWasCharacterData)){ + if(fIsCoalesce && ( fLastSectionWasEntityReference || + fLastSectionWasCData || fLastSectionWasCharacterData)){ fLastSectionWasCData = true ; fLastSectionWasEntityReference = false; fLastSectionWasCharacterData = false; @@ -3026,7 +3019,7 @@ fContentBuffer.clear(); } fUsebuffer = true; - //CDATA section is completely read in all the case. + //CDATA section is read up to the chunk size limit scanCDATASection(fContentBuffer , true); setScannerState(SCANNER_STATE_CONTENT); //1. if fIsCoalesce is set to true we set the variable fLastSectionWasCData to true @@ -3036,13 +3029,16 @@ //2. Check if application has set for reporting CDATA event //3. if the application has neither set the fIsCoalesce to true nor fReportCdataEvent //return the cdata event as characters. - if(fIsCoalesce){ + if (fIsCoalesce) { fLastSectionWasCData = true ; //there might be more data to coalesce. continue; - }else if(fReportCdataEvent){ + } else if(fReportCdataEvent) { + if (!fCDataEnd) { + setScannerState(SCANNER_STATE_CDATA); + } return XMLEvent.CDATA; - } else{ + } else { return XMLEvent.CHARACTERS; } } @@ -3051,9 +3047,11 @@ fMarkupDepth++; foundBuiltInRefs = false; - //we should not clear the buffer only when the last state was either CDATA or + //we should not clear the buffer only when the last state was + //either CDATA or //SCANNER_STATE_CHARACTER_DATA or SCANNER_STATE_REFERENCE - if(fIsCoalesce && ( fLastSectionWasEntityReference || fLastSectionWasCData || fLastSectionWasCharacterData)){ + if(fIsCoalesce && ( fLastSectionWasEntityReference || + fLastSectionWasCData || fLastSectionWasCharacterData)){ //fLastSectionWasEntityReference or fLastSectionWasCData are only //used when fIsCoalesce is set to true. fLastSectionWasEntityReference = true ; diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -968,9 +968,11 @@ case SCANNER_STATE_CONTENT: { reportFatalError("ContentIllegalInProlog", null); fEntityScanner.scanChar(null); + return -1; } case SCANNER_STATE_REFERENCE: { reportFatalError("ReferenceIllegalInProlog", null); + return -1; } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -217,7 +217,8 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; /** Property defaults. */ @@ -232,7 +233,8 @@ null, null, null, - null + null, + JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT }; private static final String XMLEntity = "[xml]".intern(); diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java Wed Jul 05 22:30:52 2017 +0200 @@ -1350,13 +1350,15 @@ * @param delimiter The string that signifies the end of the character * data to be scanned. * @param buffer The XMLStringBuffer to fill. + * @param chunkLimit the size limit of the data to be scanned. Zero by default + * indicating no limit. * * @return Returns true if there is more data to scan, false otherwise. * * @throws IOException Thrown if i/o error occurs. * @throws EOFException Thrown on end of file. */ - protected boolean scanData(String delimiter, XMLStringBuffer buffer) + protected boolean scanData(String delimiter, XMLStringBuffer buffer, int chunkLimit) throws IOException { boolean done = false; @@ -1505,6 +1507,10 @@ buffer.append(fCurrentEntity.ch, offset, length); return true; } + if (chunkLimit > 0 && + (buffer.length + fCurrentEntity.position - offset) >= chunkLimit) { + break; + } } int length = fCurrentEntity.position - offset; fCurrentEntity.columnNumber += length - newlines; @@ -1520,7 +1526,10 @@ print(); System.out.println(" -> " + done); } - } while (!done); + if (chunkLimit > 0 && buffer.length >= chunkLimit) { + break; + } + } while (!done && chunkLimit == 0); return !done; } // scanData(String, XMLStringBuffer) diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLScanner.java Wed Jul 05 22:30:52 2017 +0200 @@ -760,7 +760,7 @@ // since scanData appends the parsed data to the buffer passed // a while loop would append the whole of parsed data to the buffer(data:XMLStringBuffer) //until all of the data is buffered. - if (fEntityScanner.scanData("?>", data)) { + if (fEntityScanner.scanData("?>", data, 0)) { do { int c = fEntityScanner.peekChar(); if (c != -1) { @@ -772,7 +772,7 @@ fEntityScanner.scanChar(null); } } - } while (fEntityScanner.scanData("?>", data)); + } while (fEntityScanner.scanData("?>", data, 0)); } } // scanPIData(String,XMLString) @@ -797,7 +797,7 @@ // text // REVISIT: handle invalid character, eof text.clear(); - while (fEntityScanner.scanData("--", text)) { + while (fEntityScanner.scanData("--", text, 0)) { int c = fEntityScanner.peekChar(); //System.out.println( "XMLScanner#scanComment#text.toString() == " + text.toString() ); diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaLoader.java Wed Jul 05 22:30:52 2017 +0200 @@ -250,7 +250,8 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; // Data @@ -282,7 +283,7 @@ private XSDDescription fXSDDescription = new XSDDescription(); private String faccessExternalSchema = Constants.EXTERNAL_ACCESS_DEFAULT; - private WeakHashMap fJAXPCache; + private WeakHashMap fJAXPCache; private Locale fLocale = Locale.getDefault(); // XSLoader attributes @@ -366,7 +367,7 @@ } fCMBuilder = builder; fSchemaHandler = new XSDHandler(fGrammarBucket); - fJAXPCache = new WeakHashMap(); + fJAXPCache = new WeakHashMap<>(); fSettingsChanged = true; } @@ -377,7 +378,7 @@ * are recognized. */ public String[] getRecognizedFeatures() { - return (String[])(RECOGNIZED_FEATURES.clone()); + return RECOGNIZED_FEATURES.clone(); } // getRecognizedFeatures(): String[] /** @@ -419,7 +420,7 @@ * are recognized. */ public String[] getRecognizedProperties() { - return (String[])(RECOGNIZED_PROPERTIES.clone()); + return RECOGNIZED_PROPERTIES.clone(); } // getRecognizedProperties(): String[] /** @@ -568,7 +569,7 @@ desc.setBaseSystemId(source.getBaseSystemId()); desc.setLiteralSystemId( source.getSystemId()); // none of the other fields make sense for preparsing - Map locationPairs = new HashMap(); + Map locationPairs = new HashMap<>(); // Process external schema location properties. // We don't call tokenizeSchemaLocationStr here, because we also want // to check whether the values are valid URI. @@ -665,7 +666,7 @@ // add external schema locations to the location pairs public static void processExternalHints(String sl, String nsl, - Map locations, + Map locations, XMLErrorReporter er) { if (sl != null) { try { @@ -694,9 +695,10 @@ if (nsl != null) { try { // similarly for no ns schema location property - XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); + XSAttributeDecl attrDecl = SchemaGrammar.SG_XSI.getGlobalAttributeDecl( + SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); attrDecl.fType.validate(nsl, null, null); - LocationArray la = ((LocationArray)locations.get(XMLSymbols.EMPTY_STRING)); + LocationArray la = locations.get(XMLSymbols.EMPTY_STRING); if(la == null) { la = new LocationArray(); locations.put(XMLSymbols.EMPTY_STRING, la); @@ -763,14 +765,14 @@ return; } - Class componentType = fJAXPSource.getClass().getComponentType(); + Class componentType = fJAXPSource.getClass().getComponentType(); XMLInputSource xis = null; String sid = null; if (componentType == null) { // Not an array if (fJAXPSource instanceof InputStream || fJAXPSource instanceof InputSource) { - SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(fJAXPSource); + SchemaGrammar g = fJAXPCache.get(fJAXPSource); if (g != null) { fGrammarBucket.putGrammar(g); return; @@ -823,7 +825,7 @@ for (int i = 0; i < objArr.length; i++) { if (objArr[i] instanceof InputStream || objArr[i] instanceof InputSource) { - SchemaGrammar g = (SchemaGrammar)fJAXPCache.get(objArr[i]); + SchemaGrammar g = fJAXPCache.get(objArr[i]); if (g != null) { fGrammarBucket.putGrammar(g); continue; diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/XMLSchemaValidator.java Wed Jul 05 22:30:52 2017 +0200 @@ -344,13 +344,14 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; /** Property defaults. */ private static final Object[] PROPERTY_DEFAULTS = { null, null, null, null, null, null, null, null, null, null, null, null, - null, null, null, null}; + null, null, null, null, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT }; // this is the number of valuestores of each kind // we expect an element to have. It's almost @@ -358,10 +359,14 @@ protected static final int ID_CONSTRAINT_NUM = 1; // xsi:* attribute declarations - static final XSAttributeDecl XSI_TYPE = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); - static final XSAttributeDecl XSI_NIL = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); - static final XSAttributeDecl XSI_SCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); - static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); + static final XSAttributeDecl XSI_TYPE = + SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_TYPE); + static final XSAttributeDecl XSI_NIL = + SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NIL); + static final XSAttributeDecl XSI_SCHEMALOCATION = + SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_SCHEMALOCATION); + static final XSAttributeDecl XSI_NONAMESPACESCHEMALOCATION = + SchemaGrammar.SG_XSI.getGlobalAttributeDecl(SchemaSymbols.XSI_NONAMESPACESCHEMALOCATION); // // Data diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/opti/SchemaParsingConfig.java Wed Jul 05 22:30:52 2017 +0200 @@ -336,7 +336,8 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -368,6 +369,7 @@ fValidationManager = new ValidationManager(); fProperties.put(VALIDATION_MANAGER, fValidationManager); + fProperties.put(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); fVersionDetector = new XMLVersionDetector(); diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/xs/traversers/XSDHandler.java Wed Jul 05 22:30:52 2017 +0200 @@ -350,7 +350,7 @@ // This map's job is to act as a link between the Schema Element and its // XSDocumentInfo object. - private Map fDoc2XSDocumentMap = new HashMap(); + private Map fDoc2XSDocumentMap = new HashMap<>(); // map between elements and the XSDocumentInfo // objects that correspond to the documents being redefined. @@ -1104,10 +1104,12 @@ fSchemaGrammarDescription.setTargetNamespace(callerTNS); boolean alreadyTraversed = false; - XMLInputSource schemaSource = resolveSchemaSource(fSchemaGrammarDescription, mustResolve, child, true); + XMLInputSource schemaSource = + resolveSchemaSource(fSchemaGrammarDescription, mustResolve, child, true); if (fNamespaceGrowth && refType == XSDDescription.CONTEXT_INCLUDE) { try { - final String schemaId = XMLEntityManager.expandSystemId(schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); + final String schemaId = XMLEntityManager.expandSystemId( + schemaSource.getSystemId(), schemaSource.getBaseSystemId(), false); alreadyTraversed = sg.getDocumentLocations().contains(schemaId); } catch(MalformedURIException e) { @@ -1133,10 +1135,11 @@ // To handle mutual s XSDocumentInfo newSchemaInfo = null; if (fLastSchemaWasDuplicate) { - newSchemaInfo = newSchemaRoot == null ? null : (XSDocumentInfo)fDoc2XSDocumentMap.get(newSchemaRoot); + newSchemaInfo = newSchemaRoot == null ? null : fDoc2XSDocumentMap.get(newSchemaRoot); } else { - newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, fSchemaGrammarDescription, importCollision); + newSchemaInfo = constructTrees(newSchemaRoot, schemaHint, + fSchemaGrammarDescription, importCollision); } if (localName.equals(SchemaSymbols.ELT_REDEFINE) && @@ -3552,9 +3555,11 @@ // than checking its value. Don't set the ERROR_HANDLER // or LOCALE properties unless they've actually changed. if (fErrorHandler != fSchemaParser.getProperty(ERROR_HANDLER)) { - fSchemaParser.setProperty(ERROR_HANDLER, (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); + fSchemaParser.setProperty(ERROR_HANDLER, + (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); if (fAnnotationValidator != null) { - fAnnotationValidator.setProperty(ERROR_HANDLER, (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); + fAnnotationValidator.setProperty(ERROR_HANDLER, + (fErrorHandler != null) ? fErrorHandler : new DefaultErrorHandler()); } } if (fLocale != fSchemaParser.getProperty(LOCALE)) { @@ -3567,7 +3572,8 @@ catch (XMLConfigurationException e) {} try { - fSchemaParser.setFeature(CONTINUE_AFTER_FATAL_ERROR, fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR)); + fSchemaParser.setFeature(CONTINUE_AFTER_FATAL_ERROR, + fErrorReporter.getFeature(CONTINUE_AFTER_FATAL_ERROR)); } catch (XMLConfigurationException e) {} try { @@ -3601,13 +3607,16 @@ } } catch (XMLConfigurationException e) {} - fSecurityPropertyMgr = (XMLSecurityPropertyManager) componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); + fSecurityPropertyMgr = (XMLSecurityPropertyManager) + componentManager.getProperty(XML_SECURITY_PROPERTY_MANAGER); //Passing on the setting to the parser fSchemaParser.setProperty(XML_SECURITY_PROPERTY_MANAGER, fSecurityPropertyMgr); - fAccessExternalDTD = fSecurityPropertyMgr.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); - fAccessExternalSchema = fSecurityPropertyMgr.getValue(XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); + fAccessExternalDTD = fSecurityPropertyMgr.getValue( + XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_DTD); + fAccessExternalSchema = fSecurityPropertyMgr.getValue( + XMLSecurityPropertyManager.Property.ACCESS_EXTERNAL_SCHEMA); // Passing the Catalog settings to the parser fUseCatalog = componentManager.getFeature(XMLConstants.USE_CATALOG); @@ -3620,9 +3629,16 @@ fResolve = (String)componentManager.getProperty(JdkXmlUtils.CATALOG_RESOLVE); for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { - fSchemaParser.setProperty(f.getPropertyName(), componentManager.getProperty(f.getPropertyName())); - fEntityManager.setProperty(f.getPropertyName(), componentManager.getProperty(f.getPropertyName())); + fSchemaParser.setProperty(f.getPropertyName(), + componentManager.getProperty(f.getPropertyName())); + fEntityManager.setProperty(f.getPropertyName(), + componentManager.getProperty(f.getPropertyName())); } + + fSchemaParser.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, + componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE)); + fEntityManager.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, + componentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE)); } // reset(XMLComponentManager) @@ -3635,11 +3651,10 @@ for (int i = 0; i < fLocalElemStackPos; i++) { Element currElem = fLocalElementDecl[i]; - //XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getDocument(currElem)); - //XSDocumentInfo currSchema = (XSDocumentInfo)fDoc2XSDocumentMap.get(DOMUtil.getRoot(DOMUtil.getDocument(currElem))); XSDocumentInfo currSchema = fLocalElementDecl_schema[i]; SchemaGrammar currGrammar = fGrammarBucket.getGrammar(currSchema.fTargetNamespace); - fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, currGrammar, fAllContext[i], fParent[i], fLocalElemNamespaceContext[i]); + fElementTraverser.traverseLocal (fParticle[i], currElem, currSchema, + currGrammar, fAllContext[i], fParent[i], fLocalElemNamespaceContext[i]); // If it's an empty particle, remove it from the containing component. if (fParticle[i].fType == XSParticleDecl.PARTICLE_EMPTY) { XSModelGroupImpl group = null; @@ -4065,7 +4080,8 @@ Element decl, XSDocumentInfo decl_Doc) { if (DEBUG_NODE_POOL) { - System.out.println("DOCUMENT NS:"+ currSchema.fTargetNamespace+" hashcode:"+ ((Object)currSchema.fSchemaElement).hashCode()); + System.out.println("DOCUMENT NS:" + currSchema.fTargetNamespace + " hashcode:" + + ((Object)currSchema.fSchemaElement).hashCode()); } Object temp = decl_Doc; if (temp == null) { @@ -4091,7 +4107,8 @@ // returns whether more than s occur in children of elem private boolean nonAnnotationContent(Element elem) { - for(Element child = DOMUtil.getFirstChildElement(elem); child != null; child = DOMUtil.getNextSiblingElement(child)) { + for(Element child = DOMUtil.getFirstChildElement(elem); child != null; + child = DOMUtil.getNextSiblingElement(child)) { if(!(DOMUtil.getLocalName(child).equals(SchemaSymbols.ELT_ANNOTATION))) return true; } return false; diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/StreamValidatorHelper.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,7 +1,7 @@ /* * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. */ -/* + /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. @@ -17,7 +17,6 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - package com.sun.org.apache.xerces.internal.jaxp.validation; import com.sun.org.apache.xerces.internal.impl.Constants; @@ -47,7 +46,8 @@ import org.xml.sax.SAXException; /** - *

A validator helper for StreamSources.

+ *

+ * A validator helper for StreamSources.

* * @author Michael Glavassevich, IBM * @author Sunitha Reddy @@ -55,74 +55,98 @@ final class StreamValidatorHelper implements ValidatorHelper { // feature identifiers - - /** Feature identifier: parser settings. */ - private static final String PARSER_SETTINGS = - Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; + /** + * Feature identifier: parser settings. + */ + private static final String PARSER_SETTINGS + = Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS; // property identifiers - - /** Property identifier: entity resolver. */ - private static final String ENTITY_RESOLVER = - Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; + /** + * Property identifier: entity resolver. + */ + private static final String ENTITY_RESOLVER + = Constants.XERCES_PROPERTY_PREFIX + Constants.ENTITY_RESOLVER_PROPERTY; - /** Property identifier: error handler. */ - private static final String ERROR_HANDLER = - Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; + /** + * Property identifier: error handler. + */ + private static final String ERROR_HANDLER + = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_HANDLER_PROPERTY; - /** Property identifier: error reporter. */ - private static final String ERROR_REPORTER = - Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; + /** + * Property identifier: error reporter. + */ + private static final String ERROR_REPORTER + = Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY; - /** Property identifier: XML Schema validator. */ - private static final String SCHEMA_VALIDATOR = - Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY; + /** + * Property identifier: XML Schema validator. + */ + private static final String SCHEMA_VALIDATOR + = Constants.XERCES_PROPERTY_PREFIX + Constants.SCHEMA_VALIDATOR_PROPERTY; - /** Property identifier: symbol table. */ - private static final String SYMBOL_TABLE = - Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; + /** + * Property identifier: symbol table. + */ + private static final String SYMBOL_TABLE + = Constants.XERCES_PROPERTY_PREFIX + Constants.SYMBOL_TABLE_PROPERTY; - /** Property identifier: validation manager. */ - private static final String VALIDATION_MANAGER = - Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; + /** + * Property identifier: validation manager. + */ + private static final String VALIDATION_MANAGER + = Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY; - private static final String DEFAULT_TRANSFORMER_IMPL = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; + private static final String DEFAULT_TRANSFORMER_IMPL + = "com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl"; - /** Property id: security manager. */ - private static final String SECURITY_MANAGER = - Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; + /** + * Property id: security manager. + */ + private static final String SECURITY_MANAGER + = Constants.XERCES_PROPERTY_PREFIX + Constants.SECURITY_MANAGER_PROPERTY; // // Data // + /** + * SoftReference to parser configuration. * + */ + private SoftReference fConfiguration = new SoftReference<>(null); - /** SoftReference to parser configuration. **/ - private SoftReference fConfiguration = new SoftReference(null); - - /** Schema validator. **/ + /** + * Schema validator. * + */ private com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator fSchemaValidator; - /** Component manager. **/ + /** + * Component manager. * + */ private XMLSchemaValidatorComponentManager fComponentManager; private ValidatorHandlerImpl handler = null; public StreamValidatorHelper(XMLSchemaValidatorComponentManager componentManager) { fComponentManager = componentManager; - fSchemaValidator = (com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator) fComponentManager.getProperty(SCHEMA_VALIDATOR); + fSchemaValidator = (com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator) + fComponentManager.getProperty(SCHEMA_VALIDATOR); } public void validate(Source source, Result result) - throws SAXException, IOException { + throws SAXException, IOException { if (result == null || result instanceof StreamResult) { final StreamSource streamSource = (StreamSource) source; - TransformerHandler identityTransformerHandler ; + TransformerHandler identityTransformerHandler; - if( result!=null ) { + if (result != null) { try { - SAXTransformerFactory tf = fComponentManager.getFeature(Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ? - (SAXTransformerFactory)SAXTransformerFactory.newInstance() - : (SAXTransformerFactory) TransformerFactory.newInstance(DEFAULT_TRANSFORMER_IMPL, StreamValidatorHelper.class.getClassLoader()); + SAXTransformerFactory tf = fComponentManager.getFeature( + Constants.ORACLE_FEATURE_SERVICE_MECHANISM) ? + (SAXTransformerFactory) SAXTransformerFactory.newInstance() : + (SAXTransformerFactory) TransformerFactory.newInstance( + DEFAULT_TRANSFORMER_IMPL, + StreamValidatorHelper.class.getClassLoader()); identityTransformerHandler = tf.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new TransformerFactoryConfigurationError(e); @@ -133,13 +157,14 @@ identityTransformerHandler.setResult(result); } - XMLInputSource input = new XMLInputSource(streamSource.getPublicId(), streamSource.getSystemId(), null, false); + XMLInputSource input = new XMLInputSource(streamSource.getPublicId(), + streamSource.getSystemId(), null, false); input.setByteStream(streamSource.getInputStream()); input.setCharacterStream(streamSource.getReader()); // Gets the parser configuration. We'll create and initialize a new one, if we // haven't created one before or if the previous one was garbage collected. - XMLParserConfiguration config = (XMLParserConfiguration) fConfiguration.get(); + XMLParserConfiguration config = fConfiguration.get(); if (config == null) { config = initialize(); } @@ -155,18 +180,17 @@ try { config.parse(input); - } - catch (XMLParseException e) { + } catch (XMLParseException e) { throw Util.toSAXParseException(e); - } - catch (XNIException e) { + } catch (XNIException e) { throw Util.toSAXException(e); } return; } - throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage(fComponentManager.getLocale(), + throw new IllegalArgumentException(JAXPValidationMessageFormatter.formatMessage( + fComponentManager.getLocale(), "SourceResultMismatch", - new Object [] {source.getClass().getName(), result.getClass().getName()})); + new Object[]{source.getClass().getName(), result.getClass().getName()})); } private XMLParserConfiguration initialize() { @@ -197,7 +221,10 @@ // Passing on the CatalogFeatures settings JdkXmlUtils.catalogFeaturesConfig2Config(fComponentManager, config); - fConfiguration = new SoftReference(config); + config.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, + fComponentManager.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE)); + + fConfiguration = new SoftReference<>(config); return config; } diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaFactory.java Wed Jul 05 22:30:52 2017 +0200 @@ -165,6 +165,8 @@ for (Feature f : Feature.values()) { fXMLSchemaLoader.setProperty(f.getPropertyName(), null); } + + fXMLSchemaLoader.setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/jaxp/validation/XMLSchemaValidatorComponentManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -48,6 +48,7 @@ import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager; import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException; import javax.xml.catalog.CatalogFeatures; +import jdk.xml.internal.JdkXmlUtils; import org.w3c.dom.ls.LSResourceResolver; import org.xml.sax.ErrorHandler; @@ -311,6 +312,9 @@ for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { setProperty(f.getPropertyName(), grammarContainer.getProperty(f.getPropertyName())); } + + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, + grammarContainer.getProperty(JdkXmlUtils.CDATA_CHUNK_SIZE)); } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/DTDConfiguration.java Wed Jul 05 22:30:52 2017 +0200 @@ -345,7 +345,8 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -429,6 +430,8 @@ for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { setProperty(f.getPropertyName(), null); } + + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } // (SymbolTable,XMLGrammarPool) // diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/NonValidatingConfiguration.java Wed Jul 05 22:30:52 2017 +0200 @@ -328,7 +328,8 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -391,6 +392,8 @@ for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { setProperty(f.getPropertyName(), null); } + + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); } // (SymbolTable,XMLGrammarPool) // diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java Wed Jul 05 22:30:52 2017 +0200 @@ -561,7 +561,8 @@ JdkXmlUtils.CATALOG_DEFER, JdkXmlUtils.CATALOG_FILES, JdkXmlUtils.CATALOG_PREFER, - JdkXmlUtils.CATALOG_RESOLVE + JdkXmlUtils.CATALOG_RESOLVE, + JdkXmlUtils.CDATA_CHUNK_SIZE }; addRecognizedProperties(recognizedProperties); @@ -629,6 +630,8 @@ fProperties.put(f.getPropertyName(), null); } + setProperty(JdkXmlUtils.CDATA_CHUNK_SIZE, JdkXmlUtils.CDATA_CHUNK_SIZE_DEFAULT); + fConfigUpdated = false; } // (SymbolTable,XMLGrammarPool) diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/EmptySerializer.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/EmptySerializer.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/EmptySerializer.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved. */ /* * Licensed to the Apache Software Foundation (ASF) under one or more @@ -17,9 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: EmptySerializer.java,v 1.2.4.1 2005/09/15 08:15:16 suresh_emailid Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import java.io.IOException; @@ -48,235 +46,224 @@ public class EmptySerializer implements SerializationHandler { protected static final String ERR = "EmptySerializer method not over-ridden"; - /** - * @see SerializationHandler#asContentHandler() - */ - protected void couldThrowIOException() throws IOException - { + protected void couldThrowIOException() throws IOException { return; // don't do anything. } - protected void couldThrowSAXException() throws SAXException + protected void couldThrowSAXException() throws SAXException { + return; // don't do anything. + } + + protected void couldThrowSAXException(char[] chars, int off, int len) + throws SAXException { return; // don't do anything. } - protected void couldThrowSAXException(char[] chars, int off, int len) throws SAXException + protected void couldThrowSAXException(String elemQName) + throws SAXException { return; // don't do anything. } - protected void couldThrowSAXException(String elemQName) throws SAXException - { - return; // don't do anything. - } - - void aMethodIsCalled() - { - + void aMethodIsCalled() { // throw new RuntimeException(err); return; } - /** * @see SerializationHandler#asContentHandler() */ - public ContentHandler asContentHandler() throws IOException - { + public ContentHandler asContentHandler() throws IOException { couldThrowIOException(); return null; } + /** * @see SerializationHandler#setContentHandler(org.xml.sax.ContentHandler) */ - public void setContentHandler(ContentHandler ch) - { + public void setContentHandler(ContentHandler ch) { aMethodIsCalled(); } + /** * @see SerializationHandler#close() */ - public void close() - { + public void close() { aMethodIsCalled(); } + /** * @see SerializationHandler#getOutputFormat() */ - public Properties getOutputFormat() - { + public Properties getOutputFormat() { aMethodIsCalled(); return null; } + /** * @see SerializationHandler#getOutputStream() */ - public OutputStream getOutputStream() - { + public OutputStream getOutputStream() { aMethodIsCalled(); return null; } + /** * @see SerializationHandler#getWriter() */ - public Writer getWriter() - { + public Writer getWriter() { aMethodIsCalled(); return null; } + /** * @see SerializationHandler#reset() */ - public boolean reset() - { + public boolean reset() { aMethodIsCalled(); return false; } + /** * @see SerializationHandler#serialize(org.w3c.dom.Node) */ - public void serialize(Node node) throws IOException - { + public void serialize(Node node) throws IOException { couldThrowIOException(); } + /** * @see SerializationHandler#setCdataSectionElements(java.util.ArrayList) */ - public void setCdataSectionElements(ArrayList URI_and_localNames) - { + public void setCdataSectionElements(ArrayList URI_and_localNames) { aMethodIsCalled(); } + /** * @see SerializationHandler#setEscaping(boolean) */ - public boolean setEscaping(boolean escape) throws SAXException - { + public boolean setEscaping(boolean escape) throws SAXException { couldThrowSAXException(); return false; } + /** * @see SerializationHandler#setIndent(boolean) */ - public void setIndent(boolean indent) - { + public void setIndent(boolean indent) { aMethodIsCalled(); } + /** * @see SerializationHandler#setIndentAmount(int) */ - public void setIndentAmount(int spaces) - { + public void setIndentAmount(int spaces) { aMethodIsCalled(); } + /** * @see SerializationHandler#setIsStandalone(boolean) */ - public void setIsStandalone(boolean isStandalone) - { + public void setIsStandalone(boolean isStandalone) { aMethodIsCalled(); } + /** * @see SerializationHandler#setOutputFormat(java.util.Properties) */ - public void setOutputFormat(Properties format) - { + public void setOutputFormat(Properties format) { aMethodIsCalled(); } + /** * @see SerializationHandler#setOutputStream(java.io.OutputStream) */ - public void setOutputStream(OutputStream output) - { + public void setOutputStream(OutputStream output) { aMethodIsCalled(); } + /** * @see SerializationHandler#setVersion(java.lang.String) */ - public void setVersion(String version) - { + public void setVersion(String version) { aMethodIsCalled(); } + /** * @see SerializationHandler#setWriter(java.io.Writer) */ - public void setWriter(Writer writer) - { + public void setWriter(Writer writer) { aMethodIsCalled(); } + /** * @see SerializationHandler#setTransformer(javax.xml.transform.Transformer) */ - public void setTransformer(Transformer transformer) - { + public void setTransformer(Transformer transformer) { aMethodIsCalled(); } + /** * @see SerializationHandler#getTransformer() */ - public Transformer getTransformer() - { + public Transformer getTransformer() { aMethodIsCalled(); return null; } + /** * @see SerializationHandler#flushPending() */ - public void flushPending() throws SAXException - { + public void flushPending() throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void addAttribute( - String uri, - String localName, - String rawName, - String type, - String value, - boolean XSLAttribute) + public void addAttribute(String uri, String localName, String rawName, + String type, String value, boolean XSLAttribute) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#addAttributes(org.xml.sax.Attributes) */ - public void addAttributes(Attributes atts) throws SAXException - { + public void addAttributes(Attributes atts) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String) */ - public void addAttribute(String name, String value) - { + public void addAttribute(String name, String value) { aMethodIsCalled(); } /** * @see ExtendedContentHandler#characters(java.lang.String) */ - public void characters(String chars) throws SAXException - { + public void characters(String chars) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#endElement(java.lang.String) */ - public void endElement(String elemName) throws SAXException - { + public void endElement(String elemName) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#startDocument() */ - public void startDocument() throws SAXException - { + public void startDocument() throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String) */ @@ -285,13 +272,14 @@ { couldThrowSAXException(qName); } + /** * @see ExtendedContentHandler#startElement(java.lang.String) */ - public void startElement(String qName) throws SAXException - { + public void startElement(String qName) throws SAXException { couldThrowSAXException(qName); } + /** * @see ExtendedContentHandler#namespaceAfterStartElement(java.lang.String, java.lang.String) */ @@ -303,68 +291,67 @@ /** * @see ExtendedContentHandler#startPrefixMapping(java.lang.String, java.lang.String, boolean) */ - public boolean startPrefixMapping( - String prefix, - String uri, - boolean shouldFlush) + public boolean startPrefixMapping(String prefix, String uri, + boolean shouldFlush) throws SAXException { couldThrowSAXException(); return false; } + /** * @see ExtendedContentHandler#entityReference(java.lang.String) */ - public void entityReference(String entityName) throws SAXException - { + public void entityReference(String entityName) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedContentHandler#getNamespaceMappings() */ - public NamespaceMappings getNamespaceMappings() - { + public NamespaceMappings getNamespaceMappings() { aMethodIsCalled(); return null; } + /** * @see ExtendedContentHandler#getPrefix(java.lang.String) */ - public String getPrefix(String uri) - { + public String getPrefix(String uri) { aMethodIsCalled(); return null; } + /** * @see ExtendedContentHandler#getNamespaceURI(java.lang.String, boolean) */ - public String getNamespaceURI(String name, boolean isElement) - { + public String getNamespaceURI(String name, boolean isElement) { aMethodIsCalled(); return null; } + /** * @see ExtendedContentHandler#getNamespaceURIFromPrefix(java.lang.String) */ - public String getNamespaceURIFromPrefix(String prefix) - { + public String getNamespaceURIFromPrefix(String prefix) { aMethodIsCalled(); return null; } + /** * @see org.xml.sax.ContentHandler#setDocumentLocator(org.xml.sax.Locator) */ - public void setDocumentLocator(Locator arg0) - { + public void setDocumentLocator(Locator arg0) { aMethodIsCalled(); } + /** * @see org.xml.sax.ContentHandler#endDocument() */ - public void endDocument() throws SAXException - { + public void endDocument() throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#startPrefixMapping(java.lang.String, java.lang.String) */ @@ -373,25 +360,24 @@ { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#endPrefixMapping(java.lang.String) */ - public void endPrefixMapping(String arg0) throws SAXException - { + public void endPrefixMapping(String arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes) */ - public void startElement( - String arg0, - String arg1, - String arg2, - Attributes arg3) + public void startElement(String arg0, String arg1, String arg2, + Attributes arg3) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String) */ @@ -400,13 +386,14 @@ { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#characters(char[], int, int) */ - public void characters(char[] arg0, int arg1, int arg2) throws SAXException - { + public void characters(char[] arg0, int arg1, int arg2) throws SAXException { couldThrowSAXException(arg0, arg1, arg2); } + /** * @see org.xml.sax.ContentHandler#ignorableWhitespace(char[], int, int) */ @@ -415,6 +402,7 @@ { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#processingInstruction(java.lang.String, java.lang.String) */ @@ -423,20 +411,21 @@ { couldThrowSAXException(); } + /** * @see org.xml.sax.ContentHandler#skippedEntity(java.lang.String) */ - public void skippedEntity(String arg0) throws SAXException - { + public void skippedEntity(String arg0) throws SAXException { couldThrowSAXException(); } + /** * @see ExtendedLexicalHandler#comment(java.lang.String) */ - public void comment(String comment) throws SAXException - { + public void comment(String comment) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#startDTD(java.lang.String, java.lang.String, java.lang.String) */ @@ -445,189 +434,187 @@ { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#endDTD() */ - public void endDTD() throws SAXException - { + public void endDTD() throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#startEntity(java.lang.String) */ - public void startEntity(String arg0) throws SAXException - { + public void startEntity(String arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#endEntity(java.lang.String) */ - public void endEntity(String arg0) throws SAXException - { + public void endEntity(String arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#startCDATA() */ - public void startCDATA() throws SAXException - { + public void startCDATA() throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#endCDATA() */ - public void endCDATA() throws SAXException - { + public void endCDATA() throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.LexicalHandler#comment(char[], int, int) */ - public void comment(char[] arg0, int arg1, int arg2) throws SAXException - { + public void comment(char[] arg0, int arg1, int arg2) throws SAXException { couldThrowSAXException(); } + /** * @see XSLOutputAttributes#getDoctypePublic() */ - public String getDoctypePublic() - { + public String getDoctypePublic() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#getDoctypeSystem() */ - public String getDoctypeSystem() - { + public String getDoctypeSystem() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#getEncoding() */ - public String getEncoding() - { - aMethodIsCalled(); - return null; - } - /** - * @see XSLOutputAttributes#getIndent() - */ - public boolean getIndent() - { - aMethodIsCalled(); - return false; - } - /** - * @see XSLOutputAttributes#getIndentAmount() - */ - public int getIndentAmount() - { - aMethodIsCalled(); - return 0; - } - /** - * @see XSLOutputAttributes#getMediaType() - */ - public String getMediaType() - { + public String getEncoding() { aMethodIsCalled(); return null; } + /** - * @see XSLOutputAttributes#getOmitXMLDeclaration() + * @see XSLOutputAttributes#getIndent() */ - public boolean getOmitXMLDeclaration() - { + public boolean getIndent() { aMethodIsCalled(); return false; } + + /** + * @see XSLOutputAttributes#getIndentAmount() + */ + public int getIndentAmount() { + aMethodIsCalled(); + return 0; + } + + /** + * @see XSLOutputAttributes#getMediaType() + */ + public String getMediaType() { + aMethodIsCalled(); + return null; + } + + /** + * @see XSLOutputAttributes#getOmitXMLDeclaration() + */ + public boolean getOmitXMLDeclaration() { + aMethodIsCalled(); + return false; + } + /** * @see XSLOutputAttributes#getStandalone() */ - public String getStandalone() - { + public String getStandalone() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#getVersion() */ - public String getVersion() - { + public String getVersion() { aMethodIsCalled(); return null; } + /** * @see XSLOutputAttributes#setDoctype(java.lang.String, java.lang.String) */ - public void setDoctype(String system, String pub) - { + public void setDoctype(String system, String pub) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setDoctypePublic(java.lang.String) */ - public void setDoctypePublic(String doctype) - { + public void setDoctypePublic(String doctype) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setDoctypeSystem(java.lang.String) */ - public void setDoctypeSystem(String doctype) - { + public void setDoctypeSystem(String doctype) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setEncoding(java.lang.String) */ - public void setEncoding(String encoding) - { + public void setEncoding(String encoding) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setMediaType(java.lang.String) */ - public void setMediaType(String mediatype) - { + public void setMediaType(String mediatype) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setOmitXMLDeclaration(boolean) */ - public void setOmitXMLDeclaration(boolean b) - { + public void setOmitXMLDeclaration(boolean b) { aMethodIsCalled(); } + /** * @see XSLOutputAttributes#setStandalone(java.lang.String) */ - public void setStandalone(String standalone) - { + public void setStandalone(String standalone) { aMethodIsCalled(); } + /** * @see org.xml.sax.ext.DeclHandler#elementDecl(java.lang.String, java.lang.String) */ - public void elementDecl(String arg0, String arg1) throws SAXException - { + public void elementDecl(String arg0, String arg1) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.DeclHandler#attributeDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void attributeDecl( - String arg0, - String arg1, - String arg2, - String arg3, - String arg4) + public void attributeDecl(String arg0, String arg1, String arg2, + String arg3, String arg4) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.DeclHandler#internalEntityDecl(java.lang.String, java.lang.String) */ @@ -636,6 +623,7 @@ { couldThrowSAXException(); } + /** * @see org.xml.sax.ext.DeclHandler#externalEntityDecl(java.lang.String, java.lang.String, java.lang.String) */ @@ -644,32 +632,32 @@ { couldThrowSAXException(); } + /** * @see org.xml.sax.ErrorHandler#warning(org.xml.sax.SAXParseException) */ - public void warning(SAXParseException arg0) throws SAXException - { + public void warning(SAXParseException arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ErrorHandler#error(org.xml.sax.SAXParseException) */ - public void error(SAXParseException arg0) throws SAXException - { + public void error(SAXParseException arg0) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.ErrorHandler#fatalError(org.xml.sax.SAXParseException) */ - public void fatalError(SAXParseException arg0) throws SAXException - { + public void fatalError(SAXParseException arg0) throws SAXException { couldThrowSAXException(); } + /** * @see Serializer#asDOMSerializer() */ - public DOMSerializer asDOMSerializer() throws IOException - { + public DOMSerializer asDOMSerializer() throws IOException { couldThrowIOException(); return null; } @@ -684,8 +672,7 @@ /** * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) */ - public void setSourceLocator(SourceLocator locator) - { + public void setSourceLocator(SourceLocator locator) { aMethodIsCalled(); } @@ -701,30 +688,30 @@ /** * @see ExtendedContentHandler#characters(org.w3c.dom.Node) */ - public void characters(Node node) throws SAXException - { + public void characters(Node node) throws SAXException { couldThrowSAXException(); } /** * @see ExtendedContentHandler#addXSLAttribute(java.lang.String, java.lang.String, java.lang.String) */ - public void addXSLAttribute(String qName, String value, String uri) - { + public void addXSLAttribute(String qName, String value, String uri) { aMethodIsCalled(); } /** * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void addAttribute(String uri, String localName, String rawName, String type, String value) throws SAXException - { + public void addAttribute(String uri, String localName, String rawName, + String type, String value) throws SAXException { couldThrowSAXException(); } + /** * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String) */ - public void notationDecl(String arg0, String arg1, String arg2) throws SAXException + public void notationDecl(String arg0, String arg1, String arg2) + throws SAXException { couldThrowSAXException(); } @@ -732,12 +719,8 @@ /** * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) */ - public void unparsedEntityDecl( - String arg0, - String arg1, - String arg2, - String arg3) - throws SAXException { + public void unparsedEntityDecl(String arg0, String arg1, String arg2, + String arg3) throws SAXException { couldThrowSAXException(); } @@ -746,10 +729,8 @@ */ public void setDTDEntityExpansion(boolean expand) { aMethodIsCalled(); - } - public String getOutputProperty(String name) { aMethodIsCalled(); return null; @@ -762,19 +743,16 @@ public void setOutputProperty(String name, String val) { aMethodIsCalled(); - } public void setOutputPropertyDefault(String name, String val) { aMethodIsCalled(); - } /** * @see org.apache.xml.serializer.Serializer#asDOM3Serializer() */ - public Object asDOM3Serializer() throws IOException - { + public Object asDOM3Serializer() throws IOException { couldThrowIOException(); return null; } diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/SerializerBase.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/SerializerBase.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/SerializerBase.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,15 +1,13 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved. */ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -19,22 +17,18 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: SerializerBase.java,v 1.5 2006/04/14 12:09:19 sunithareddy Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; +import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; +import com.sun.org.apache.xml.internal.serializer.utils.Utils; import java.io.IOException; import java.util.HashMap; import java.util.Set; import java.util.ArrayList; - import javax.xml.transform.OutputKeys; import javax.xml.transform.SourceLocator; import javax.xml.transform.Transformer; - -import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; -import com.sun.org.apache.xml.internal.serializer.utils.Utils; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; @@ -42,7 +36,6 @@ import org.xml.sax.SAXParseException; import org.xml.sax.ext.Locator2; - /** * This class acts as a base class for the XML "serializers" * and the stream serializers. @@ -54,7 +47,6 @@ implements SerializationHandler, SerializerConstants { - /** * To fire off the end element trace event * @param name Name of element @@ -62,8 +54,7 @@ protected void fireEndElem(String name) throws org.xml.sax.SAXException { - if (m_tracer != null) - { + if (m_tracer != null) { flushMyWriter(); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_ENDELEMENT,name, (Attributes)null); } @@ -78,8 +69,7 @@ protected void fireCharEvent(char[] chars, int start, int length) throws org.xml.sax.SAXException { - if (m_tracer != null) - { + if (m_tracer != null) { flushMyWriter(); m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length); } @@ -87,7 +77,7 @@ /** * true if we still need to call startDocumentInternal() - */ + */ protected boolean m_needToCallStartDocument = true; /** True if a trailing "]]>" still needs to be written to be @@ -150,6 +140,7 @@ * Flag to tell if indenting (pretty-printing) is on. */ protected boolean m_doIndent = false; + /** * Amount to indent. */ @@ -186,7 +177,6 @@ protected SourceLocator m_sourceLocator; - /** * The writer to send output to. This field is only used in the ToStream * serializers, but exists here just so that the fireStartDoc() and @@ -227,11 +217,9 @@ * * @see ExtendedLexicalHandler#comment(String) */ - public void comment(String data) throws SAXException - { + public void comment(String data) throws SAXException { final int length = data.length(); - if (length > m_charsBuff.length) - { + if (length > m_charsBuff.length) { m_charsBuff = new char[length * 2 + 1]; } data.getChars(0, length, m_charsBuff, 0); @@ -248,10 +236,7 @@ * XML file, it sometimes generates a NS prefix of the form "ns?" for * an attribute. */ - protected String patchName(String qname) - { - - + protected String patchName(String qname) { final int lastColon = qname.lastIndexOf(':'); if (lastColon > 0) { @@ -259,12 +244,11 @@ final String prefix = qname.substring(0, firstColon); final String localName = qname.substring(lastColon + 1); - // If uri is "" then ignore prefix + // If uri is "" then ignore prefix final String uri = m_prefixMap.lookupNamespace(prefix); if (uri != null && uri.length() == 0) { return localName; - } - else if (firstColon != lastColon) { + } else if (firstColon != lastColon) { return prefix + ':' + localName; } } @@ -277,8 +261,7 @@ * @param qname the qualified name * @return the name, but excluding any prefix and colon. */ - protected static String getLocalName(String qname) - { + protected static String getLocalName(String qname) { final int col = qname.lastIndexOf(':'); return (col > 0) ? qname.substring(col + 1) : qname; } @@ -309,8 +292,7 @@ * during the invocation of the events in this interface. The * application should not attempt to use it at any other time.

*/ - public void setDocumentLocator(Locator locator) - { + public void setDocumentLocator(Locator locator) { m_locator = locator; } @@ -332,20 +314,13 @@ * @param XSLAttribute true if this attribute is coming from an xsl:attriute element * @see ExtendedContentHandler#addAttribute(String, String, String, String, String) */ - public void addAttribute( - String uri, - String localName, - String rawName, - String type, - String value, - boolean XSLAttribute) + public void addAttribute(String uri, String localName, String rawName, + String type, String value, boolean XSLAttribute) throws SAXException { - if (m_elemContext.m_startTagOpen) - { + if (m_elemContext.m_startTagOpen) { addAttributeAlways(uri, localName, rawName, type, value, XSLAttribute); } - } /** @@ -362,51 +337,32 @@ * @return true if the attribute was added, * false if an existing value was replaced. */ - public boolean addAttributeAlways( - String uri, - String localName, - String rawName, - String type, - String value, - boolean XSLAttribute) + public boolean addAttributeAlways(String uri, String localName, String rawName, + String type, String value, boolean XSLAttribute) { boolean was_added; -// final int index = -// (localName == null || uri == null) ? -// m_attributes.getIndex(rawName):m_attributes.getIndex(uri, localName); - int index; -// if (localName == null || uri == null){ -// index = m_attributes.getIndex(rawName); -// } -// else { -// index = m_attributes.getIndex(uri, localName); -// } + int index; - if (localName == null || uri == null || uri.length() == 0) - index = m_attributes.getIndex(rawName); - else { - index = m_attributes.getIndex(uri,localName); - } - if (index >= 0) - { - /* We've seen the attribute before. - * We may have a null uri or localName, but all - * we really want to re-set is the value anyway. - */ - m_attributes.setValue(index,value); - was_added = false; - } - else - { - // the attribute doesn't exist yet, create it - m_attributes.addAttribute(uri, localName, rawName, type, value); - was_added = true; - } - return was_added; - + if (localName == null || uri == null || uri.length() == 0) + index = m_attributes.getIndex(rawName); + else { + index = m_attributes.getIndex(uri,localName); + } + if (index >= 0) { + /* We've seen the attribute before. + * We may have a null uri or localName, but all + * we really want to re-set is the value anyway. + */ + m_attributes.setValue(index,value); + was_added = false; + } else { + // the attribute doesn't exist yet, create it + m_attributes.addAttribute(uri, localName, rawName, type, value); + was_added = true; + } + return was_added; } - /** * Adds the given attribute to the set of collected attributes, * but only if there is a currently open element. @@ -414,16 +370,14 @@ * @param name the attribute's qualified name * @param value the value of the attribute */ - public void addAttribute(String name, final String value) - { - if (m_elemContext.m_startTagOpen) - { + public void addAttribute(String name, final String value) { + if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); final String uri = getNamespaceURI(patchedName, false); addAttributeAlways(uri,localName, patchedName, "CDATA", value, false); - } + } } /** @@ -434,15 +388,13 @@ * @param value the value of the attribute * @param uri the URI that the prefix of the name points to */ - public void addXSLAttribute(String name, final String value, final String uri) - { - if (m_elemContext.m_startTagOpen) - { + public void addXSLAttribute(String name, final String value, final String uri) { + if (m_elemContext.m_startTagOpen) { final String patchedName = patchName(name); final String localName = getLocalName(patchedName); addAttributeAlways(uri,localName, patchedName, "CDATA", value, true); - } + } } /** @@ -451,12 +403,9 @@ * is currently open. * @param atts List of attributes to add to this list */ - public void addAttributes(Attributes atts) throws SAXException - { - + public void addAttributes(Attributes atts) throws SAXException { int nAtts = atts.getLength(); - for (int i = 0; i < nAtts; i++) - { + for (int i = 0; i < nAtts; i++) { String uri = atts.getURI(i); if (null == uri) @@ -469,7 +418,6 @@ atts.getType(i), atts.getValue(i), false); - } } @@ -482,8 +430,7 @@ * or null if the serializer is not SAX 2 capable * @throws IOException An I/O exception occured */ - public ContentHandler asContentHandler() throws IOException - { + public ContentHandler asContentHandler() throws IOException { return this; } @@ -494,8 +441,7 @@ * @throws org.xml.sax.SAXException The application may raise an exception. * @see #startEntity */ - public void endEntity(String name) throws org.xml.sax.SAXException - { + public void endEntity(String name) throws org.xml.sax.SAXException { if (name.equals("[dtd]")) m_inExternalDTD = false; m_inEntityRef = false; @@ -509,27 +455,24 @@ * ToStream serializers, not ToSAXHandler serializers. * @see ToStream */ - public void close() - { + public void close() { // do nothing (base behavior) } /** * Initialize global variables */ - protected void initCDATA() - { + protected void initCDATA() { // CDATA stack - // _cdataStack = new Stack(); - // _cdataStack.push(new Integer(-1)); // push dummy value + // _cdataStack = new Stack(); + // _cdataStack.push(new Integer(-1)); // push dummy value } /** * Returns the character encoding to be used in the output document. * @return the character encoding to be used in the output document. */ - public String getEncoding() - { + public String getEncoding() { return getOutputProperty(OutputKeys.ENCODING); } @@ -537,8 +480,7 @@ * Sets the character encoding coming from the xsl:output encoding stylesheet attribute. * @param m_encoding the character encoding */ - public void setEncoding(String encoding) - { + public void setEncoding(String encoding) { setOutputProperty(OutputKeys.ENCODING,encoding); } @@ -547,19 +489,16 @@ * @param b true if the XML declaration is to be omitted from the output * document. */ - public void setOmitXMLDeclaration(boolean b) - { + public void setOmitXMLDeclaration(boolean b) { String val = b ? "yes":"no"; setOutputProperty(OutputKeys.OMIT_XML_DECLARATION,val); } - /** * @return true if the XML declaration is to be omitted from the output * document. */ - public boolean getOmitXMLDeclaration() - { + public boolean getOmitXMLDeclaration() { return m_shouldNotWriteXMLHeader; } @@ -625,8 +564,7 @@ * document. This method remembers if the value was explicitly set using * this method, verses if the value is the default value. */ - public void setStandalone(String standalone) - { + public void setStandalone(String standalone) { setOutputProperty(OutputKeys.STANDALONE, standalone); } @@ -635,8 +573,7 @@ * default or explicite setting. * @param standalone "yes" | "no" */ - protected void setStandaloneInternal(String standalone) - { + protected void setStandaloneInternal(String standalone) { if ("yes".equals(standalone)) m_standalone = "yes"; else @@ -650,8 +587,7 @@ * be included in the output document. * @see XSLOutputAttributes#getStandalone() */ - public String getStandalone() - { + public String getStandalone() { return m_standalone; } @@ -659,8 +595,7 @@ * @return true if the output document should be indented to visually * indicate its structure. */ - public boolean getIndent() - { + public boolean getIndent() { return m_doIndent; } /** @@ -669,8 +604,7 @@ * @return the mediatype the media-type or MIME type associated with the * output document. */ - public String getMediaType() - { + public String getMediaType() { return m_mediatype; } @@ -678,8 +612,7 @@ * Gets the version of the output format. * @return the version of the output format. */ - public String getVersion() - { + public String getVersion() { return m_version; } @@ -688,8 +621,7 @@ * @param version the version of the output format. * @see SerializationHandler#setVersion(String) */ - public void setVersion(String version) - { + public void setVersion(String version) { setOutputProperty(OutputKeys.VERSION, version); } @@ -700,16 +632,14 @@ * @see javax.xml.transform.OutputKeys#MEDIA_TYPE * @see SerializationHandler#setMediaType(String) */ - public void setMediaType(String mediaType) - { + public void setMediaType(String mediaType) { setOutputProperty(OutputKeys.MEDIA_TYPE,mediaType); } /** * @return the number of spaces to indent for each indentation level. */ - public int getIndentAmount() - { + public int getIndentAmount() { return m_indentAmount; } @@ -717,8 +647,7 @@ * Sets the indentation amount. * @param m_indentAmount The m_indentAmount to set */ - public void setIndentAmount(int m_indentAmount) - { + public void setIndentAmount(int m_indentAmount) { this.m_indentAmount = m_indentAmount; } @@ -729,8 +658,7 @@ * visually indicate its structure. * @see XSLOutputAttributes#setIndent(boolean) */ - public void setIndent(boolean doIndent) - { + public void setIndent(boolean doIndent) { String val = doIndent ? "yes":"no"; setOutputProperty(OutputKeys.INDENT,val); } @@ -740,8 +668,7 @@ * @param isStandalone true if the ORACLE_IS_STANDALONE is set to yes * @see OutputPropertiesFactory ORACLE_IS_STANDALONE */ - public void setIsStandalone(boolean isStandalone) - { + public void setIsStandalone(boolean isStandalone) { m_isStandalone = isStandalone; } @@ -772,8 +699,7 @@ * @throws IOException An I/O exception occured * @see Serializer#asDOMSerializer() */ - public DOMSerializer asDOMSerializer() throws IOException - { + public DOMSerializer asDOMSerializer() throws IOException { return this; } @@ -785,8 +711,7 @@ * * @return true if strings are equal. */ - private static final boolean subPartMatch(String p, String t) - { + private static final boolean subPartMatch(String p, String t) { return (p == t) || ((null != p) && (p.equals(t))); } @@ -799,8 +724,7 @@ * @return returns the prefix of the qualified name, * or null if there is no prefix. */ - protected static final String getPrefixPart(String qname) - { + protected static final String getPrefixPart(String qname) { final int col = qname.indexOf(':'); return (col > 0) ? qname.substring(0, col) : null; //return (col > 0) ? qname.substring(0,col) : ""; @@ -811,8 +735,7 @@ * @return the current namespace mappings (prefix/uri) * @see ExtendedContentHandler#getNamespaceMappings() */ - public NamespaceMappings getNamespaceMappings() - { + public NamespaceMappings getNamespaceMappings() { return m_prefixMap; } @@ -822,8 +745,7 @@ * @return a prefix pointing to the given URI (if any). * @see ExtendedContentHandler#getPrefix(String) */ - public String getPrefix(String namespaceURI) - { + public String getPrefix(String namespaceURI) { String prefix = m_prefixMap.lookupPrefix(namespaceURI); return prefix; } @@ -836,19 +758,15 @@ * an element. * @return returns the namespace URI associated with the qualified name. */ - public String getNamespaceURI(String qname, boolean isElement) - { + public String getNamespaceURI(String qname, boolean isElement) { String uri = EMPTYSTRING; int col = qname.lastIndexOf(':'); final String prefix = (col > 0) ? qname.substring(0, col) : EMPTYSTRING; - if (!EMPTYSTRING.equals(prefix) || isElement) - { - if (m_prefixMap != null) - { + if (!EMPTYSTRING.equals(prefix) || isElement) { + if (m_prefixMap != null) { uri = m_prefixMap.lookupNamespace(prefix); - if (uri == null && !prefix.equals(XMLNS_PREFIX)) - { + if (uri == null && !prefix.equals(XMLNS_PREFIX)) { throw new RuntimeException( Utils.messages.createMessage( MsgKey.ER_NAMESPACE_PREFIX, @@ -866,8 +784,7 @@ * @return the namespace URI currently associated with the * prefix, null if the prefix is undefined. */ - public String getNamespaceURIFromPrefix(String prefix) - { + public String getNamespaceURIFromPrefix(String prefix) { String uri = null; if (m_prefixMap != null) uri = m_prefixMap.lookupNamespace(prefix); @@ -881,16 +798,14 @@ * * @throws org.xml.sax.SAXException */ - public void entityReference(String name) throws org.xml.sax.SAXException - { - + public void entityReference(String name) throws org.xml.sax.SAXException { flushPending(); startEntity(name); endEntity(name); if (m_tracer != null) - fireEntityReference(name); + fireEntityReference(name); } /** @@ -898,8 +813,7 @@ * @param t the transformer associated with this serializer. * @see SerializationHandler#setTransformer(Transformer) */ - public void setTransformer(Transformer t) - { + public void setTransformer(Transformer t) { m_transformer = t; // If this transformer object implements the SerializerTrace interface @@ -912,13 +826,13 @@ m_tracer = null; } } + /** * Gets the transformer associated with this serializer * @return returns the transformer associated with this serializer. * @see SerializationHandler#getTransformer() */ - public Transformer getTransformer() - { + public Transformer getTransformer() { return m_transformer; } @@ -933,11 +847,9 @@ { flushPending(); String data = node.getNodeValue(); - if (data != null) - { + if (data != null) { final int length = data.length(); - if (length > m_charsBuff.length) - { + if (length > m_charsBuff.length) { m_charsBuff = new char[length * 2 + 1]; } data.getChars(0, length, m_charsBuff, 0); @@ -956,16 +868,13 @@ * @see org.xml.sax.ErrorHandler#fatalError(SAXParseException) */ public void fatalError(SAXParseException exc) throws SAXException { - - m_elemContext.m_startTagOpen = false; - + m_elemContext.m_startTagOpen = false; } /** * @see org.xml.sax.ErrorHandler#warning(SAXParseException) */ - public void warning(SAXParseException exc) throws SAXException - { + public void warning(SAXParseException exc) throws SAXException { } /** @@ -983,20 +892,6 @@ } /** - * Report the characters event - * @param chars content of characters - * @param start starting index of characters to output - * @param length number of characters to output - */ -// protected void fireCharEvent(char[] chars, int start, int length) -// throws org.xml.sax.SAXException -// { -// if (m_tracer != null) -// m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CHARACTERS, chars, start,length); -// } -// - - /** * This method is only used internally when flushing the writer from the * various fire...() trace events. Due to the writer being wrapped with * SerializerTraceWriter it may cause the flush of these trace events: @@ -1005,20 +900,15 @@ * which trace the output written to the output stream. * */ - private void flushMyWriter() - { - if (m_writer != null) - { - try - { + private void flushMyWriter() { + if (m_writer != null) { + try { m_writer.flush(); - } - catch(IOException ioe) - { - + } catch(IOException ioe) { } } } + /** * Report the CDATA trace event * @param chars content of CDATA @@ -1028,10 +918,9 @@ protected void fireCDATAEvent(char[] chars, int start, int length) throws org.xml.sax.SAXException { - if (m_tracer != null) - { + if (m_tracer != null) { flushMyWriter(); - m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CDATA, chars, start,length); + m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_CDATA, chars, start,length); } } @@ -1044,10 +933,9 @@ protected void fireCommentEvent(char[] chars, int start, int length) throws org.xml.sax.SAXException { - if (m_tracer != null) - { + if (m_tracer != null) { flushMyWriter(); - m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT, new String(chars, start, length)); + m_tracer.fireGenerateEvent(SerializerTrace.EVENTTYPE_COMMENT, new String(chars, start, length)); } } @@ -1221,12 +1109,10 @@ * * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) */ - public void setSourceLocator(SourceLocator locator) - { + public void setSourceLocator(SourceLocator locator) { m_sourceLocator = locator; } - /** * Used only by TransformerSnapshotImpl to restore the serialization * to a previous state. @@ -1237,8 +1123,7 @@ m_prefixMap = mappings; } - public boolean reset() - { + public boolean reset() { resetSerializerBase(); return true; } @@ -1247,8 +1132,7 @@ * Reset all of the fields owned by SerializerBase * */ - private void resetSerializerBase() - { + private void resetSerializerBase() { this.m_attributes.clear(); this.m_StringOfCDATASections = null; this.m_elemContext = new ElemContext(); @@ -1280,13 +1164,12 @@ * * This concept is made clear in the XSLT 2.0 draft. */ - final boolean inTemporaryOutputState() - { + final boolean inTemporaryOutputState() { /* This is a hack. We should really be letting the serializer know * that it is in temporary output state with an explicit call, but * from a pragmatic point of view (for now anyways) having no output - * encoding at all, not even the default UTF-8 indicates that the serializer - * is being used for temporary RTF. + * encoding at all, not even the default UTF-8 indicates that the + * serializer is being used for temporary RTF. */ return (getEncoding() == null); @@ -1295,36 +1178,38 @@ /** * This method adds an attribute the the current element, * but should not be used for an xsl:attribute child. - * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String) + * @see ExtendedContentHandler#addAttribute(java.lang.String, java.lang.String, + * java.lang.String, java.lang.String, java.lang.String) */ - public void addAttribute(String uri, String localName, String rawName, String type, String value) throws SAXException + public void addAttribute(String uri, String localName, String rawName, + String type, String value) throws SAXException { - if (m_elemContext.m_startTagOpen) - { + if (m_elemContext.m_startTagOpen) { addAttributeAlways(uri, localName, rawName, type, value, false); } } /** - * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, java.lang.String, java.lang.String) + * @see org.xml.sax.DTDHandler#notationDecl(java.lang.String, + * java.lang.String, java.lang.String) */ public void notationDecl(String arg0, String arg1, String arg2) - throws SAXException { + throws SAXException + { // This method just provides a definition to satisfy the interface - // A particular sub-class of SerializerBase provides the implementation (if desired) + // A particular sub-class of SerializerBase provides the implementation + // (if desired) } /** - * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, java.lang.String, java.lang.String, java.lang.String) + * @see org.xml.sax.DTDHandler#unparsedEntityDecl(java.lang.String, + * java.lang.String, java.lang.String, java.lang.String) */ - public void unparsedEntityDecl( - String arg0, - String arg1, - String arg2, - String arg3) - throws SAXException { + public void unparsedEntityDecl(String arg0, String arg1, String arg2, + String arg3) throws SAXException { // This method just provides a definition to satisfy the interface - // A particular sub-class of SerializerBase provides the implementation (if desired) + // A particular sub-class of SerializerBase provides the implementation + // (if desired) } /** @@ -1606,6 +1491,7 @@ * map will have what that attribute maps to. */ private HashMap m_OutputProps; + /** * A mapping of keys to default values, for example if * the default value of the encoding is "UTF-8" then this @@ -1616,6 +1502,7 @@ Set getOutputPropDefaultKeys() { return m_OutputPropsDefault.keySet(); } + Set getOutputPropKeys() { return m_OutputProps.keySet(); } @@ -1634,6 +1521,7 @@ return val; } + /** * * @param name The name of the property, e.g. "{http://myprop}indent-tabs" or "indent". diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToSAXHandler.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToSAXHandler.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToSAXHandler.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,13 +1,13 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. */ /* - * Copyright 2001-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -17,13 +17,10 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: ToSAXHandler.java,v 1.2.4.1 2005/09/22 11:03:15 pvedula Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import java.util.ArrayList; - import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.ErrorHandler; @@ -39,23 +36,16 @@ * * @xsl.usage internal */ -public abstract class ToSAXHandler extends SerializerBase -{ - public ToSAXHandler() - { - } +public abstract class ToSAXHandler extends SerializerBase { + public ToSAXHandler() { } - public ToSAXHandler( - ContentHandler hdlr, - LexicalHandler lex, - String encoding) - { + public ToSAXHandler(ContentHandler hdlr, LexicalHandler lex, String encoding) { setContentHandler(hdlr); setLexHandler(lex); setEncoding(encoding); } - public ToSAXHandler(ContentHandler handler, String encoding) - { + + public ToSAXHandler(ContentHandler handler, String encoding) { setContentHandler(handler); setEncoding(encoding); } @@ -90,16 +80,14 @@ /** * Pass callback to the SAX Handler */ - protected void startDocumentInternal() throws SAXException - { - if (m_needToCallStartDocument) - { + protected void startDocumentInternal() throws SAXException { + if (m_needToCallStartDocument) { super.startDocumentInternal(); - m_saxHandler.startDocument(); m_needToCallStartDocument = false; } } + /** * Do nothing. * @see org.xml.sax.ext.LexicalHandler#startDTD(String, String, String) @@ -113,20 +101,20 @@ /** * Receive notification of character data. * - * @param characters The string of characters to process. + * @param chars The string of characters to process. * * @throws org.xml.sax.SAXException * * @see ExtendedContentHandler#characters(String) */ - public void characters(String characters) throws SAXException - { - final int len = characters.length(); - if (len > m_charsBuff.length) - { - m_charsBuff = new char[len*2 + 1]; + public void characters(String chars) throws SAXException { + final int len = (chars == null) ? 0 : chars.length(); + if (len > m_charsBuff.length) { + m_charsBuff = new char[len * 2 + 1]; } - characters.getChars(0,len, m_charsBuff, 0); + if (len > 0) { + chars.getChars(0, len, m_charsBuff, 0); + } characters(m_charsBuff, 0, len); } @@ -135,16 +123,13 @@ * * @see ExtendedLexicalHandler#comment(String) */ - public void comment(String comment) throws SAXException - { + public void comment(String comment) throws SAXException { flushPending(); // Ignore if a lexical handler has not been set - if (m_lexHandler != null) - { + if (m_lexHandler != null) { final int len = comment.length(); - if (len > m_charsBuff.length) - { + if (len > m_charsBuff.length) { m_charsBuff = new char[len*2 + 1]; } comment.getChars(0,len, m_charsBuff, 0); @@ -153,7 +138,6 @@ if (m_tracer != null) super.fireCommentEvent(m_charsBuff, 0, len); } - } /** @@ -167,12 +151,10 @@ // Redefined in SAXXMLOutput } - protected void closeStartTag() throws SAXException - { + protected void closeStartTag() throws SAXException { } - protected void closeCDATA() throws SAXException - { + protected void closeCDATA() throws SAXException { // Redefined in SAXXMLOutput } @@ -191,12 +173,8 @@ * * @see org.xml.sax.ContentHandler#startElement(String,String,String,Attributes) */ - public void startElement( - String arg0, - String arg1, - String arg2, - Attributes arg3) - throws SAXException + public void startElement(String arg0, String arg1, String arg2, + Attributes arg3) throws SAXException { if (m_state != null) { m_state.resetState(getTransformer()); @@ -211,8 +189,7 @@ * Sets the LexicalHandler. * @param _lexHandler The LexicalHandler to set */ - public void setLexHandler(LexicalHandler _lexHandler) - { + public void setLexHandler(LexicalHandler _lexHandler) { this.m_lexHandler = _lexHandler; } @@ -220,11 +197,9 @@ * Sets the SAX ContentHandler. * @param _saxHandler The ContentHandler to set */ - public void setContentHandler(ContentHandler _saxHandler) - { + public void setContentHandler(ContentHandler _saxHandler) { this.m_saxHandler = _saxHandler; - if (m_lexHandler == null && _saxHandler instanceof LexicalHandler) - { + if (m_lexHandler == null && _saxHandler instanceof LexicalHandler) { // we are not overwriting an existing LexicalHandler, and _saxHandler // is also implements LexicalHandler, so lets use it m_lexHandler = (LexicalHandler) _saxHandler; @@ -236,8 +211,7 @@ * stream serializers. * @see SerializationHandler#setCdataSectionElements(java.util.ArrayList) */ - public void setCdataSectionElements(ArrayList URI_and_localNames) - { + public void setCdataSectionElements(ArrayList URI_and_localNames) { // do nothing } @@ -247,8 +221,7 @@ * @param doOutputNSAttr whether or not namespace declarations * should appear as attributes */ - public void setShouldOutputNSAttr(boolean doOutputNSAttr) - { + public void setShouldOutputNSAttr(boolean doOutputNSAttr) { m_shouldGenerateNSAttribute = doOutputNSAttr; } @@ -258,8 +231,7 @@ * also be mirrored with self generated additional attributes of elements * that declare the namespace, for example the attribute xmlns:prefix1="uri1" */ - boolean getShouldOutputNSAttr() - { + boolean getShouldOutputNSAttr() { return m_shouldGenerateNSAttribute; } @@ -267,27 +239,21 @@ * This method flushes any pending events, which can be startDocument() * closing the opening tag of an element, or closing an open CDATA section. */ - public void flushPending() throws SAXException - { - - if (m_needToCallStartDocument) - { + public void flushPending() throws SAXException { + if (m_needToCallStartDocument) { startDocumentInternal(); m_needToCallStartDocument = false; } - if (m_elemContext.m_startTagOpen) - { + if (m_elemContext.m_startTagOpen) { closeStartTag(); m_elemContext.m_startTagOpen = false; } - if (m_cdataTagOpen) - { + if (m_cdataTagOpen) { closeCDATA(); m_cdataTagOpen = false; } - } /** @@ -350,8 +316,7 @@ throws org.xml.sax.SAXException { // remember the current node - if (m_state != null) - { + if (m_state != null) { m_state.setCurrentNode(node); } @@ -392,12 +357,10 @@ */ public void warning(SAXParseException exc) throws SAXException { super.warning(exc); - if (m_saxHandler instanceof ErrorHandler) ((ErrorHandler)m_saxHandler).warning(exc); } - /** * Try's to reset the super class and reset this class for * re-use, so that you don't need to create a new serializer @@ -406,11 +369,9 @@ * @return true if the class was successfuly reset. * @see Serializer#reset() */ - public boolean reset() - { + public boolean reset() { boolean wasReset = false; - if (super.reset()) - { + if (super.reset()) { resetToSAXHandler(); wasReset = true; } @@ -421,8 +382,7 @@ * Reset all of the fields owned by ToSAXHandler class * */ - private void resetToSAXHandler() - { + private void resetToSAXHandler() { this.m_lexHandler = null; this.m_saxHandler = null; this.m_state = null; diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,15 +1,13 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved. */ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -19,12 +17,13 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: ToStream.java,v 1.4 2005/11/10 06:43:26 suresh_emailid Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import com.sun.org.apache.xalan.internal.utils.SecuritySupport; +import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; +import com.sun.org.apache.xml.internal.serializer.utils.Utils; +import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; @@ -36,30 +35,22 @@ import java.util.Set; import java.util.StringTokenizer; import java.util.ArrayList; - import javax.xml.transform.ErrorListener; import javax.xml.transform.OutputKeys; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; - -import com.sun.org.apache.xml.internal.serializer.utils.MsgKey; -import com.sun.org.apache.xml.internal.serializer.utils.Utils; -import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException; import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.SAXException; -//import com.sun.media.sound.IESecurity; - /** * This abstract class is a base class for other stream * serializers (xml, html, text ...) that write output to a stream. * * @xsl.usage internal */ -abstract public class ToStream extends SerializerBase -{ +abstract public class ToStream extends SerializerBase { private static final String COMMENT_BEGIN = ""; @@ -67,7 +58,6 @@ /** Stack to keep track of disabling output escaping. */ protected BoolStack m_disableOutputEscapingStates = new BoolStack(); - /** * The encoding information associated with this serializer. * Although initially there is no encoding, @@ -87,21 +77,17 @@ */ java.lang.reflect.Method m_canConvertMeth; - - /** * Boolean that tells if we already tried to get the converter. */ boolean m_triedToGetConverter = false; - /** * Opaque reference to the sun.io.CharToByteConverter for this * encoding. */ Object m_charToByteConverter = null; - /** * Stack to keep track of whether or not we need to * preserve whitespace. @@ -139,7 +125,6 @@ */ protected int m_maxCharacter = Encodings.getLastPrintable(); - /** * The system line separator for writing out line breaks. * The default value is from the system property, @@ -188,8 +173,8 @@ protected boolean m_inDoctype = false; /** - * Flag to quickly tell if the encoding is UTF8. - */ + * Flag to quickly tell if the encoding is UTF8. + */ boolean m_isUTF8 = false; /** @@ -203,29 +188,23 @@ */ private boolean m_expandDTDEntities = true; - /** * Default constructor */ - public ToStream() - { - } + public ToStream() { } /** * This helper method to writes out "]]>" when closing a CDATA section. * * @throws org.xml.sax.SAXException */ - protected void closeCDATA() throws org.xml.sax.SAXException - { - try - { + protected void closeCDATA() throws org.xml.sax.SAXException { + try { m_writer.write(CDATA_DELIMITER_CLOSE); // write out a CDATA section closing "]]>" m_cdataTagOpen = false; // Remember that we have done so. } - catch (IOException e) - { + catch (IOException e) { throw new SAXException(e); } } @@ -237,18 +216,11 @@ * @param node Node to serialize. * @throws IOException An I/O exception occured while serializing */ - public void serialize(Node node) throws IOException - { - - try - { - TreeWalker walker = - new TreeWalker(this); - + public void serialize(Node node) throws IOException { + try { + TreeWalker walker = new TreeWalker(this); walker.traverse(node); - } - catch (org.xml.sax.SAXException se) - { + } catch (org.xml.sax.SAXException se) { throw new WrappedRuntimeException(se); } } @@ -260,8 +232,7 @@ * * NEEDSDOC ($objectName$) @return */ - static final boolean isUTF16Surrogate(char c) - { + static final boolean isUTF16Surrogate(char c) { return (c & 0xFC00) == 0xD800; } @@ -275,49 +246,40 @@ * * @throws org.xml.sax.SAXException */ - protected final void flushWriter() throws org.xml.sax.SAXException - { - final java.io.Writer writer = m_writer; - if (null != writer) - { - try - { - if (writer instanceof WriterToUTF8Buffered) - { + protected final void flushWriter() throws org.xml.sax.SAXException { + final Writer writer = m_writer; + if (null != writer) { + try { + if (writer instanceof WriterToUTF8Buffered) { if (m_shouldFlush) - ((WriterToUTF8Buffered) writer).flush(); + ((WriterToUTF8Buffered)writer).flush(); else - ((WriterToUTF8Buffered) writer).flushBuffer(); + ((WriterToUTF8Buffered)writer).flushBuffer(); } - if (writer instanceof WriterToASCI) - { + if (writer instanceof WriterToASCI) { if (m_shouldFlush) writer.flush(); - } - else - { + } else { // Flush always. // Not a great thing if the writer was created // by this class, but don't have a choice. writer.flush(); } - } - catch (IOException ioe) - { + } catch (IOException ioe) { throw new org.xml.sax.SAXException(ioe); } } } OutputStream m_outputStream; + /** * Get the output stream where the events will be serialized to. * * @return reference to the result stream, or null of only a writer was * set. */ - public OutputStream getOutputStream() - { + public OutputStream getOutputStream() { return m_outputStream; } @@ -341,9 +303,8 @@ // Do not inline external DTD if (m_inExternalDTD) return; - try - { - final java.io.Writer writer = m_writer; + try { + final Writer writer = m_writer; DTDprolog(); writer.write(""); else @@ -2598,15 +2542,12 @@ * OutputProperties. Eventually this method should go away and a call * to setCdataSectionElements(ArrayList v) should be made directly. */ - private void setCdataSectionElements(String key, Properties props) - { - + private void setCdataSectionElements(String key, Properties props) { String s = props.getProperty(key); - if (null != s) - { + if (null != s) { // ArrayList of URI/LocalName pairs - ArrayList v = new ArrayList<>(); + ArrayList al = new ArrayList<>(); int l = s.length(); boolean inCurly = false; StringBuilder buf = new StringBuilder(); @@ -2624,7 +2565,7 @@ { if (buf.length() > 0) { - addCdataSectionElement(buf.toString(), v); + addCdataSectionElement(buf.toString(), al); buf.setLength(0); } continue; @@ -2640,11 +2581,11 @@ if (buf.length() > 0) { - addCdataSectionElement(buf.toString(), v); + addCdataSectionElement(buf.toString(), al); buf.setLength(0); } // call the official, public method to set the collected names - setCdataSectionElements(v); + setCdataSectionElements(al); } } @@ -2656,25 +2597,19 @@ * * @return a QName object */ - private void addCdataSectionElement(String URI_and_localName, ArrayList v) - { - - StringTokenizer tokenizer = - new StringTokenizer(URI_and_localName, "{}", false); + private void addCdataSectionElement(String URI_and_localName, ArrayList al) { + StringTokenizer tokenizer = new StringTokenizer(URI_and_localName, "{}", false); String s1 = tokenizer.nextToken(); String s2 = tokenizer.hasMoreTokens() ? tokenizer.nextToken() : null; - if (null == s2) - { + if (null == s2) { // add null URI and the local name - v.add(null); - v.add(s1); - } - else - { + al.add(null); + al.add(s1); + } else { // add URI, then local name - v.add(s1); - v.add(s2); + al.add(s1); + al.add(s2); } } @@ -2685,25 +2620,20 @@ * * @param URI_and_localNames an ArrayList of pairs of Strings (URI/local) */ - public void setCdataSectionElements(ArrayList URI_and_localNames) - { + public void setCdataSectionElements(ArrayList URI_and_localNames) { // convert to the new way. - if (URI_and_localNames != null) - { + if (URI_and_localNames != null) { final int len = URI_and_localNames.size() - 1; - if (len > 0) - { + if (len > 0) { final StringBuilder sb = new StringBuilder(); - for (int i = 0; i < len; i += 2) - { + for (int i = 0; i < len; i += 2) { // whitspace separated "{uri1}local1 {uri2}local2 ..." if (i != 0) sb.append(' '); final String uri = (String) URI_and_localNames.get(i); final String localName = (String) URI_and_localNames.get(i + 1); - if (uri != null) - { + if (uri != null) { // If there is no URI don't put this in, just the localName then. sb.append('{'); sb.append(uri); @@ -3007,25 +2937,19 @@ * exist. This method should be called everytime an attribute is added, * or when an attribute value is changed, or an element is created. */ - - protected void firePseudoAttributes() - { - if (m_tracer != null) - { - try - { + protected void firePseudoAttributes() { + if (m_tracer != null) { + try { // flush out the " 0) - { + if (nAttrs > 0) { // make a writer that internally appends to the same // StringBuffer - java.io.Writer writer = - new ToStream.WritertoStringBuffer(sb); + Writer writer = new ToStream.WritertoStringBuffer(sb); processAttributes(writer, nAttrs); // Don't clear the attributes! @@ -3042,13 +2966,9 @@ ch, 0, ch.length); - } - catch (IOException ioe) - { + } catch (IOException ioe) { // ignore ? - } - catch (SAXException se) - { + } catch (SAXException se) { // ignore ? } } @@ -3060,41 +2980,35 @@ * In this manner trace events, and the real writing of attributes will use * the same code. */ - private class WritertoStringBuffer extends java.io.Writer - { + private class WritertoStringBuffer extends Writer { final private StringBuffer m_stringbuf; + /** * @see java.io.Writer#write(char[], int, int) */ - WritertoStringBuffer(StringBuffer sb) - { + WritertoStringBuffer(StringBuffer sb) { m_stringbuf = sb; } - public void write(char[] arg0, int arg1, int arg2) throws IOException - { + public void write(char[] arg0, int arg1, int arg2) throws IOException { m_stringbuf.append(arg0, arg1, arg2); } + /** * @see java.io.Writer#flush() */ - public void flush() throws IOException - { - } + public void flush() throws IOException {} + /** * @see java.io.Writer#close() */ - public void close() throws IOException - { - } - - public void write(int i) - { + public void close() throws IOException {} + + public void write(int i) { m_stringbuf.append((char) i); } - public void write(String s) - { + public void write(String s) { m_stringbuf.append(s); } } @@ -3104,12 +3018,11 @@ */ public void setTransformer(Transformer transformer) { super.setTransformer(transformer); - if (m_tracer != null - && !(m_writer instanceof SerializerTraceWriter) ) + if (m_tracer != null && !(m_writer instanceof SerializerTraceWriter)) { m_writer = new SerializerTraceWriter(m_writer, m_tracer); - - + } } + /** * Try's to reset the super class and reset this class for * re-use, so that you don't need to create a new serializer @@ -3117,11 +3030,9 @@ * * @return true if the class was successfuly reset. */ - public boolean reset() - { + public boolean reset() { boolean wasReset = false; - if (super.reset()) - { + if (super.reset()) { resetToStream(); wasReset = true; } @@ -3132,14 +3043,12 @@ * Reset all of the fields owned by ToStream class * */ - private void resetToStream() - { + private void resetToStream() { this.m_cdataStartCalled = false; /* The stream is being reset. It is one of * ToXMLStream, ToHTMLStream ... and this type can't be changed * so neither should m_charInfo which is associated with the * type of Stream. Just leave m_charInfo as-is for the next re-use. - * */ // this.m_charInfo = null; // don't set to null @@ -3183,173 +3092,150 @@ * * @xsl.usage internal */ - static final class BoolStack - { - - /** Array of boolean values */ - private boolean m_values[]; - - /** Array size allocated */ - private int m_allocatedSize; - - /** Index into the array of booleans */ - private int m_index; - - /** - * Default constructor. Note that the default - * block size is very small, for small lists. - */ - public BoolStack() - { - this(32); - } - - /** - * Construct a IntVector, using the given block size. - * - * @param size array size to allocate - */ - public BoolStack(int size) - { - - m_allocatedSize = size; - m_values = new boolean[size]; - m_index = -1; - } - - /** - * Get the length of the list. - * - * @return Current length of the list - */ - public final int size() - { - return m_index + 1; - } - - /** - * Clears the stack. - * - */ - public final void clear() - { - m_index = -1; - } - - /** - * Pushes an item onto the top of this stack. - * - * - * @param val the boolean to be pushed onto this stack. - * @return the item argument. - */ - public final boolean push(boolean val) - { - - if (m_index == m_allocatedSize - 1) - grow(); - - return (m_values[++m_index] = val); - } - - /** - * Removes the object at the top of this stack and returns that - * object as the value of this function. - * - * @return The object at the top of this stack. - * @throws EmptyStackException if this stack is empty. - */ - public final boolean pop() - { - return m_values[m_index--]; - } - - /** - * Removes the object at the top of this stack and returns the - * next object at the top as the value of this function. - * - * - * @return Next object to the top or false if none there - */ - public final boolean popAndTop() - { - - m_index--; - - return (m_index >= 0) ? m_values[m_index] : false; - } - - /** - * Set the item at the top of this stack - * - * - * @param b Object to set at the top of this stack - */ - public final void setTop(boolean b) - { - m_values[m_index] = b; - } - - /** - * Looks at the object at the top of this stack without removing it - * from the stack. - * - * @return the object at the top of this stack. - * @throws EmptyStackException if this stack is empty. - */ - public final boolean peek() - { - return m_values[m_index]; - } - - /** - * Looks at the object at the top of this stack without removing it - * from the stack. If the stack is empty, it returns false. - * - * @return the object at the top of this stack. - */ - public final boolean peekOrFalse() - { - return (m_index > -1) ? m_values[m_index] : false; - } - - /** - * Looks at the object at the top of this stack without removing it - * from the stack. If the stack is empty, it returns true. - * - * @return the object at the top of this stack. - */ - public final boolean peekOrTrue() - { - return (m_index > -1) ? m_values[m_index] : true; - } - - /** - * Tests if this stack is empty. - * - * @return true if this stack is empty; - * false otherwise. - */ - public boolean isEmpty() - { - return (m_index == -1); - } - - /** - * Grows the size of the stack - * - */ - private void grow() - { - - m_allocatedSize *= 2; - - boolean newVector[] = new boolean[m_allocatedSize]; - - System.arraycopy(m_values, 0, newVector, 0, m_index + 1); - - m_values = newVector; - } + static final class BoolStack { + /** Array of boolean values */ + private boolean m_values[]; + + /** Array size allocated */ + private int m_allocatedSize; + + /** Index into the array of booleans */ + private int m_index; + + /** + * Default constructor. Note that the default + * block size is very small, for small lists. + */ + public BoolStack() { + this(32); + } + + /** + * Construct a IntVector, using the given block size. + * + * @param size array size to allocate + */ + public BoolStack(int size) { + m_allocatedSize = size; + m_values = new boolean[size]; + m_index = -1; + } + + /** + * Get the length of the list. + * + * @return Current length of the list + */ + public final int size() { + return m_index + 1; + } + + /** + * Clears the stack. + * + */ + public final void clear() { + m_index = -1; + } + + /** + * Pushes an item onto the top of this stack. + * + * + * @param val the boolean to be pushed onto this stack. + * @return the item argument. + */ + public final boolean push(boolean val) { + if (m_index == m_allocatedSize - 1) + grow(); + + return (m_values[++m_index] = val); + } + + /** + * Removes the object at the top of this stack and returns that + * object as the value of this function. + * + * @return The object at the top of this stack. + * @throws EmptyStackException if this stack is empty. + */ + public final boolean pop() { + return m_values[m_index--]; + } + + /** + * Removes the object at the top of this stack and returns the + * next object at the top as the value of this function. + * + * + * @return Next object to the top or false if none there + */ + public final boolean popAndTop() { + m_index--; + return (m_index >= 0) ? m_values[m_index] : false; + } + + /** + * Set the item at the top of this stack + * + * + * @param b Object to set at the top of this stack + */ + public final void setTop(boolean b) { + m_values[m_index] = b; + } + + /** + * Looks at the object at the top of this stack without removing it + * from the stack. + * + * @return the object at the top of this stack. + * @throws EmptyStackException if this stack is empty. + */ + public final boolean peek() { + return m_values[m_index]; + } + + /** + * Looks at the object at the top of this stack without removing it + * from the stack. If the stack is empty, it returns false. + * + * @return the object at the top of this stack. + */ + public final boolean peekOrFalse() { + return (m_index > -1) ? m_values[m_index] : false; + } + + /** + * Looks at the object at the top of this stack without removing it + * from the stack. If the stack is empty, it returns true. + * + * @return the object at the top of this stack. + */ + public final boolean peekOrTrue() { + return (m_index > -1) ? m_values[m_index] : true; + } + + /** + * Tests if this stack is empty. + * + * @return true if this stack is empty; + * false otherwise. + */ + public boolean isEmpty() { + return (m_index == -1); + } + + /** + * Grows the size of the stack + * + */ + private void grow() { + m_allocatedSize *= 2; + boolean newVector[] = new boolean[m_allocatedSize]; + System.arraycopy(m_values, 0, newVector, 0, m_index + 1); + m_values = newVector; + } } // Implement DTDHandler @@ -3421,14 +3307,12 @@ * @throws IOException */ private void DTDprolog() throws SAXException, IOException { - final java.io.Writer writer = m_writer; - if (m_needToOutputDocTypeDecl) - { + final Writer writer = m_writer; + if (m_needToOutputDocTypeDecl) { outputDocTypeDecl(m_elemContext.m_elementName, false); m_needToOutputDocTypeDecl = false; } - if (m_inDoctype) - { + if (m_inDoctype) { writer.write(" ["); writer.write(m_lineSep, 0, m_lineSepLen); m_inDoctype = false; diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToUnknownStream.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToUnknownStream.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToUnknownStream.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,13 +1,13 @@ /* - * reserved comment block - * DO NOT REMOVE OR ALTER! + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. */ /* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -17,9 +17,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: ToUnknownStream.java,v 1.3 2005/09/28 13:49:08 pvedula Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import java.io.IOException; @@ -27,17 +25,14 @@ import java.io.Writer; import java.util.Properties; import java.util.ArrayList; - import javax.xml.transform.SourceLocator; import javax.xml.transform.Transformer; - import org.w3c.dom.Node; import org.xml.sax.Attributes; import org.xml.sax.ContentHandler; import org.xml.sax.Locator; import org.xml.sax.SAXException; - /** *This class wraps another SerializationHandler. The wrapped object will either * handler XML or HTML, which is not known until a little later when the first XML @@ -55,7 +50,6 @@ */ public final class ToUnknownStream extends SerializerBase { - /** * The wrapped handler, initially XML but possibly switched to HTML */ @@ -71,11 +65,11 @@ */ private boolean m_wrapped_handler_not_initialized = false; - /** * the prefix of the very first tag in the document */ private String m_firstElementPrefix; + /** * the element name (including any prefix) of the very first tag in the document */ @@ -101,6 +95,7 @@ * _namespacePrefix has the matching prefix for these URI's */ private ArrayList m_namespaceURI = null; + /** * A collection of namespace Prefix (only for first element) * _namespaceURI has the matching URIs for these prefix' @@ -112,34 +107,13 @@ * was initialized */ private boolean m_needToCallStartDocument = false; - /** - * true if setVersion() was called before the underlying handler - * was initialized - */ - private boolean m_setVersion_called = false; - /** - * true if setDoctypeSystem() was called before the underlying handler - * was initialized - */ - private boolean m_setDoctypeSystem_called = false; - /** - * true if setDoctypePublic() was called before the underlying handler - * was initialized - */ - private boolean m_setDoctypePublic_called = false; - /** - * true if setMediaType() was called before the underlying handler - * was initialized - */ - private boolean m_setMediaType_called = false; /** * Default constructor. * Initially this object wraps an XML Stream object, so _handler is never null. * That may change later to an HTML Stream object. */ - public ToUnknownStream() - { + public ToUnknownStream() { m_handler = new ToXMLStream(); } @@ -147,8 +121,7 @@ * @see Serializer#asContentHandler() * @return the wrapped XML or HTML handler */ - public ContentHandler asContentHandler() throws IOException - { + public ContentHandler asContentHandler() throws IOException { /* don't return the real handler ( m_handler ) because * that would expose the real handler to the outside. * Keep m_handler private so it can be internally swapped @@ -160,8 +133,7 @@ /** * @see SerializationHandler#close() */ - public void close() - { + public void close() { m_handler.close(); } @@ -169,8 +141,7 @@ * @see Serializer#getOutputFormat() * @return the properties of the underlying handler */ - public Properties getOutputFormat() - { + public Properties getOutputFormat() { return m_handler.getOutputFormat(); } @@ -178,8 +149,7 @@ * @see Serializer#getOutputStream() * @return the OutputStream of the underlying XML or HTML handler */ - public OutputStream getOutputStream() - { + public OutputStream getOutputStream() { return m_handler.getOutputStream(); } @@ -187,8 +157,7 @@ * @see Serializer#getWriter() * @return the Writer of the underlying XML or HTML handler */ - public Writer getWriter() - { + public Writer getWriter() { return m_handler.getWriter(); } @@ -197,8 +166,7 @@ * @see Serializer#reset() * @return ??? */ - public boolean reset() - { + public boolean reset() { return m_handler.reset(); } @@ -208,10 +176,8 @@ * @see DOMSerializer#serialize(Node) * */ - public void serialize(Node node) throws IOException - { - if (m_firstTagNotEmitted) - { + public void serialize(Node node) throws IOException { + if (m_firstTagNotEmitted) { flush(); } m_handler.serialize(node); @@ -220,8 +186,7 @@ /** * @see SerializationHandler#setEscaping(boolean) */ - public boolean setEscaping(boolean escape) throws SAXException - { + public boolean setEscaping(boolean escape) throws SAXException { return m_handler.setEscaping(escape); } @@ -230,8 +195,7 @@ * @param format the output properties to set * @see Serializer#setOutputFormat(Properties) */ - public void setOutputFormat(Properties format) - { + public void setOutputFormat(Properties format) { m_handler.setOutputFormat(format); } @@ -240,8 +204,7 @@ * @param output the OutputStream to write to * @see Serializer#setOutputStream(OutputStream) */ - public void setOutputStream(OutputStream output) - { + public void setOutputStream(OutputStream output) { m_handler.setOutputStream(output); } @@ -250,8 +213,7 @@ * @param writer the writer to write to * @see Serializer#setWriter(Writer) */ - public void setWriter(Writer writer) - { + public void setWriter(Writer writer) { m_handler.setWriter(writer); } @@ -265,12 +227,8 @@ * @param XSLAttribute true if this attribute is coming from an xsl:attribute element * @see ExtendedContentHandler#addAttribute(String, String, String, String, String) */ - public void addAttribute( - String uri, - String localName, - String rawName, - String type, - String value) + public void addAttribute(String uri, String localName, String rawName, + String type, String value) throws SAXException { addAttribute(uri, localName, rawName, type, value, false); @@ -286,35 +244,27 @@ * @param XSLAttribute true if this attribute is coming from an xsl:attribute element * @see ExtendedContentHandler#addAttribute(String, String, String, String, String) */ - public void addAttribute( - String uri, - String localName, - String rawName, - String type, - String value, - boolean XSLAttribute) + public void addAttribute(String uri, String localName, String rawName, + String type, String value, boolean XSLAttribute) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } m_handler.addAttribute(uri, localName, rawName, type, value, XSLAttribute); } + /** * Adds an attribute to the currenly open tag * @param rawName the attribute name, with prefix (if any) * @param value the value of the parameter * @see ExtendedContentHandler#addAttribute(String, String) */ - public void addAttribute(String rawName, String value) - { - if (m_firstTagNotEmitted) - { + public void addAttribute(String rawName, String value) { + if (m_firstTagNotEmitted) { flush(); } m_handler.addAttribute(rawName, value); - } /** @@ -323,52 +273,50 @@ public void addUniqueAttribute(String rawName, String value, int flags) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } m_handler.addUniqueAttribute(rawName, value, flags); - } /** * Converts the String to a character array and calls the SAX method * characters(char[],int,int); * + * @param chars The string of characters to process. + * + * @throws org.xml.sax.SAXException + * * @see ExtendedContentHandler#characters(String) */ - public void characters(String chars) throws SAXException - { - final int length = chars.length(); - if (length > m_charsBuff.length) - { - m_charsBuff = new char[length*2 + 1]; + public void characters(String chars) throws SAXException { + final int len = (chars == null) ? 0 : chars.length(); + if (len > m_charsBuff.length) { + m_charsBuff = new char[len * 2 + 1]; } - chars.getChars(0, length, m_charsBuff, 0); - this.characters(m_charsBuff, 0, length); + if (len > 0) { + chars.getChars(0, len, m_charsBuff, 0); + } + this.characters(m_charsBuff, 0, len); } /** * Pass the call on to the underlying handler * @see ExtendedContentHandler#endElement(String) */ - public void endElement(String elementName) throws SAXException - { - if (m_firstTagNotEmitted) - { + public void endElement(String elementName) throws SAXException { + if (m_firstTagNotEmitted) { flush(); } m_handler.endElement(elementName); } - /** * @see org.xml.sax.ContentHandler#startPrefixMapping(String, String) * @param prefix The prefix that maps to the URI * @param uri The URI for the namespace */ - public void startPrefixMapping(String prefix, String uri) throws SAXException - { + public void startPrefixMapping(String prefix, String uri) throws SAXException { this.startPrefixMapping(prefix,uri, true); } @@ -387,11 +335,12 @@ throws SAXException { // hack for XSLTC with finding URI for default namespace - if (m_firstTagNotEmitted && m_firstElementURI == null && m_firstElementName != null) + if (m_firstTagNotEmitted && + m_firstElementURI == null && + m_firstElementName != null) { String prefix1 = getPrefixPart(m_firstElementName); - if (prefix1 == null && EMPTYSTRING.equals(prefix)) - { + if (prefix1 == null && EMPTYSTRING.equals(prefix)) { // the elements URI is not known yet, and it // doesn't have a prefix, and we are currently // setting the uri for prefix "", so we have @@ -399,45 +348,36 @@ m_firstElementURI = uri; } } - startPrefixMapping(prefix,uri, false); + startPrefixMapping(prefix, uri, false); } public boolean startPrefixMapping(String prefix, String uri, boolean shouldFlush) throws SAXException { boolean pushed = false; - if (m_firstTagNotEmitted) - { - if (m_firstElementName != null && shouldFlush) - { + if (m_firstTagNotEmitted) { + if (m_firstElementName != null && shouldFlush) { /* we've already seen a startElement, and this is a prefix mapping * for the up coming element, so flush the old element * then send this event on its way. */ flush(); pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush); - } - else - { - if (m_namespacePrefix == null) - { + } else { + if (m_namespacePrefix == null) { m_namespacePrefix = new ArrayList<>(); m_namespaceURI = new ArrayList<>(); } m_namespacePrefix.add(prefix); m_namespaceURI.add(uri); - if (m_firstElementURI == null) - { + if (m_firstElementURI == null) { if (prefix.equals(m_firstElementPrefix)) m_firstElementURI = uri; } } - - } - else - { - pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush); + } else { + pushed = m_handler.startPrefixMapping(prefix, uri, shouldFlush); } return pushed; } @@ -446,54 +386,39 @@ * This method cannot be cached because default is different in * HTML and XML (we need more than a boolean). */ - - public void setVersion(String version) - { + public void setVersion(String version) { m_handler.setVersion(version); - - // Cache call to setVersion() - // super.setVersion(version); - m_setVersion_called = true; } /** * @see org.xml.sax.ContentHandler#startDocument() */ - public void startDocument() throws SAXException - { + public void startDocument() throws SAXException { m_needToCallStartDocument = true; } - - - public void startElement(String qName) throws SAXException - { + public void startElement(String qName) throws SAXException { this.startElement(null, null, qName, null); } - public void startElement(String namespaceURI, String localName, String qName) throws SAXException - { + public void startElement(String namespaceURI, String localName, + String qName) throws SAXException { this.startElement(namespaceURI, localName, qName, null); } - public void startElement( - String namespaceURI, - String localName, - String elementName, - Attributes atts) throws SAXException + public void startElement(String namespaceURI, String localName, + String elementName, Attributes atts) + throws SAXException { - - if (m_needToCallSetDocumentInfo){ + if (m_needToCallSetDocumentInfo) { super.setDocumentInfo(); m_needToCallSetDocumentInfo = false; } /* we are notified of the start of an element */ - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { /* we have not yet sent the first element on its way */ - if (m_firstElementName != null) - { + if (m_firstElementName != null) { /* this is not the first element, but a later one. * But we have the old element pending, so flush it out, * then send this one on its way. @@ -645,16 +570,14 @@ * Pass the call on to the underlying handler * @see XSLOutputAttributes#getVersion() */ - public String getVersion() - { + public String getVersion() { return m_handler.getVersion(); } /** * @see XSLOutputAttributes#setDoctype(String, String) */ - public void setDoctype(String system, String pub) - { + public void setDoctype(String system, String pub) { m_handler.setDoctypePublic(pub); m_handler.setDoctypeSystem(system); } @@ -665,10 +588,8 @@ * @param doctype the public doctype to set * @see XSLOutputAttributes#setDoctypePublic(String) */ - public void setDoctypePublic(String doctype) - { + public void setDoctypePublic(String doctype) { m_handler.setDoctypePublic(doctype); - m_setDoctypePublic_called = true; } /** @@ -677,18 +598,15 @@ * @param doctype the system doctype to set * @see XSLOutputAttributes#setDoctypeSystem(String) */ - public void setDoctypeSystem(String doctype) - { + public void setDoctypeSystem(String doctype) { m_handler.setDoctypeSystem(doctype); - m_setDoctypeSystem_called = true; } /** * Pass the call on to the underlying handler * @see XSLOutputAttributes#setEncoding(String) */ - public void setEncoding(String encoding) - { + public void setEncoding(String encoding) { m_handler.setEncoding(encoding); } @@ -696,34 +614,29 @@ * Pass the call on to the underlying handler * @see XSLOutputAttributes#setIndent(boolean) */ - public void setIndent(boolean indent) - { + public void setIndent(boolean indent) { m_handler.setIndent(indent); } /** * Pass the call on to the underlying handler */ - public void setIndentAmount(int value) - { + public void setIndentAmount(int value) { m_handler.setIndentAmount(value); } /** * @see XSLOutputAttributes#setMediaType(String) */ - public void setMediaType(String mediaType) - { + public void setMediaType(String mediaType) { m_handler.setMediaType(mediaType); - m_setMediaType_called = true; } /** * Pass the call on to the underlying handler * @see XSLOutputAttributes#setOmitXMLDeclaration(boolean) */ - public void setOmitXMLDeclaration(boolean b) - { + public void setOmitXMLDeclaration(boolean b) { m_handler.setOmitXMLDeclaration(b); } @@ -731,27 +644,16 @@ * Pass the call on to the underlying handler * @see XSLOutputAttributes#setStandalone(String) */ - public void setStandalone(String standalone) - { + public void setStandalone(String standalone) { m_handler.setStandalone(standalone); } /** - * @see XSLOutputAttributes#setVersion(String) - */ - - /** * Pass the call on to the underlying handler * @see org.xml.sax.ext.DeclHandler#attributeDecl(String, String, String, String, String) */ - public void attributeDecl( - String arg0, - String arg1, - String arg2, - String arg3, - String arg4) - throws SAXException - { + public void attributeDecl(String arg0, String arg1, String arg2, + String arg3, String arg4) throws SAXException { m_handler.attributeDecl(arg0, arg1, arg2, arg3, arg4); } @@ -761,8 +663,7 @@ */ public void elementDecl(String arg0, String arg1) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { emitFirstTag(); } m_handler.elementDecl(arg0, arg1); @@ -778,8 +679,7 @@ String systemId) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } m_handler.externalEntityDecl(name, publicId, systemId); @@ -792,8 +692,7 @@ public void internalEntityDecl(String arg0, String arg1) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } m_handler.internalEntityDecl(arg0, arg1); @@ -806,29 +705,21 @@ public void characters(char[] characters, int offset, int length) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); } - m_handler.characters(characters, offset, length); - } /** * Pass the call on to the underlying handler * @see org.xml.sax.ContentHandler#endDocument() */ - public void endDocument() throws SAXException - { - if (m_firstTagNotEmitted) - { + public void endDocument() throws SAXException { + if (m_firstTagNotEmitted) { flush(); } - m_handler.endDocument(); - - } /** @@ -838,17 +729,14 @@ public void endElement(String namespaceURI, String localName, String qName) throws SAXException { - if (m_firstTagNotEmitted) - { + if (m_firstTagNotEmitted) { flush(); if (namespaceURI == null && m_firstElementURI != null) namespaceURI = m_firstElementURI; - if (localName == null && m_firstElementLocalName != null) localName = m_firstElementLocalName; } - m_handler.endElement(namespaceURI, localName, qName); } @@ -856,8 +744,7 @@ * Pass the call on to the underlying handler * @see org.xml.sax.ContentHandler#endPrefixMapping(String) */ - public void endPrefixMapping(String prefix) throws SAXException - { + public void endPrefixMapping(String prefix) throws SAXException { m_handler.endPrefixMapping(prefix); } @@ -1071,12 +958,9 @@ m_wrapped_handler_not_initialized = false; } - private void emitFirstTag() throws SAXException - { - if (m_firstElementName != null) - { - if (m_wrapped_handler_not_initialized) - { + private void emitFirstTag() throws SAXException { + if (m_firstElementName != null) { + if (m_wrapped_handler_not_initialized) { initStreamOutput(); m_wrapped_handler_not_initialized = false; } @@ -1086,14 +970,11 @@ m_attributes = null; // Output namespaces of first tag - if (m_namespacePrefix != null) - { + if (m_namespacePrefix != null) { final int n = m_namespacePrefix.size(); - for (int i = 0; i < n; i++) - { - final String prefix = - (String) m_namespacePrefix.get(i); - final String uri = (String) m_namespaceURI.get(i); + for (int i = 0; i < n; i++) { + final String prefix = m_namespacePrefix.get(i); + final String uri = m_namespaceURI.get(i); m_handler.startPrefixMapping(prefix, uri, false); } m_namespacePrefix = null; @@ -1109,8 +990,7 @@ * Don't want to override static function on SerializerBase * So added Unknown suffix to method name. */ - private String getLocalNameUnknown(String value) - { + private String getLocalNameUnknown(String value) { int idx = value.lastIndexOf(':'); if (idx >= 0) value = value.substring(idx + 1); @@ -1121,13 +1001,12 @@ } /** - * Utility function to return prefix - * - * Don't want to override static function on SerializerBase - * So added Unknown suffix to method name. - */ - private String getPrefixPartUnknown(String qname) - { + * Utility function to return prefix + * + * Don't want to override static function on SerializerBase + * So added Unknown suffix to method name. + */ + private String getPrefixPartUnknown(String qname) { final int index = qname.indexOf(':'); return (index > 0) ? qname.substring(0, index) : EMPTYSTRING; } @@ -1139,8 +1018,7 @@ * * @return true if the first element is an opening tag */ - private boolean isFirstElemHTML() - { + private boolean isFirstElemHTML() { boolean isHTML; // is the first tag html, not considering the prefix ? @@ -1148,29 +1026,27 @@ getLocalNameUnknown(m_firstElementName).equalsIgnoreCase("html"); // Try to rule out if this is not to be an HTML document based on URI - if (isHTML - && m_firstElementURI != null - && !EMPTYSTRING.equals(m_firstElementURI)) + if (isHTML && + m_firstElementURI != null && + !EMPTYSTRING.equals(m_firstElementURI)) { // the element has a non-trivial namespace isHTML = false; } // Try to rule out if this is an not to be an HTML document based on prefix - if (isHTML && m_namespacePrefix != null) - { + if (isHTML && m_namespacePrefix != null) { /* the first element has a name of "html", but lets check the prefix. * If the prefix points to a namespace with a URL that is not "" * then the doecument doesn't start with an tag, and isn't html */ final int max = m_namespacePrefix.size(); - for (int i = 0; i < max; i++) - { + for (int i = 0; i < max; i++) { final String prefix = m_namespacePrefix.get(i); final String uri = m_namespaceURI.get(i); - if (m_firstElementPrefix != null - && m_firstElementPrefix.equals(prefix) - && !EMPTYSTRING.equals(uri)) + if (m_firstElementPrefix != null && + m_firstElementPrefix.equals(prefix) && + !EMPTYSTRING.equals(uri)) { // The first element has a prefix, so it can't be isHTML = false; @@ -1181,11 +1057,11 @@ } return isHTML; } + /** * @see Serializer#asDOMSerializer() */ - public DOMSerializer asDOMSerializer() throws IOException - { + public DOMSerializer asDOMSerializer() throws IOException { return m_handler.asDOMSerializer(); } @@ -1194,15 +1070,14 @@ * specified in the cdata-section-elements attribute. * @see SerializationHandler#setCdataSectionElements(java.util.Vector) */ - public void setCdataSectionElements(ArrayList URI_and_localNames) - { + public void setCdataSectionElements(ArrayList URI_and_localNames) { m_handler.setCdataSectionElements(URI_and_localNames); } + /** * @see ExtendedContentHandler#addAttributes(org.xml.sax.Attributes) */ - public void addAttributes(Attributes atts) throws SAXException - { + public void addAttributes(Attributes atts) throws SAXException { m_handler.addAttributes(atts); } @@ -1211,98 +1086,83 @@ * Simply returns the mappings of the wrapped handler. * @see ExtendedContentHandler#getNamespaceMappings() */ - public NamespaceMappings getNamespaceMappings() - { + public NamespaceMappings getNamespaceMappings() { NamespaceMappings mappings = null; - if (m_handler != null) - { + if (m_handler != null) { mappings = m_handler.getNamespaceMappings(); } return mappings; } + /** * @see SerializationHandler#flushPending() */ - public void flushPending() throws SAXException - { - + public void flushPending() throws SAXException { flush(); - m_handler.flushPending(); } - private void flush() - { - try - { - if (m_firstTagNotEmitted) - { - emitFirstTag(); - } - if (m_needToCallStartDocument) - { - m_handler.startDocument(); - m_needToCallStartDocument = false; - } - } - catch(SAXException e) - { + private void flush() { + try { + if (m_firstTagNotEmitted) { + emitFirstTag(); + } + if (m_needToCallStartDocument) { + m_handler.startDocument(); + m_needToCallStartDocument = false; + } + } catch(SAXException e) { throw new RuntimeException(e.toString()); } - - } /** * @see ExtendedContentHandler#getPrefix */ - public String getPrefix(String namespaceURI) - { + public String getPrefix(String namespaceURI) { return m_handler.getPrefix(namespaceURI); } + /** * @see ExtendedContentHandler#entityReference(java.lang.String) */ - public void entityReference(String entityName) throws SAXException - { + public void entityReference(String entityName) throws SAXException { m_handler.entityReference(entityName); } /** * @see ExtendedContentHandler#getNamespaceURI(java.lang.String, boolean) */ - public String getNamespaceURI(String qname, boolean isElement) - { + public String getNamespaceURI(String qname, boolean isElement) { return m_handler.getNamespaceURI(qname, isElement); } - public String getNamespaceURIFromPrefix(String prefix) - { + public String getNamespaceURIFromPrefix(String prefix) { return m_handler.getNamespaceURIFromPrefix(prefix); } - public void setTransformer(Transformer t) - { + public void setTransformer(Transformer t) { m_handler.setTransformer(t); if ((t instanceof SerializerTrace) && - (((SerializerTrace) t).hasTraceListeners())) { - m_tracer = (SerializerTrace) t; + (((SerializerTrace) t).hasTraceListeners())) + { + m_tracer = (SerializerTrace) t; } else { - m_tracer = null; + m_tracer = null; } } - public Transformer getTransformer() - { + + public Transformer getTransformer() { return m_handler.getTransformer(); } /** * @see SerializationHandler#setContentHandler(org.xml.sax.ContentHandler) */ - public void setContentHandler(ContentHandler ch) - { + public void setContentHandler(ContentHandler ch) { m_handler.setContentHandler(ch); } + /** * This method is used to set the source locator, which might be used to * generated an error message. @@ -1310,14 +1170,11 @@ * * @see ExtendedContentHandler#setSourceLocator(javax.xml.transform.SourceLocator) */ - public void setSourceLocator(SourceLocator locator) - { + public void setSourceLocator(SourceLocator locator) { m_handler.setSourceLocator(locator); } - protected void firePseudoElement(String elementName) - { - + protected void firePseudoElement(String elementName) { if (m_tracer != null) { StringBuffer sb = new StringBuffer(); diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/XSLOutputAttributes.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/XSLOutputAttributes.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/XSLOutputAttributes.java Wed Jul 05 22:30:52 2017 +0200 @@ -3,13 +3,12 @@ * DO NOT REMOVE OR ALTER! */ /* - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You under the Apache License, Version 2.0 + * (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * @@ -19,9 +18,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -/* - * $Id: XSLOutputAttributes.java,v 1.2.4.1 2005/09/15 08:15:32 suresh_emailid Exp $ - */ + package com.sun.org.apache.xml.internal.serializer; import java.util.ArrayList; @@ -55,8 +52,7 @@ * * @xsl.usage internal */ -interface XSLOutputAttributes -{ +interface XSLOutputAttributes { /** * Returns the previously set value of the value to be used as the public * identifier in the document type declaration (DTD). @@ -65,6 +61,7 @@ * output document. */ public String getDoctypePublic(); + /** * Returns the previously set value of the value to be used * as the system identifier in the document type declaration (DTD). @@ -73,13 +70,15 @@ * */ public String getDoctypeSystem(); + /** * @return the character encoding to be used in the output document. */ public String getEncoding(); + /** - * @return true if the output document should be indented to visually - * indicate its structure. + * @return true if the output document should be indented to visually + * indicate its structure. */ public boolean getIndent(); @@ -87,21 +86,25 @@ * @return the number of spaces to indent for each indentation level. */ public int getIndentAmount(); + /** * @return the mediatype the media-type or MIME type associated with the * output document. */ public String getMediaType(); + /** * @return true if the XML declaration is to be omitted from the output * document. */ public boolean getOmitXMLDeclaration(); + /** - * @return a value of "yes" if the standalone delaration is to - * be included in the output document. - */ + * @return a value of "yes" if the standalone delaration is to + * be included in the output document. + */ public String getStandalone(); + /** * @return the version of the output format. */ @@ -132,20 +135,23 @@ public void setDoctype(String system, String pub); /** Set the value coming from the xsl:output doctype-public stylesheet attribute. - * @param doctype the public identifier to be used in the DOCTYPE - * declaration in the output document. - */ + * @param doctype the public identifier to be used in the DOCTYPE + * declaration in the output document. + */ public void setDoctypePublic(String doctype); + /** Set the value coming from the xsl:output doctype-system stylesheet attribute. - * @param doctype the system identifier to be used in the DOCTYPE - * declaration in the output document. - */ + * @param doctype the system identifier to be used in the DOCTYPE + * declaration in the output document. + */ public void setDoctypeSystem(String doctype); + /** * Sets the character encoding coming from the xsl:output encoding stylesheet attribute. * @param encoding the character encoding */ public void setEncoding(String encoding); + /** * Sets the value coming from the xsl:output indent stylesheet * attribute. @@ -153,18 +159,21 @@ * indicate its structure. */ public void setIndent(boolean indent); + /** * Sets the value coming from the xsl:output media-type stylesheet attribute. * @param mediatype the media-type or MIME type associated with the output * document. */ public void setMediaType(String mediatype); + /** * Sets the value coming from the xsl:output omit-xml-declaration stylesheet attribute * @param b true if the XML declaration is to be omitted from the output * document. */ public void setOmitXMLDeclaration(boolean b); + /** * Sets the value coming from the xsl:output standalone stylesheet attribute. * @param standalone a value of "yes" indicates that the @@ -172,6 +181,7 @@ * document. */ public void setStandalone(String standalone); + /** * Sets the value coming from the xsl:output version attribute. * @param version the version of the output format. @@ -194,6 +204,7 @@ * @return The value of the parameter */ public String getOutputProperty(String name); + /** * Get the default value for a property that affects seraialization, * or null if there is none. It is possible that a non-default value @@ -203,6 +214,7 @@ * @return The default value of the parameter, or null if there is no default value. */ public String getOutputPropertyDefault(String name); + /** * Set the non-default value for a property that affects seraialization. * @param name The name of the property, which is just the local name @@ -216,7 +228,7 @@ * * @val The non-default value of the parameter */ - public void setOutputProperty(String name, String val); + public void setOutputProperty(String name, String val); /** * Set the default value for a property that affects seraialization. @@ -231,5 +243,5 @@ * * @val The default value of the parameter */ - public void setOutputPropertyDefault(String name, String val); + public void setOutputPropertyDefault(String name, String val); } diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/utils/XMLReaderManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -81,6 +81,8 @@ private boolean _useCatalog; private CatalogFeatures _catalogFeatures; + private int _cdataChunkSize; + /** * Hidden constructor */ @@ -173,13 +175,12 @@ } } - try { - //reader is cached, but this property might have been reset - reader.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, _accessExternalDTD); - } catch (SAXException se) { - XMLSecurityManager.printWarning(reader.getClass().getName(), - XMLConstants.ACCESS_EXTERNAL_DTD, se); - } + //reader is cached, but this property might have been reset + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD, + _accessExternalDTD, true); + + JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, JdkXmlUtils.CDATA_CHUNK_SIZE, + _cdataChunkSize, false); String lastProperty = ""; try { @@ -278,7 +279,8 @@ _xmlSecurityManager = (XMLSecurityManager)value; } else if (JdkXmlFeatures.CATALOG_FEATURES.equals(name)) { _catalogFeatures = (CatalogFeatures)value; + } else if (JdkXmlUtils.CDATA_CHUNK_SIZE.equals(name)) { + _cdataChunkSize = JdkXmlUtils.getValue(value, _cdataChunkSize); } - } } diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java --- a/jaxp/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/jdk/xml/internal/JdkXmlUtils.java Wed Jul 05 22:30:52 2017 +0200 @@ -25,6 +25,7 @@ package jdk.xml.internal; +import com.sun.org.apache.xalan.internal.utils.XMLSecurityManager; import com.sun.org.apache.xerces.internal.util.ParserConfigurationSettings; import com.sun.org.apache.xerces.internal.xni.parser.XMLComponentManager; import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException; @@ -39,6 +40,7 @@ * Constants for use across JAXP processors. */ public class JdkXmlUtils { + /** * Catalog features */ @@ -58,11 +60,63 @@ /** * Default value of USE_CATALOG. This will read the System property */ - public static final boolean USE_CATALOG_DEFAULT = - SecuritySupport.getJAXPSystemProperty(SP_USE_CATALOG, true); + public static final boolean USE_CATALOG_DEFAULT + = SecuritySupport.getJAXPSystemProperty(Boolean.class, SP_USE_CATALOG, "true"); + + /** + * JDK features (will be consolidated in the next major feature revamp + */ + public final static String CDATA_CHUNK_SIZE = "jdk.xml.cdataChunkSize"; + public static final int CDATA_CHUNK_SIZE_DEFAULT + = SecuritySupport.getJAXPSystemProperty(Integer.class, CDATA_CHUNK_SIZE, "0"); + + /** + * Returns the value. + * + * @param value the specified value + * @param defValue the default value + * @return the value, or the default value if the value is null + */ + public static int getValue(Object value, int defValue) { + if (value == null) { + return defValue; + } + + if (value instanceof Number) { + return ((Number) value).intValue(); + } else if (value instanceof String) { + return Integer.parseInt(String.valueOf(value)); + } else { + throw new IllegalArgumentException("Unexpected class: " + + value.getClass()); + } + } + + /** + * Sets the XMLReader instance with the specified property if the the + * property is supported, ignores error if not, issues a warning if so + * requested. + * + * @param reader an XMLReader instance + * @param property the name of the property + * @param value the value of the property + * @param warn a flag indicating whether a warning should be issued + */ + public static void setXMLReaderPropertyIfSupport(XMLReader reader, String property, + Object value, boolean warn) { + try { + reader.setProperty(property, value); + } catch (SAXNotRecognizedException | SAXNotSupportedException e) { + if (warn) { + XMLSecurityManager.printWarning(reader.getClass().getName(), + property, e); + } + } + } /** * Returns the value of a Catalog feature by the property name. + * * @param features a CatalogFeatures instance * @param name the name of a Catalog feature * @return the value of a Catalog feature, null if the name does not match @@ -106,10 +160,9 @@ return builder.build(); } - /** - * Passing on the CatalogFeatures settings from one Xerces configuration object - * to another. + * Passing on the CatalogFeatures settings from one Xerces configuration + * object to another. * * @param config1 a Xerces configuration object * @param config2 a Xerces configuration object @@ -120,14 +173,13 @@ boolean useCatalog = config1.getFeature(XMLConstants.USE_CATALOG); try { config2.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog); - } - catch (XMLConfigurationException e) { + } catch (XMLConfigurationException e) { supportCatalog = false; } if (supportCatalog && useCatalog) { try { - for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { + for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { config2.setProperty(f.getPropertyName(), config1.getProperty(f.getPropertyName())); } } catch (XMLConfigurationException e) { @@ -137,8 +189,8 @@ } /** - * Passing on the CatalogFeatures settings from a Xerces configuration object - * to an XMLReader. + * Passing on the CatalogFeatures settings from a Xerces configuration + * object to an XMLReader. * * @param config a Xerces configuration object * @param reader an XMLReader @@ -148,14 +200,13 @@ boolean useCatalog = config.getFeature(XMLConstants.USE_CATALOG); try { reader.setFeature(JdkXmlUtils.USE_CATALOG, useCatalog); - } - catch (SAXNotRecognizedException | SAXNotSupportedException e) { + } catch (SAXNotRecognizedException | SAXNotSupportedException e) { supportCatalog = false; } if (supportCatalog && useCatalog) { try { - for( CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { + for (CatalogFeatures.Feature f : CatalogFeatures.Feature.values()) { reader.setProperty(f.getPropertyName(), config.getProperty(f.getPropertyName())); } } catch (SAXNotRecognizedException | SAXNotSupportedException e) { diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/src/java.xml/share/classes/jdk/xml/internal/SecuritySupport.java --- a/jaxp/src/java.xml/share/classes/jdk/xml/internal/SecuritySupport.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/src/java.xml/share/classes/jdk/xml/internal/SecuritySupport.java Wed Jul 05 22:30:52 2017 +0200 @@ -83,19 +83,26 @@ } /** - * Reads boolean type system property. + * Reads a system property. * + * @param the type of the property value + * @param type the type of the property value * @param propName the name of the property * @param defValue the default value * @return the value of the property, or the default value of no system * property is found */ - public static boolean getJAXPSystemProperty(String propName, boolean defValue) { + public static T getJAXPSystemProperty(Class type, String propName, String defValue) { String value = getJAXPSystemProperty(propName); if (value == null) { - return defValue; + value = defValue; } - return Boolean.parseBoolean(value); + if (Integer.class.isAssignableFrom(type)) { + return type.cast(Integer.parseInt(value)); + } else if (Boolean.class.isAssignableFrom(type)) { + return type.cast(Boolean.parseBoolean(value)); + } + return type.cast(value); } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/test/Makefile --- a/jaxp/test/Makefile Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/test/Makefile Wed Jul 05 22:30:52 2017 +0200 @@ -55,7 +55,7 @@ UNAME = uname UNIQ = uniq WC = wc -ZIP = zip +ZIPEXE = zip # Get OS name from uname (Cygwin inexplicably adds _NT-5.1) UNAME_S := $(shell $(UNAME) -s | $(CUT) -f1 -d_) @@ -130,7 +130,7 @@ ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \ && $(CD) $(ABS_TEST_OUTPUT_DIR) \ && $(CHMOD) -R a+r . \ - && $(ZIP) -q -r $(ARCHIVE_BUNDLE) . ) + && $(ZIPEXE) -q -r $(ARCHIVE_BUNDLE) . ) # important results files SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt") diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/test/ProblemList.txt --- a/jaxp/test/ProblemList.txt Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/test/ProblemList.txt Wed Jul 05 22:30:52 2017 +0200 @@ -23,4 +23,4 @@ # ########################################################################### -javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh 8147431 generic-all +javax/xml/jaxp/isolatedjdk/catalog/PropertiesTest.sh 8169827 generic-all diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPPolicyManager.java --- a/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPPolicyManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/test/javax/xml/jaxp/libs/jaxp/library/JAXPPolicyManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -23,6 +23,7 @@ package jaxp.library; +import java.net.URL; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; @@ -34,6 +35,7 @@ import java.util.HashMap; import java.util.Map; import java.util.PropertyPermission; +import java.util.Set; import java.util.StringJoiner; @@ -107,12 +109,7 @@ addPermission(new SecurityPermission("getPolicy")); addPermission(new SecurityPermission("setPolicy")); addPermission(new RuntimePermission("setSecurityManager")); - //Properties that jtreg and TestNG require - addPermission(new PropertyPermission("testng.show.stack.frames", "read")); addPermission(new PropertyPermission("test.src", "read")); - addPermission(new PropertyPermission("test.classes", "read")); - addPermission(new PropertyPermission("dataproviderthreadcount", "read")); - addPermission(new PropertyPermission("experimental", "read")); } /* @@ -163,6 +160,8 @@ * JAXP concrete classes. */ class TestPolicy extends Policy { + private final static Set TEST_JARS = + Set.of("jtreg.jar", "javatest.jar", "testng.jar", "jcommander.jar"); private final PermissionCollection permissions = new Permissions(); private ThreadLocal> transientPermissions = new ThreadLocal<>(); @@ -211,6 +210,16 @@ return permissions; } + private boolean isTestMachineryDomain(ProtectionDomain domain) { + CodeSource cs = (domain == null) ? null : domain.getCodeSource(); + URL loc = (cs == null) ? null : cs.getLocation(); + String path = (loc == null) ? null : loc.getPath(); + return path != null && TEST_JARS.stream() + .filter(path::endsWith) + .findAny() + .isPresent(); + } + @Override public boolean implies(ProtectionDomain domain, Permission perm) { if (allowAll()) @@ -221,8 +230,11 @@ if (permissions.implies(perm)) return true; - else - return tmpImplies(perm); + + if (isTestMachineryDomain(domain)) + return true; + + return tmpImplies(perm); } /* diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/test/javax/xml/jaxp/unittest/common/CDataChunkSizeTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jaxp/test/javax/xml/jaxp/unittest/common/CDataChunkSizeTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,284 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +package common; + +import java.io.StringReader; +import javax.xml.parsers.SAXParserFactory; +import javax.xml.stream.XMLEventReader; +import javax.xml.stream.XMLInputFactory; +import javax.xml.stream.XMLStreamConstants; +import javax.xml.stream.XMLStreamReader; +import javax.xml.stream.events.Characters; +import javax.xml.stream.events.XMLEvent; +import org.testng.Assert; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; +import org.xml.sax.InputSource; +import org.xml.sax.SAXException; +import org.xml.sax.XMLReader; +import org.xml.sax.ext.DefaultHandler2; + +/* + * @test + * @bug 8158619 + * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest + * @run testng/othervm -DrunSecMngr=true common.CDataChunkSizeTest + * @run testng/othervm common.CDataChunkSizeTest + * @summary Verifies the support of property jdk.xml.cdataChunkSize + */ +@Listeners({jaxp.library.BasePolicy.class}) +public class CDataChunkSizeTest { + + final static String CDATA_CHUNK_SIZE = "jdk.xml.cdataChunkSize"; + final static int NO_LIMIT = 0; + + /* + * @bug 8158619 + * Verifies SAXParser's support of the property + */ + @Test(dataProvider = "xml-data") + public void testSAX(String xml, int chunkSize, int numOfChunks, boolean withinLimit) throws Exception { + SAXParserFactory spf = SAXParserFactory.newInstance(); + XMLReader reader = spf.newSAXParser().getXMLReader(); + MyHandler handler = new MyHandler(chunkSize); + reader.setContentHandler(handler); + reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler); + + if (chunkSize > 0) { + reader.setProperty(CDATA_CHUNK_SIZE, chunkSize); + } + + reader.parse(new InputSource(new StringReader(xml))); + System.out.println("CData num of chunks:" + handler.getNumOfCDataChunks()); + System.out.println("CData size within limit:" + handler.chunkSizeWithinLimit()); + Assert.assertEquals(handler.getNumOfCDataChunks(), numOfChunks); + Assert.assertEquals(handler.chunkSizeWithinLimit(), withinLimit); + + } + + + /* + * @bug 8158619 + * Verifies StAX parser's support of the property + */ + @Test(dataProvider = "xml-data") + public void testStAX(String xml, int chunkSize, int expectedNumOfChunks, boolean withinLimit) throws Exception { + XMLInputFactory xifactory = XMLInputFactory.newInstance(); + xifactory.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", true); + if (chunkSize > 0) { + xifactory.setProperty(CDATA_CHUNK_SIZE, chunkSize); + } + XMLStreamReader streamReader = xifactory.createXMLStreamReader(new StringReader(xml)); + + StringBuilder cdata = new StringBuilder(); + int numOfChunks = 0; + boolean isWithinLimit = true; + while (streamReader.hasNext()) { + int eventType = streamReader.next(); + switch (eventType) { + case XMLStreamConstants.START_ELEMENT: + debugPrint("\nElement: " + streamReader.getLocalName()); + break; + case XMLStreamConstants.CDATA: + String text = streamReader.getText(); + numOfChunks++; + if (text.length() > chunkSize) { + isWithinLimit = false; + } + debugPrint("\nCDATA: " + text.length()); + cdata.append(text); + break; + case XMLStreamConstants.CHARACTERS: + debugPrint("\nCharacters: " + streamReader.getText().length()); + break; + } + } + debugPrint("CData in single chunk:" + cdata.toString().length()); + Assert.assertEquals(numOfChunks, expectedNumOfChunks); + Assert.assertEquals(isWithinLimit, withinLimit); + } + + /* + * @bug 8158619 + * Verifies StAX parser's support of the property + */ + @Test(dataProvider = "xml-data") + public void testEventReader(String xml, int chunkSize, int expectedNumOfChunks, boolean withinLimit) throws Exception { + XMLInputFactory xif = XMLInputFactory.newInstance(); + xif.setProperty("http://java.sun.com/xml/stream/properties/report-cdata-event", true); + if (chunkSize > 0) { + xif.setProperty(CDATA_CHUNK_SIZE, chunkSize); + } + XMLEventReader reader = xif.createXMLEventReader(new StringReader(xml)); + + StringBuilder cdata = new StringBuilder(); + int numOfChunks = 0; + boolean isWithinLimit = true; + while (reader.hasNext()) { + XMLEvent event = reader.nextEvent(); + //All text events get reported as Characters events + if (event.getEventType() == XMLStreamConstants.CHARACTERS) { + Characters cdataEvent = (Characters) event; + if (cdataEvent.isCData()) { + String text = cdataEvent.getData(); + numOfChunks++; + if (text.length() > chunkSize) { + isWithinLimit = false; + } + debugPrint("\nCDATA: " + text.length()); + cdata.append(text); + } + } + } + debugPrint("CData in single chunk:" + cdata.toString().length()); + Assert.assertEquals(numOfChunks, expectedNumOfChunks); + Assert.assertEquals(isWithinLimit, withinLimit); + } + + /* + * Data for tests: + * xml, size limit, expected number of chunks, expected that the size of all chunks is within the limit + */ + @DataProvider(name = "xml-data") + public Object[][] xmlData() throws Exception { + return new Object[][]{ + //{xml, NO_LIMIT, 1, false}, + {xml, 80, 13, true},}; + } + + final static String xml = "\n" + + "\n" + + " * XML Catalogs, OASIS Standard V1.1, 7 October 2005.\n" + + " *

\n" + + " * A catalog is an XML file that contains a root {@code catalog} entry with a list of catalog entries. The entries can also be grouped with a {@code group} entry. The catalog and group entries may specify {@code prefer} and {@code xml:base} attributes that set preference of public or system type of entries and base URI to resolve relative URIs.\n" + + "]]>"; + + final static String xmlVal = "\n" + + "\n" + + " \n" + + "\n" + + ""; + + final static String xsd = "\n" + + "\n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + " \n" + + //{1,8000} + " \n" + + " \n" + + "\n" + + ""; + + /** + * SAX Handler + */ + class MyHandler extends DefaultHandler2 { + + StringBuilder text = new StringBuilder(); + StringBuilder cdata = new StringBuilder(); + + int cdataChunkSize = 0; + boolean cdataStart = false; + boolean cdataEnd = false; + int numOfCDataChunks; + boolean withinLimit = true; + + public MyHandler(int chunkSize) { + cdataChunkSize = chunkSize; + } + + public String getText() { + return text.toString(); + } + + public String getCData() { + return cdata.toString(); + } + + public int getNumOfCDataChunks() { + return numOfCDataChunks; + } + + public boolean chunkSizeWithinLimit() { + return withinLimit; + } + + @Override + public void startCDATA() { + cdataStart = true; + debugPrint("\nstartCDATA"); + } + + public void endCDATA() { + cdataEnd = true; + debugPrint(cdata.toString()); + debugPrint("\nendCDATA"); + } + + @Override + public void characters(char[] ch, int start, int length) throws SAXException { + if (cdataStart && !cdataEnd) { + numOfCDataChunks++; + cdata.append(ch, start, length); + if (length > cdataChunkSize) { + withinLimit = false; + } + } else { + text.append(ch, start, length); + } + + debugPrint("\ncharacter event\n" + new String(ch, start, length)); + } + } + + void debugPrint(String msg) { + if (DEBUG) { + System.out.println(msg); + } + } + + static final boolean DEBUG = false; +} diff -r 183ae2332dd9 -r f4e854a77aa3 jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java --- a/jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxp/test/javax/xml/jaxp/unittest/transform/TransformerTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -27,17 +27,20 @@ import java.io.BufferedReader; import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileReader; import java.io.IOException; -import java.io.InputStream; import java.io.StringReader; import java.io.StringWriter; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMResult; +import javax.xml.transform.dom.DOMSource; import javax.xml.transform.sax.SAXSource; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; @@ -47,6 +50,7 @@ import org.testng.annotations.Listeners; import org.testng.annotations.Test; import org.w3c.dom.Document; +import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.ContentHandler; @@ -69,33 +73,10 @@ * @run testng/othervm -DrunSecMngr=true transform.TransformerTest * @run testng/othervm transform.TransformerTest * @summary Transformer Tests - * @bug 6272879 6305029 6505031 8150704 8162598 + * @bug 6272879 6305029 6505031 8150704 8162598 8169772 */ @Listeners({jaxp.library.FilePolicy.class}) public class TransformerTest { - private Transformer createTransformer() throws TransformerException { - return TransformerFactory.newInstance().newTransformer(); - } - - private Transformer createTransformerFromInputstream(InputStream xslStream) throws TransformerException { - return TransformerFactory.newInstance().newTransformer(new StreamSource(xslStream)); - } - - private Transformer createTransformerFromResource(String xslResource) throws TransformerException { - return TransformerFactory.newInstance().newTransformer(new StreamSource(getClass().getResource(xslResource).toString())); - } - - private Document transformInputStreamToDocument(Transformer transformer, InputStream sourceStream) throws TransformerException { - DOMResult response = new DOMResult(); - transformer.transform(new StreamSource(sourceStream), response); - return (Document)response.getNode(); - } - - private StringWriter transformResourceToStringWriter(Transformer transformer, String xmlResource) throws TransformerException { - StringWriter sw = new StringWriter(); - transformer.transform(new StreamSource(getClass().getResource(xmlResource).toString()), new StreamResult(sw)); - return sw; - } /** * Reads the contents of the given file into a string. @@ -302,10 +283,15 @@ System.out.println(sourceXml); System.out.println(); + // transform to DOM result + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(new StreamSource(new ByteArrayInputStream(xsl.getBytes()))); + DOMResult result = new DOMResult(); + t.transform(new StreamSource(new ByteArrayInputStream(sourceXml.getBytes())), result); + Document document = (Document)result.getNode(); + System.out.println("Result after transformation:"); System.out.println("============================"); - Document document = transformInputStreamToDocument(createTransformerFromInputstream(new ByteArrayInputStream(xsl.getBytes())), - new ByteArrayInputStream(sourceXml.getBytes())); OutputFormat format = new OutputFormat(); format.setIndenting(true); new XMLSerializer(System.out, format).serialize(document); @@ -335,13 +321,14 @@ // test SAXSource SAXSource saxSource = new SAXSource(new XMLReaderFor6305029(), new InputSource()); StringWriter resultWriter = new StringWriter(); - createTransformer().transform(saxSource, new StreamResult(resultWriter)); + TransformerFactory tf = TransformerFactory.newInstance(); + tf.newTransformer().transform(saxSource, new StreamResult(resultWriter)); AssertJUnit.assertEquals("Identity transform of SAXSource", XML_DOCUMENT, resultWriter.toString()); // test StreamSource StreamSource streamSource = new StreamSource(new StringReader(XML_DOCUMENT)); resultWriter = new StringWriter(); - createTransformer().transform(streamSource, new StreamResult(resultWriter)); + tf.newTransformer().transform(streamSource, new StreamResult(resultWriter)); AssertJUnit.assertEquals("Identity transform of StreamSource", XML_DOCUMENT, resultWriter.toString()); } @@ -351,10 +338,13 @@ */ @Test public final void testBug6505031() throws TransformerException { - Transformer transformer = createTransformerFromResource("transform.xsl"); - transformer.setParameter("config", getClass().getResource("config.xml").toString()); - transformer.setParameter("mapsFile", getClass().getResource("maps.xml").toString()); - String s = transformResourceToStringWriter(transformer, "template.xml").toString(); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(new StreamSource(getClass().getResource("transform.xsl").toString())); + t.setParameter("config", getClass().getResource("config.xml").toString()); + t.setParameter("mapsFile", getClass().getResource("maps.xml").toString()); + StringWriter sw = new StringWriter(); + t.transform(new StreamSource(getClass().getResource("template.xml").toString()), new StreamResult(sw)); + String s = sw.toString(); Assert.assertTrue(s.contains("map1key1value") && s.contains("map2key1value")); } @@ -365,17 +355,20 @@ @Test public final void testBug8150704() throws TransformerException, IOException { System.out.println("Testing transformation of Bug8150704-1.xml..."); - Transformer transformer = createTransformerFromResource("Bug8150704-1.xsl"); - StringWriter result = transformResourceToStringWriter(transformer, "Bug8150704-1.xml"); - String resultstring = result.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(new StreamSource(getClass().getResource("Bug8150704-1.xsl").toString())); + StringWriter sw = new StringWriter(); + t.transform(new StreamSource(getClass().getResource("Bug8150704-1.xml").toString()), new StreamResult(sw)); + String resultstring = sw.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); String reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-1.ref").getPath())); Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-1.xml does not match reference"); System.out.println("Passed."); System.out.println("Testing transformation of Bug8150704-2.xml..."); - transformer = createTransformerFromResource("Bug8150704-2.xsl"); - result = transformResourceToStringWriter(transformer, "Bug8150704-2.xml"); - resultstring = result.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); + t = tf.newTransformer(new StreamSource(getClass().getResource("Bug8150704-2.xsl").toString())); + sw = new StringWriter(); + t.transform(new StreamSource(getClass().getResource("Bug8150704-2.xml").toString()), new StreamResult(sw)); + resultstring = sw.toString().replaceAll("\\r\\n", "\n").replaceAll("\\r", "\n"); reference = getFileContentAsString(new File(getClass().getResource("Bug8150704-2.ref").getPath())); Assert.assertEquals(resultstring, reference, "Output of transformation of Bug8150704-2.xml does not match reference"); System.out.println("Passed."); @@ -422,11 +415,15 @@ System.out.println(sourceXml); System.out.println(); + // transform to DOM result + TransformerFactory tf = TransformerFactory.newInstance(); + Transformer t = tf.newTransformer(new StreamSource(new ByteArrayInputStream(xsl.getBytes()))); + DOMResult result = new DOMResult(); + t.transform(new StreamSource(new ByteArrayInputStream(sourceXml.getBytes())), result); + Document document = (Document)result.getNode(); + System.out.println("Result after transformation:"); System.out.println("============================"); - Document document = transformInputStreamToDocument( - createTransformerFromInputstream(new ByteArrayInputStream(xsl.getBytes())), - new ByteArrayInputStream(sourceXml.getBytes())); OutputFormat format = new OutputFormat(); format.setIndenting(true); new XMLSerializer(System.out, format).serialize(document); @@ -438,4 +435,38 @@ checkNodeNS8162598(document.getElementsByTagName("test5").item(0), "ns1", "ns1", null); Assert.assertNull(document.getElementsByTagName("test6").item(0).getNamespaceURI(), "unexpected namespace for test6"); } + + /** + * @bug 8169772 + * @summary Test transformation of DOM with null valued text node + * + * This test would throw a NullPointerException during transform when the + * fix was not present. + */ + @Test + public final void testBug8169772() throws ParserConfigurationException, + SAXException, IOException, TransformerException + { + // create a small DOM + Document doc = DocumentBuilderFactory.newInstance(). + newDocumentBuilder().parse( + new ByteArrayInputStream( + "".getBytes() + ) + ); + + // insert a bad element + Element e = doc.createElement("ERROR"); + e.appendChild(doc.createTextNode(null)); + doc.getDocumentElement().appendChild(e); + + // transform + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + TransformerFactory.newInstance().newTransformer().transform( + new DOMSource(doc.getDocumentElement()), new StreamResult(bos) + ); + System.out.println("Transformation result (DOM with null text node):"); + System.out.println("================================================"); + System.out.println(bos); + } } diff -r 183ae2332dd9 -r f4e854a77aa3 jaxws/.hgtags --- a/jaxws/.hgtags Wed Jul 05 22:29:12 2017 +0200 +++ b/jaxws/.hgtags Wed Jul 05 22:30:52 2017 +0200 @@ -391,3 +391,4 @@ 1c988e708a06257119d54d8a57e99e3b0f37ff18 jdk-9+143 92523c51d6a48b0a83912ba3cc43bc57b8159c2a jdk-9+144 29277a4e73077269358859c43bd6658593fc0410 jdk-9+145 +1461e3e07876ea61bd0a07355a43912c9b04022a jdk-9+146 diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/.hgtags --- a/jdk/.hgtags Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/.hgtags Wed Jul 05 22:30:52 2017 +0200 @@ -388,3 +388,4 @@ 8dbc8594f9d5149bf1c22221272284609408227a jdk-9+143 efa71dc820eb8bd5a6c9f2f66f39c383ac3ee99d jdk-9+144 99b7853cfbd8227c4441de4b6119c10742556840 jdk-9+145 +6e4ff59afb5d0adf21a72c4ff534326594a99e5d jdk-9+146 diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/make/copy/Copy-java.base.gmk --- a/jdk/make/copy/Copy-java.base.gmk Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/make/copy/Copy-java.base.gmk Wed Jul 05 22:30:52 2017 +0200 @@ -181,6 +181,7 @@ DEF_POLICY_DST := $(LIB_DST_DIR)/security/default.policy DEF_POLICY_SRC_LIST := $(DEF_POLICY_SRC) +DEF_POLICY_SRC_LIST += $(CUSTOM_POLICY_SRC_LIST) ifneq ($(filter $(OPENJDK_TARGET_OS), windows solaris), ) DEF_POLICY_SRC_LIST += $(JDK_TOPDIR)/src/java.base/$(OPENJDK_TARGET_OS)/lib/security/default.policy diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/make/copy/Copy-jdk.accessibility.gmk --- a/jdk/make/copy/Copy-jdk.accessibility.gmk Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/make/copy/Copy-jdk.accessibility.gmk Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright (c) 2104, 2015, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2104, 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 @@ -30,8 +30,7 @@ ifeq ($(OPENJDK_TARGET_OS), windows) TARGETS += $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCallbacks.h \ $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCalls.h \ - $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgePackages.h \ - $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgeCalls.c + $(INCLUDE_DST_OS_DIR)/bridge/AccessBridgePackages.h $(INCLUDE_DST_OS_DIR)/bridge/%: \ $(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge/% diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/make/launcher/Launcher-jdk.accessibility.gmk --- a/jdk/make/launcher/Launcher-jdk.accessibility.gmk Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/make/launcher/Launcher-jdk.accessibility.gmk Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2014, 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 @@ -71,7 +71,7 @@ $$(eval $$(call SetupNativeCompilation, BUILD_JACCESSINSPECTOR$1, \ SRC := $(TOPDIR)/jaccessinspector $(TOPDIR)/common \ - $(TOPDIR)/toolscommon $(TOPDIR)/include/bridge, \ + $(TOPDIR)/toolscommon $(TOPDIR)/bridge, \ CFLAGS := $$(CFLAGS_JDKEXE) $(TOOLS_CFLAGS) -DACCESSBRIDGE_ARCH_$2 -EHsc, \ LDFLAGS := $$(LDFLAGS_JDKEXE) -stack:655360, \ LIBS := advapi32.lib user32.lib, \ @@ -98,7 +98,7 @@ $$(eval $$(call SetupNativeCompilation,BUILD_JACCESSWALKER$1, \ SRC := $(TOPDIR)/jaccesswalker $(TOPDIR)/common \ - $(TOPDIR)/toolscommon $(TOPDIR)/include/bridge, \ + $(TOPDIR)/toolscommon $(TOPDIR)/bridge, \ CFLAGS := $$(CFLAGS_JDKEXE) $(TOOLS_CFLAGS) -DACCESSBRIDGE_ARCH_$2 -EHsc, \ LDFLAGS := $$(LDFLAGS_JDKEXE) -stack:655360, \ LIBS := advapi32.lib comctl32.lib gdi32.lib user32.lib, \ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/make/lib/Awt2dLibraries.gmk --- a/jdk/make/lib/Awt2dLibraries.gmk Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/make/lib/Awt2dLibraries.gmk Wed Jul 05 22:30:52 2017 +0200 @@ -356,7 +356,7 @@ $(X_CFLAGS), \ WARNINGS_AS_ERRORS_xlc := false, \ DISABLED_WARNINGS_gcc := type-limits pointer-to-int-cast \ - deprecated-declarations unused-result maybe-uninitialized format \ + unused-result maybe-uninitialized format \ format-security int-to-pointer-cast parentheses, \ DISABLED_WARNINGS_solstudio := E_DECLARATION_IN_CODE \ E_ASSIGNMENT_TYPE_MISMATCH E_NON_CONST_INIT, \ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/make/lib/Lib-jdk.accessibility.gmk --- a/jdk/make/lib/Lib-jdk.accessibility.gmk Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/make/lib/Lib-jdk.accessibility.gmk Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ # -# Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2014, 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 @@ -48,7 +48,7 @@ OPTIMIZATION := LOW, \ CFLAGS := $(CFLAGS_JDKLIB) $(ACCESSBRIDGE_CFLAGS) \ $(addprefix -I,$(JAVA_AB_SRCDIR)) \ - -I$(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge \ + -I$(ROOT_SRCDIR)/include/bridge \ -DACCESSBRIDGE_ARCH_$2, \ LDFLAGS := $(LDFLAGS_JDKLIB) -subsystem:windows, \ LIBS := kernel32.lib user32.lib gdi32.lib \ @@ -78,7 +78,7 @@ OPTIMIZATION := LOW, \ CFLAGS := $(filter-out -MD, $(CFLAGS_JDKLIB)) -MT $(ACCESSBRIDGE_CFLAGS) \ $(addprefix -I,$(WIN_AB_SRCDIR)) \ - -I$(JDK_TOPDIR)/src/jdk.accessibility/windows/native/include/bridge \ + -I$(ROOT_SRCDIR)/include/bridge \ -DACCESSBRIDGE_ARCH_$2, \ LDFLAGS := $(LDFLAGS_JDKLIB) -subsystem:windows \ -def:$(ROOT_SRCDIR)/libwindowsaccessbridge/WinAccessBridge.DEF, \ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/io/ObjectInputFilter.java --- a/jdk/src/java.base/share/classes/java/io/ObjectInputFilter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/io/ObjectInputFilter.java Wed Jul 05 22:30:52 2017 +0200 @@ -194,11 +194,17 @@ * When setting the filter, it should be stateless and idempotent, * reporting the same result when passed the same arguments. *

- * The filter is configured using the {@link java.security.Security} - * property {@code jdk.serialFilter} and can be overridden by - * the System property {@code jdk.serialFilter}. - * - * The syntax is the same as for the {@link #createFilter(String) createFilter} method. + * The filter is configured during the initialization of the {@code ObjectInputFilter.Config} + * class. For example, by calling {@link #getSerialFilter() Config.getSerialFilter}. + * If the system property {@code jdk.serialFilter} is defined, it is used + * to configure the filter. + * If the system property is not defined, and the {@link java.security.Security} + * property {@code jdk.serialFilter} is defined then it is used to configure the filter. + * Otherwise, the filter is not configured during initialization. + * The syntax for each property is the same as for the + * {@link #createFilter(String) createFilter} method. + * If a filter is not configured, it can be set with + * {@link #setSerialFilter(ObjectInputFilter) Config.setSerialFilter}. * * @since 9 */ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/lang/CharSequence.java --- a/jdk/src/java.base/share/classes/java/lang/CharSequence.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/lang/CharSequence.java Wed Jul 05 22:30:52 2017 +0200 @@ -121,8 +121,11 @@ * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code * point is passed through uninterpreted. * - *

If the sequence is mutated while the stream is being read, the - * result is undefined. + *

The stream binds to this sequence when the terminal stream operation + * commences (specifically, for mutable sequences the spliterator for the + * stream is late-binding). + * If the sequence is modified during that operation then the result is + * undefined. * * @return an IntStream of char values from this sequence * @since 1.8 @@ -168,8 +171,11 @@ * unpaired surrogates, and undefined code units, are zero-extended to * {@code int} values which are then passed to the stream. * - *

If the sequence is mutated while the stream is being read, the result - * is undefined. + *

The stream binds to this sequence when the terminal stream operation + * commences (specifically, for mutable sequences the spliterator for the + * stream is late-binding). + * If the sequence is modified during that operation then the result is + * undefined. * * @return an IntStream of Unicode code points from this sequence * @since 1.8 diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/lang/Class.java --- a/jdk/src/java.base/share/classes/java/lang/Class.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/lang/Class.java Wed Jul 05 22:30:52 2017 +0200 @@ -2704,9 +2704,6 @@ * Reflection support. */ - // Caches for certain reflective results - private static boolean useCaches = true; - // reflection data that might get invalidated when JVM TI RedefineClasses() is called private static class ReflectionData { volatile Field[] declaredFields; @@ -2739,8 +2736,7 @@ SoftReference> reflectionData = this.reflectionData; int classRedefinedCount = this.classRedefinedCount; ReflectionData rd; - if (useCaches && - reflectionData != null && + if (reflectionData != null && (rd = reflectionData.get()) != null && rd.redefinedCount == classRedefinedCount) { return rd; @@ -2752,8 +2748,6 @@ private ReflectionData newReflectionData(SoftReference> oldReflectionData, int classRedefinedCount) { - if (!useCaches) return null; - while (true) { ReflectionData rd = new ReflectionData<>(classRedefinedCount); // try to CAS it... @@ -2819,7 +2813,6 @@ // be propagated to the outside world, but must instead be copied // via ReflectionFactory.copyField. private Field[] privateGetDeclaredFields(boolean publicOnly) { - checkInitted(); Field[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -2842,7 +2835,6 @@ // be propagated to the outside world, but must instead be copied // via ReflectionFactory.copyField. private Field[] privateGetPublicFields(Set> traversedInterfaces) { - checkInitted(); Field[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -2902,7 +2894,6 @@ // objects must NOT be propagated to the outside world, but must // instead be copied via ReflectionFactory.copyConstructor. private Constructor[] privateGetDeclaredConstructors(boolean publicOnly) { - checkInitted(); Constructor[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -2937,7 +2928,6 @@ // be propagated to the outside world, but must instead be copied // via ReflectionFactory.copyMethod. private Method[] privateGetDeclaredMethods(boolean publicOnly) { - checkInitted(); Method[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -3134,7 +3124,6 @@ // be propagated to the outside world, but must instead be copied // via ReflectionFactory.copyMethod. private Method[] privateGetPublicMethods() { - checkInitted(); Method[] res; ReflectionData rd = reflectionData(); if (rd != null) { @@ -3445,7 +3434,7 @@ * @since 1.4 */ public boolean desiredAssertionStatus() { - ClassLoader loader = getClassLoader(); + ClassLoader loader = getClassLoader0(); // If the loader is null this is a system class, so ask the VM if (loader == null) return desiredAssertionStatus0(this); @@ -3490,39 +3479,6 @@ } private static ReflectionFactory reflectionFactory; - // To be able to query system properties as soon as they're available - private static boolean initted = false; - private static void checkInitted() { - if (initted) return; - AccessController.doPrivileged(new PrivilegedAction<>() { - public Void run() { - // Tests to ensure the system properties table is fully - // initialized. This is needed because reflection code is - // called very early in the initialization process (before - // command-line arguments have been parsed and therefore - // these user-settable properties installed.) We assume that - // if System.out is non-null then the System class has been - // fully initialized and that the bulk of the startup code - // has been run. - - if (System.out == null) { - // java.lang.System not yet fully initialized - return null; - } - - // Doesn't use Boolean.getBoolean to avoid class init. - String val = - System.getProperty("sun.reflect.noCaches"); - if (val != null && val.equals("true")) { - useCaches = false; - } - - initted = true; - return null; - } - }); - } - /** * Returns the elements of this enum class or null if this * Class object does not represent an enum type. diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/lang/ClassLoader.java --- a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java Wed Jul 05 22:30:52 2017 +0200 @@ -104,9 +104,9 @@ * class or resource itself. * *

Class loaders that support concurrent loading of classes are known as - * {@linkplain #isParallelCapable() parallel capable} class loaders and - * are required to register themselves at their class initialization time by - * invoking the {@link + * {@linkplain #isRegisteredAsParallelCapable() parallel capable} class + * loaders and are required to register themselves at their class initialization + * time by invoking the {@link * #registerAsParallelCapable ClassLoader.registerAsParallelCapable} * method. Note that the ClassLoader class is registered as parallel * capable by default. However, its subclasses still need to register themselves @@ -1335,10 +1335,12 @@ * @return A URL object for reading the resource, or * null if the resource could not be found or the invoker * doesn't have adequate privileges to get the resource. + * @throws NullPointerException If {@code name} is {@code null} * * @since 1.1 */ public URL getResource(String name) { + Objects.requireNonNull(name); URL url; if (parent != null) { url = parent.getResource(name); @@ -1382,12 +1384,14 @@ * * @throws IOException * If I/O errors occur + * @throws NullPointerException If {@code name} is {@code null} * * @see #findResources(String) * * @since 1.2 */ public Enumeration getResources(String name) throws IOException { + Objects.requireNonNull(name); @SuppressWarnings("unchecked") Enumeration[] tmp = (Enumeration[]) new Enumeration[2]; if (parent != null) { @@ -1434,11 +1438,14 @@ * that the class loader doesn't have access to will not be in the * stream. * + * @throws NullPointerException If {@code name} is {@code null} + * * @see #findResources(String) * * @since 9 */ public Stream resources(String name) { + Objects.requireNonNull(name); int characteristics = Spliterator.NONNULL | Spliterator.IMMUTABLE; Supplier> si = () -> { try { @@ -1495,7 +1502,8 @@ } /** - * Registers the caller as {@linkplain #isParallelCapable() parallel capable}. + * Registers the caller as + * {@linkplain #isRegisteredAsParallelCapable() parallel capable}. * The registration succeeds if and only if all of the following * conditions are met: *

    @@ -1509,7 +1517,7 @@ * @return {@code true} if the caller is successfully registered as * parallel capable and {@code false} if otherwise. * - * @see #isParallelCapable() + * @see #isRegisteredAsParallelCapable() * * @since 1.7 */ @@ -1521,7 +1529,7 @@ } /** - * Returns {@code true} if this class loader is + * Returns {@code true} if this class loader is registered as * {@linkplain #registerAsParallelCapable parallel capable}, otherwise * {@code false}. * @@ -1532,7 +1540,7 @@ * * @since 9 */ - public final boolean isParallelCapable() { + public final boolean isRegisteredAsParallelCapable() { return ParallelLoaders.isRegistered(this.getClass()); } @@ -1599,10 +1607,12 @@ * * @return An input stream for reading the resource, or null * if the resource could not be found + * @throws NullPointerException If {@code name} is {@code null} * * @since 1.1 */ public InputStream getResourceAsStream(String name) { + Objects.requireNonNull(name); URL url = getResource(name); try { return url != null ? url.openStream() : null; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java --- a/jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java Wed Jul 05 22:30:52 2017 +0200 @@ -200,7 +200,8 @@ } /** - * {@inheritDoc} + * Returns the {@code Class} object representing the class that + * declares the constructor represented by this object. */ @Override public Class getDeclaringClass() { @@ -321,6 +322,11 @@ * public java.util.Hashtable(int,float) * } * + *

    If the constructor is declared to throw exceptions, the + * parameter list is followed by a space, followed by the word + * "{@code throws}" followed by a comma-separated list of the + * thrown exception types. + * *

    The only possible modifiers for constructors are the access * modifiers {@code public}, {@code protected} or * {@code private}. Only one of these may appear, or none if the @@ -357,13 +363,13 @@ * "Type...". * * A space is used to separate access modifiers from one another - * and from the type parameters or return type. If there are no + * and from the type parameters or class name. If there are no * type parameters, the type parameter list is elided; if the type * parameter list is present, a space separates the list from the * class name. If the constructor is declared to throw * exceptions, the parameter list is followed by a space, followed * by the word "{@code throws}" followed by a - * comma-separated list of the thrown exception types. + * comma-separated list of the generic thrown exception types. * *

    The only possible modifiers for constructors are the access * modifiers {@code public}, {@code protected} or diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/lang/reflect/Method.java --- a/jdk/src/java.base/share/classes/java/lang/reflect/Method.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/lang/reflect/Method.java Wed Jul 05 22:30:52 2017 +0200 @@ -211,7 +211,8 @@ } /** - * {@inheritDoc} + * Returns the {@code Class} object representing the class or interface + * that declares the method represented by this object. */ @Override public Class getDeclaringClass() { @@ -372,7 +373,7 @@ * the method name, followed by a parenthesized, comma-separated * list of the method's formal parameter types. If the method * throws checked exceptions, the parameter list is followed by a - * space, followed by the word throws followed by a + * space, followed by the word "{@code throws}" followed by a * comma-separated list of the thrown exception types. * For example: *

    @@ -428,8 +429,8 @@
          * parameter list is present, a space separates the list from the
          * class name.  If the method is declared to throw exceptions, the
          * parameter list is followed by a space, followed by the word
    -     * throws followed by a comma-separated list of the generic thrown
    -     * exception types.
    +     * "{@code throws}" followed by a comma-separated list of the generic
    +     * thrown exception types.
          *
          * 

    The access modifiers are placed in canonical order as * specified by "The Java Language Specification". This is diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/net/Authenticator.java --- a/jdk/src/java.base/share/classes/java/net/Authenticator.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/net/Authenticator.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -131,6 +131,35 @@ } /** + * Gets the default authenticator. + * First, if there is a security manager, its {@code checkPermission} + * method is called with a + * {@code NetPermission("requestPasswordAuthentication")} permission. + * This may result in a java.lang.SecurityException. + * Then the default authenticator, if set, is returned. + * Otherwise, {@code null} is returned. + * + * @return The default authenticator, if set, {@code null} otherwise. + * + * @throws SecurityException + * if a security manager exists and its + * {@code checkPermission} method doesn't allow + * requesting password authentication. + * @since 9 + * @see SecurityManager#checkPermission + * @see java.net.NetPermission + */ + public static Authenticator getDefault() { + SecurityManager sm = System.getSecurityManager(); + if (sm != null) { + NetPermission requestPermission + = new NetPermission("requestPasswordAuthentication"); + sm.checkPermission(requestPermission); + } + return theAuthenticator; + } + + /** * Ask the authenticator that has been registered with the system * for a password. *

    diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/net/URLClassLoader.java --- a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java Wed Jul 05 22:30:52 2017 +0200 @@ -42,6 +42,7 @@ import java.util.Enumeration; import java.util.List; import java.util.NoSuchElementException; +import java.util.Objects; import java.util.Set; import java.util.WeakHashMap; import java.util.jar.Attributes; @@ -301,9 +302,12 @@ * @return An input stream for reading the resource, or {@code null} * if the resource could not be found * + * @throws NullPointerException If {@code name} is {@code null} + * * @since 1.7 */ public InputStream getResourceAsStream(String name) { + Objects.requireNonNull(name); URL url = getResource(name); try { if (url == null) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/security/ProtectionDomain.java --- a/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java Wed Jul 05 22:30:52 2017 +0200 @@ -32,6 +32,7 @@ import java.util.ArrayList; import java.util.Enumeration; import java.util.List; +import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import jdk.internal.misc.JavaSecurityAccess; import jdk.internal.misc.JavaSecurityProtectionDomainAccess; @@ -524,7 +525,7 @@ // have some side effects so this manual // comparison is sufficient. if (pdpName.equals(pp.getName()) && - pdpActions.equals(pp.getActions())) { + Objects.equals(pdpActions, pp.getActions())) { plVector.remove(i); break; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/security/SecureRandom.java --- a/jdk/src/java.base/share/classes/java/security/SecureRandom.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/security/SecureRandom.java Wed Jul 05 22:30:52 2017 +0200 @@ -120,6 +120,24 @@ * gathered, for example, if the entropy source is /dev/random on various * Unix-like operating systems. * + *

    Thread safety

    + * {@code SecureRandom} objects are safe for use by multiple concurrent threads. + * + * @implSpec + * A {@code SecureRandom} service provider can advertise that it is thread-safe + * by setting the service + * provider attribute "ThreadSafe" to "true" when registering the provider. + * Otherwise, this class will instead synchronize access to the following + * methods of the {@code SecureRandomSpi} implementation: + *
      + *
    • {@link SecureRandomSpi#engineSetSeed(byte[])} + *
    • {@link SecureRandomSpi#engineNextBytes(byte[])} + *
    • {@link SecureRandomSpi#engineNextBytes(byte[], SecureRandomParameters)} + *
    • {@link SecureRandomSpi#engineGenerateSeed(int)} + *
    • {@link SecureRandomSpi#engineReseed(SecureRandomParameters)} + *
    + * * @see java.security.SecureRandomSpi * @see java.util.Random * @@ -150,6 +168,14 @@ */ private SecureRandomSpi secureRandomSpi = null; + /** + * Thread safety. + * + * @serial + * @since 9 + */ + private final boolean threadSafe; + /* * The algorithm name of null if unknown. * @@ -189,6 +215,16 @@ */ super(0); getDefaultPRNG(false, null); + this.threadSafe = getThreadSafe(); + } + + private boolean getThreadSafe() { + if (provider == null || algorithm == null) { + return false; + } else { + return Boolean.parseBoolean(provider.getProperty( + "SecureRandom." + algorithm + " ThreadSafe", "false")); + } } /** @@ -217,6 +253,7 @@ public SecureRandom(byte[] seed) { super(0); getDefaultPRNG(true, seed); + this.threadSafe = getThreadSafe(); } private void getDefaultPRNG(boolean setSeed, byte[] seed) { @@ -269,6 +306,7 @@ this.secureRandomSpi = secureRandomSpi; this.provider = provider; this.algorithm = algorithm; + this.threadSafe = getThreadSafe(); if (!skipDebug && pdebug != null) { pdebug.println("SecureRandom." + algorithm + @@ -653,8 +691,14 @@ * * @see #getSeed */ - public synchronized void setSeed(byte[] seed) { - secureRandomSpi.engineSetSeed(seed); + public void setSeed(byte[] seed) { + if (threadSafe) { + secureRandomSpi.engineSetSeed(seed); + } else { + synchronized (this) { + secureRandomSpi.engineSetSeed(seed); + } + } } /** @@ -679,7 +723,7 @@ * yet been initialized at that point. */ if (seed != 0) { - this.secureRandomSpi.engineSetSeed(longToByteArray(seed)); + setSeed(longToByteArray(seed)); } } @@ -690,7 +734,13 @@ */ @Override public void nextBytes(byte[] bytes) { - secureRandomSpi.engineNextBytes(bytes); + if (threadSafe) { + secureRandomSpi.engineNextBytes(bytes); + } else { + synchronized (this) { + secureRandomSpi.engineNextBytes(bytes); + } + } } /** @@ -707,12 +757,19 @@ * * @since 9 */ - public synchronized void nextBytes( - byte[] bytes, SecureRandomParameters params) { + public void nextBytes(byte[] bytes, SecureRandomParameters params) { if (params == null) { throw new IllegalArgumentException("params cannot be null"); } - secureRandomSpi.engineNextBytes(Objects.requireNonNull(bytes), params); + if (threadSafe) { + secureRandomSpi.engineNextBytes( + Objects.requireNonNull(bytes), params); + } else { + synchronized (this) { + secureRandomSpi.engineNextBytes( + Objects.requireNonNull(bytes), params); + } + } } /** @@ -756,6 +813,7 @@ * * @param numBytes the number of seed bytes to generate. * + * @throws IllegalArgumentException if {@code numBytes} is negative * @return the seed bytes. * * @see #setSeed @@ -782,7 +840,13 @@ if (numBytes < 0) { throw new IllegalArgumentException("numBytes cannot be negative"); } - return secureRandomSpi.engineGenerateSeed(numBytes); + if (threadSafe) { + return secureRandomSpi.engineGenerateSeed(numBytes); + } else { + synchronized (this) { + return secureRandomSpi.engineGenerateSeed(numBytes); + } + } } /** @@ -917,8 +981,14 @@ * * @since 9 */ - public synchronized void reseed() { - secureRandomSpi.engineReseed(null); + public void reseed() { + if (threadSafe) { + secureRandomSpi.engineReseed(null); + } else { + synchronized (this) { + secureRandomSpi.engineReseed(null); + } + } } /** @@ -937,11 +1007,17 @@ * * @since 9 */ - public synchronized void reseed(SecureRandomParameters params) { + public void reseed(SecureRandomParameters params) { if (params == null) { throw new IllegalArgumentException("params cannot be null"); } - secureRandomSpi.engineReseed(params); + if (threadSafe) { + secureRandomSpi.engineReseed(params); + } else { + synchronized (this) { + secureRandomSpi.engineReseed(params); + } + } } // Declare serialVersionUID to be compatible with JDK1.1 diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/security/SecureRandomSpi.java --- a/jdk/src/java.base/share/classes/java/security/SecureRandomSpi.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/security/SecureRandomSpi.java Wed Jul 05 22:30:52 2017 +0200 @@ -58,6 +58,26 @@ * a {@code SecureRandomParameters} argument will never * return an instance of this implementation. The * {@link #engineGetParameters()} method must return {@code null}. + *

    + * See {@link SecureRandom} for additional details on thread safety. By + * default, a {@code SecureRandomSpi} implementation is considered to be + * not safe for use by multiple concurrent threads and {@code SecureRandom} + * will synchronize access to each of the applicable engine methods + * (see {@link SecureRandom} for the list of methods). However, if a + * {@code SecureRandomSpi} implementation is thread-safe, the + * service provider attribute "ThreadSafe" should be set to "true" during + * its registration, as follows: + *

    + * put("SecureRandom.AlgName ThreadSafe", "true");
    + *
    + * or + *
    + * putService(new Service(this, "SecureRandom", "AlgName", className,
    + *          null, Map.of("ThreadSafe", "true")));
    + *
    + * {@code SecureRandom} will call the applicable engine methods + * without any synchronization. * * @since 1.2 */ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/time/ZoneId.java --- a/jdk/src/java.base/share/classes/java/time/ZoneId.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/time/ZoneId.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -76,6 +76,7 @@ import java.time.zone.ZoneRules; import java.time.zone.ZoneRulesException; import java.time.zone.ZoneRulesProvider; +import java.util.HashSet; import java.util.Locale; import java.util.Map; import java.util.Objects; @@ -284,7 +285,7 @@ * @return a modifiable copy of the set of zone IDs, not null */ public static Set getAvailableZoneIds() { - return ZoneRulesProvider.getAvailableZoneIds(); + return new HashSet(ZoneRulesProvider.getAvailableZoneIds()); } //----------------------------------------------------------------------- diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/time/format/DateTimePrintContext.java --- a/jdk/src/java.base/share/classes/java/time/format/DateTimePrintContext.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/time/format/DateTimePrintContext.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -302,14 +302,10 @@ * @throws DateTimeException if the field is not available and the section is not optional */ Long getValue(TemporalField field) { - try { - return temporal.getLong(field); - } catch (DateTimeException ex) { - if (optional > 0) { - return null; - } - throw ex; + if (optional > 0 && !temporal.isSupported(field)) { + return null; } + return temporal.getLong(field); } //----------------------------------------------------------------------- diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/time/zone/ZoneRulesProvider.java --- a/jdk/src/java.base/share/classes/java/time/zone/ZoneRulesProvider.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/time/zone/ZoneRulesProvider.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -77,6 +77,7 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.Collections; /** * Provider of time-zone rules to the system. @@ -137,6 +138,11 @@ */ private static final ConcurrentMap ZONES = new ConcurrentHashMap<>(512, 0.75f, 2); + /** + * The zone ID data + */ + private static volatile Set ZONE_IDS; + static { // if the property java.time.zone.DefaultZoneRulesProvider is // set then its value is the class name of the default provider @@ -194,10 +200,10 @@ *

    * These IDs are the string form of a {@link ZoneId}. * - * @return a modifiable copy of the set of zone IDs, not null + * @return the unmodifiable set of zone IDs, not null */ public static Set getAvailableZoneIds() { - return new HashSet<>(ZONES.keySet()); + return ZONE_IDS; } /** @@ -303,7 +309,7 @@ * @param provider the provider to register, not null * @throws ZoneRulesException if unable to complete the registration */ - private static void registerProvider0(ZoneRulesProvider provider) { + private static synchronized void registerProvider0(ZoneRulesProvider provider) { for (String zoneId : provider.provideZoneIds()) { Objects.requireNonNull(zoneId, "zoneId"); ZoneRulesProvider old = ZONES.putIfAbsent(zoneId, provider); @@ -313,6 +319,8 @@ ", currently loading from provider: " + provider); } } + Set combinedSet = new HashSet(ZONES.keySet()); + ZONE_IDS = Collections.unmodifiableSet(combinedSet); } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/util/BitSet.java --- a/jdk/src/java.base/share/classes/java/util/BitSet.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/util/BitSet.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -29,6 +29,7 @@ import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.LongBuffer; +import java.util.function.IntConsumer; import java.util.stream.IntStream; import java.util.stream.StreamSupport; @@ -1209,40 +1210,165 @@ * is the number of bits in the set state, equal to the value * returned by the {@link #cardinality()} method. * - *

    The bit set must remain constant during the execution of the - * terminal stream operation. Otherwise, the result of the terminal - * stream operation is undefined. + *

    The stream binds to this bit set when the terminal stream operation + * commences (specifically, the spliterator for the stream is + * late-binding). If the + * bit set is modified during that operation then the result is undefined. * * @return a stream of integers representing set indices * @since 1.8 */ public IntStream stream() { - class BitSetIterator implements PrimitiveIterator.OfInt { - int next = nextSetBit(0); + class BitSetSpliterator implements Spliterator.OfInt { + private int index; // current bit index for a set bit + private int fence; // -1 until used; then one past last bit index + private int est; // size estimate + private boolean root; // true if root and not split + // root == true then size estimate is accurate + // index == -1 or index >= fence if fully traversed + // Special case when the max bit set is Integer.MAX_VALUE + + BitSetSpliterator(int origin, int fence, int est, boolean root) { + this.index = origin; + this.fence = fence; + this.est = est; + this.root = root; + } + + private int getFence() { + int hi; + if ((hi = fence) < 0) { + // Round up fence to maximum cardinality for allocated words + // This is sufficient and cheap for sequential access + // When splitting this value is lowered + hi = fence = (wordsInUse >= wordIndex(Integer.MAX_VALUE)) + ? Integer.MAX_VALUE + : wordsInUse << ADDRESS_BITS_PER_WORD; + est = cardinality(); + index = nextSetBit(0); + } + return hi; + } @Override - public boolean hasNext() { - return next != -1; + public boolean tryAdvance(IntConsumer action) { + Objects.requireNonNull(action); + + int hi = getFence(); + int i = index; + if (i < 0 || i >= hi) { + // Check if there is a final bit set for Integer.MAX_VALUE + if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) { + index = -1; + action.accept(Integer.MAX_VALUE); + return true; + } + return false; + } + + index = nextSetBit(i + 1, wordIndex(hi - 1)); + action.accept(i); + return true; + } + + @Override + public void forEachRemaining(IntConsumer action) { + Objects.requireNonNull(action); + + int hi = getFence(); + int i = index; + int v = wordIndex(hi - 1); + index = -1; + while (i >= 0 && i < hi) { + action.accept(i); + i = nextSetBit(i + 1, v); + } + // Check if there is a final bit set for Integer.MAX_VALUE + if (i == Integer.MAX_VALUE && hi == Integer.MAX_VALUE) { + action.accept(Integer.MAX_VALUE); + } } @Override - public int nextInt() { - if (next != -1) { - int ret = next; - next = (next == Integer.MAX_VALUE) ? -1 : nextSetBit(next+1); - return ret; - } else { - throw new NoSuchElementException(); + public OfInt trySplit() { + int hi = getFence(); + int lo = index; + if (lo < 0) { + return null; + } + + // Lower the fence to be the upper bound of last bit set + // The index is the first bit set, thus this spliterator + // covers one bit and cannot be split, or two or more + // bits + hi = fence = (hi < Integer.MAX_VALUE || !get(Integer.MAX_VALUE)) + ? previousSetBit(hi - 1) + 1 + : Integer.MAX_VALUE; + + // Find the mid point + int mid = (lo + hi) >>> 1; + if (lo >= mid) { + return null; } + + // Raise the index of this spliterator to be the next set bit + // from the mid point + index = nextSetBit(mid, wordIndex(hi - 1)); + root = false; + + // Don't lower the fence (mid point) of the returned spliterator, + // traversal or further splitting will do that work + return new BitSetSpliterator(lo, mid, est >>>= 1, false); + } + + @Override + public long estimateSize() { + getFence(); // force init + return est; + } + + @Override + public int characteristics() { + // Only sized when root and not split + return (root ? Spliterator.SIZED : 0) | + Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED; + } + + @Override + public Comparator getComparator() { + return null; } } + return StreamSupport.intStream(new BitSetSpliterator(0, -1, 0, true), false); + } - return StreamSupport.intStream( - () -> Spliterators.spliterator( - new BitSetIterator(), cardinality(), - Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED), - Spliterator.SIZED | Spliterator.SUBSIZED | - Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED, - false); + /** + * Returns the index of the first bit that is set to {@code true} + * that occurs on or after the specified starting index and up to and + * including the specified word index + * If no such bit exists then {@code -1} is returned. + * + * @param fromIndex the index to start checking from (inclusive) + * @param toWordIndex the last word index to check (inclusive) + * @return the index of the next set bit, or {@code -1} if there + * is no such bit + */ + private int nextSetBit(int fromIndex, int toWordIndex) { + int u = wordIndex(fromIndex); + // Check if out of bounds + if (u > toWordIndex) + return -1; + + long word = words[u] & (WORD_MASK << fromIndex); + + while (true) { + if (word != 0) + return (u * BITS_PER_WORD) + Long.numberOfTrailingZeros(word); + // Check if out of bounds + if (++u > toWordIndex) + return -1; + word = words[u]; + } } + } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/util/PriorityQueue.java --- a/jdk/src/java.base/share/classes/java/util/PriorityQueue.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/util/PriorityQueue.java Wed Jul 05 22:30:52 2017 +0200 @@ -54,7 +54,8 @@ *

    This class and its iterator implement all of the * optional methods of the {@link Collection} and {@link * Iterator} interfaces. The Iterator provided in method {@link - * #iterator()} is not guaranteed to traverse the elements of + * #iterator()} and the Spliterator provided in method {@link #spliterator()} + * are not guaranteed to traverse the elements of * the priority queue in any particular order. If you need ordered * traversal, consider using {@code Arrays.sort(pq.toArray())}. * @@ -799,7 +800,8 @@ /** * Creates a late-binding * and fail-fast {@link Spliterator} over the elements in this - * queue. + * queue. The spliterator does not traverse elements in any particular order + * (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported). * *

    The {@code Spliterator} reports {@link Spliterator#SIZED}, * {@link Spliterator#SUBSIZED}, and {@link Spliterator#NONNULL}. diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/util/concurrent/PriorityBlockingQueue.java --- a/jdk/src/java.base/share/classes/java/util/concurrent/PriorityBlockingQueue.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/util/concurrent/PriorityBlockingQueue.java Wed Jul 05 22:30:52 2017 +0200 @@ -65,7 +65,8 @@ *

    This class and its iterator implement all of the * optional methods of the {@link Collection} and {@link * Iterator} interfaces. The Iterator provided in method {@link - * #iterator()} is not guaranteed to traverse the elements of + * #iterator()} and the Spliterator provided in method {@link #spliterator()} + * are not guaranteed to traverse the elements of * the PriorityBlockingQueue in any particular order. If you need * ordered traversal, consider using * {@code Arrays.sort(pq.toArray())}. Also, method {@code drainTo} @@ -994,6 +995,8 @@ /** * Returns a {@link Spliterator} over the elements in this queue. + * The spliterator does not traverse elements in any particular order + * (the {@link Spliterator#ORDERED ORDERED} characteristic is not reported). * *

    The returned spliterator is * weakly consistent. diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/util/stream/Stream.java --- a/jdk/src/java.base/share/classes/java/util/stream/Stream.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/util/stream/Stream.java Wed Jul 05 22:30:52 2017 +0200 @@ -1327,7 +1327,7 @@ * @param s the {@code Supplier} of generated elements * @return a new infinite sequential unordered {@code Stream} */ - public static Stream generate(Supplier s) { + public static Stream generate(Supplier s) { Objects.requireNonNull(s); return StreamSupport.stream( new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/java/util/stream/StreamSpliterators.java --- a/jdk/src/java.base/share/classes/java/util/stream/StreamSpliterators.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/java/util/stream/StreamSpliterators.java Wed Jul 05 22:30:52 2017 +0200 @@ -1346,9 +1346,9 @@ } static final class OfRef extends InfiniteSupplyingSpliterator { - final Supplier s; + final Supplier s; - OfRef(long size, Supplier s) { + OfRef(long size, Supplier s) { super(size); this.s = s; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java --- a/jdk/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/jdk/internal/loader/ClassLoaders.java Wed Jul 05 22:30:52 2017 +0200 @@ -72,13 +72,13 @@ // If neither is specified then default to -cp // If -cp is not specified and -m is specified, the value of // java.class.path is an empty string, then no class path. - URLClassPath ucp = null; + URLClassPath ucp = new URLClassPath(new URL[0]); String mainMid = System.getProperty("jdk.module.main"); String cp = System.getProperty("java.class.path"); if (cp == null) cp = ""; if (mainMid == null || cp.length() > 0) - ucp = toURLClassPath(cp); + addClassPathToUCP(cp, ucp); // create the class loaders BOOT_LOADER = new BootClassLoader(bcp); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java --- a/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java Wed Jul 05 22:30:52 2017 +0200 @@ -462,6 +462,8 @@ * This method: * 1. Loads the main class from the module or class path * 2. Checks the public static void main method. + * 3. If the main class extends FX Application then call on FXHelper to + * perform the launch. * * @param printToStderr if set, all output will be routed to stderr * @param mode LaunchMode as determined by the arguments passed on the @@ -479,11 +481,23 @@ Class mainClass = (mode == LM_MODULE) ? loadModuleMainClass(what) : loadMainClass(mode, what); - validateMainClass(mainClass); + // record the real main class for UI purposes + // neither method above can return null, they will abort() + appClass = mainClass; - // record main class if not already set - if (appClass == null) - appClass = mainClass; + /* + * Check if FXHelper can launch it using the FX launcher. In an FX app, + * the main class may or may not have a main method, so do this before + * validating the main class. + */ + if (JAVAFX_FXHELPER_CLASS_NAME_SUFFIX.equals(mainClass.getName()) || + doesExtendFXApplication(mainClass)) { + // Will abort() if there are problems with FX runtime + FXHelper.setFXLaunchParameters(what, mode); + mainClass = FXHelper.class; + } + + validateMainClass(mainClass); return mainClass; } @@ -530,7 +544,6 @@ String cn = Normalizer.normalize(mainClass, Normalizer.Form.NFC); c = Class.forName(m, cn); - } if (c == null) { abort(null, "java.launcher.module.error2", mainClass, mainModule); @@ -542,8 +555,6 @@ /** * Loads the main class from the class path (LM_CLASS or LM_JAR). - * If the main class extends FX Application then call on FXHelper to - * determine the main class to launch. */ private static Class loadMainClass(int mode, String what) { // get the class name @@ -570,7 +581,7 @@ if (System.getProperty("os.name", "").contains("OS X") && Normalizer.isNormalized(cn, Normalizer.Form.NFD)) { try { - // On Mac OS X since all names with diacretic symbols are + // On Mac OS X since all names with diacritical marks are // given as decomposed it is possible that main class name // comes incorrectly from the command line and we have // to re-compose it @@ -583,21 +594,6 @@ abort(cnfe, "java.launcher.cls.error1", cn); } } - - // record the main class - appClass = mainClass; - - /* - * Check if FXHelper can launch it using the FX launcher. In an FX app, - * the main class may or may not have a main method, so do this before - * validating the main class. - */ - if (JAVAFX_FXHELPER_CLASS_NAME_SUFFIX.equals(mainClass.getName()) || - doesExtendFXApplication(mainClass)) { - // Will abort() if there are problems with FX runtime - FXHelper.setFXLaunchParameters(what, mode); - return FXHelper.class; - } return mainClass; } @@ -773,9 +769,15 @@ * java -cp somedir FXClass N/A LM_CLASS "LM_CLASS" * java -jar fxapp.jar Present LM_JAR "LM_JAR" * java -jar fxapp.jar Not Present LM_JAR "LM_JAR" + * java -m module/class [1] N/A LM_MODULE "LM_MODULE" + * java -m module N/A LM_MODULE "LM_MODULE" + * + * [1] - JavaFX-Application-Class is ignored when modular args are used, even + * if present in a modular jar */ private static final String JAVAFX_LAUNCH_MODE_CLASS = "LM_CLASS"; private static final String JAVAFX_LAUNCH_MODE_JAR = "LM_JAR"; + private static final String JAVAFX_LAUNCH_MODE_MODULE = "LM_MODULE"; /* * FX application launcher and launch method, so we can launch @@ -835,6 +837,9 @@ case LM_JAR: fxLaunchMode = JAVAFX_LAUNCH_MODE_JAR; break; + case LM_MODULE: + fxLaunchMode = JAVAFX_LAUNCH_MODE_MODULE; + break; default: // should not have gotten this far... throw new InternalError(mode + ": Unknown launch mode"); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java --- a/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java Wed Jul 05 22:30:52 2017 +0200 @@ -96,25 +96,32 @@ if (nativeAvailable && useNativePRNG) { map.put("SecureRandom.NativePRNG", "sun.security.provider.NativePRNG"); + map.put("SecureRandom.NativePRNG ThreadSafe", "true"); } map.put("SecureRandom.DRBG", "sun.security.provider.DRBG"); + map.put("SecureRandom.DRBG ThreadSafe", "true"); map.put("SecureRandom.SHA1PRNG", "sun.security.provider.SecureRandom"); + + map.put("SecureRandom.SHA1PRNG ThreadSafe", "true"); if (nativeAvailable && !useNativePRNG) { map.put("SecureRandom.NativePRNG", "sun.security.provider.NativePRNG"); + map.put("SecureRandom.NativePRNG ThreadSafe", "true"); } if (NativePRNG.Blocking.isAvailable()) { map.put("SecureRandom.NativePRNGBlocking", "sun.security.provider.NativePRNG$Blocking"); + map.put("SecureRandom.NativePRNGBlocking ThreadSafe", "true"); } if (NativePRNG.NonBlocking.isAvailable()) { map.put("SecureRandom.NativePRNGNonBlocking", "sun.security.provider.NativePRNG$NonBlocking"); + map.put("SecureRandom.NativePRNGNonBlocking ThreadSafe", "true"); } /* @@ -329,6 +336,7 @@ map.put("AlgorithmParameters.DSA ImplementedIn", "Software"); map.put("KeyFactory.DSA ImplementedIn", "Software"); map.put("SecureRandom.SHA1PRNG ImplementedIn", "Software"); + map.put("SecureRandom.DRBG ImplementedIn", "Software"); map.put("CertificateFactory.X.509 ImplementedIn", "Software"); map.put("KeyStore.JKS ImplementedIn", "Software"); map.put("CertPathValidator.PKIX ImplementedIn", "Software"); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java --- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -403,6 +403,13 @@ EnumSet.of(CryptoPrimitive.KEY_AGREEMENT), suite.name, null)) { suites.add(suite); + } else { + if (debug != null && Debug.isOn("sslctx") && + Debug.isOn("verbose")) { + System.out.println( + "Ignoring disabled cipher suite: " + + suite.name); + } } } else if (debug != null && Debug.isOn("sslctx") && Debug.isOn("verbose")) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java --- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLSessionImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -960,17 +960,6 @@ + "]"; } - /** - * When SSL sessions are finalized, all values bound to - * them are removed. - */ - @Override - protected void finalize() throws Throwable { - String[] names = getValueNames(); - for (int i = 0; i < names.length; i++) { - removeValue(names[i]); - } - } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.base/share/lib/security/default.policy --- a/jdk/src/java.base/share/lib/security/default.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.base/share/lib/security/default.policy Wed Jul 05 22:30:52 2017 +0200 @@ -155,7 +155,6 @@ grant codeBase "jrt:/jdk.localedata" { permission java.lang.RuntimePermission "accessClassInPackage.sun.text.*"; permission java.lang.RuntimePermission "accessClassInPackage.sun.util.*"; - permission java.util.PropertyPermission "*", "read"; }; grant codeBase "jrt:/jdk.naming.dns" { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java Wed Jul 05 22:30:52 2017 +0200 @@ -431,6 +431,7 @@ } @Override + @SuppressWarnings("deprecation") public void mouseReleased(final MouseEvent e) { if (didForwardEvent(e)) return; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldFormattedUI.java --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldFormattedUI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTextFieldFormattedUI.java Wed Jul 05 22:30:52 2017 +0200 @@ -55,6 +55,7 @@ super.uninstallListeners(); } + @SuppressWarnings("deprecation") public void mouseClicked(final MouseEvent e) { if (e.getClickCount() != 1) return; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java --- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaUtils.java Wed Jul 05 22:30:52 2017 +0200 @@ -176,11 +176,12 @@ } @Override + @SuppressWarnings("deprecation") T getInstance() { try { ReflectUtil.checkPackageAccess(clazz); return clazz.newInstance(); - } catch (InstantiationException | IllegalAccessException ignored) { + } catch (ReflectiveOperationException ignored) { } return null; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java --- a/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/sun/java2d/OSXSurfaceData.java Wed Jul 05 22:30:52 2017 +0200 @@ -672,7 +672,7 @@ TexturePaint color = (TexturePaint) sg2d.paint; this.fGraphicsStatesInt.put(kColorStateIndex, kColorTexture); texturePaintImage = color.getImage(); - SurfaceData textureSurfaceData = BufImgSurfaceData.createData(texturePaintImage); + SurfaceData textureSurfaceData = OSXOffScreenSurfaceData.createNewSurface(texturePaintImage); this.fGraphicsStatesInt.put(kColorWidthIndex, texturePaintImage.getWidth()); this.fGraphicsStatesInt.put(kColorHeightIndex, texturePaintImage.getHeight()); Rectangle2D anchor = color.getAnchorRect(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibleText.java --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibleText.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CAccessibleText.java Wed Jul 05 22:30:52 2017 +0200 @@ -293,6 +293,7 @@ }, c); } + @SuppressWarnings("deprecation") static int[] getVisibleCharacterRange(final Accessible a) { final Accessible sa = CAccessible.getSwingAccessible(a); if (!(sa instanceof JTextComponent)) return null; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDataTransferer.java Wed Jul 05 22:30:52 2017 +0200 @@ -38,6 +38,7 @@ import java.util.*; import java.util.regex.*; import java.awt.datatransfer.*; +import java.nio.charset.StandardCharsets; import sun.awt.datatransfer.*; public class CDataTransferer extends DataTransferer { @@ -132,7 +133,7 @@ String charset = Charset.defaultCharset().name(); if (transferable != null && transferable.isDataFlavorSupported(javaTextEncodingFlavor)) { try { - charset = new String((byte[]) transferable.getTransferData(javaTextEncodingFlavor), "UTF-8"); + charset = new String((byte[]) transferable.getTransferData(javaTextEncodingFlavor), StandardCharsets.UTF_8); } catch (UnsupportedFlavorException cannotHappen) { } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java Wed Jul 05 22:30:52 2017 +0200 @@ -214,6 +214,7 @@ this.setDefaultDragImage(); } + @SuppressWarnings("deprecation") private void setDefaultDragImage(JTextComponent component) { DragGestureEvent trigger = getTrigger(); int selectionStart = component.getSelectionStart(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformLWWindow.java Wed Jul 05 22:30:52 2017 +0200 @@ -196,7 +196,8 @@ getLocalGraphicsEnvironment(); LWLightweightFramePeer peer = (LWLightweightFramePeer)getPeer(); - int scale = ((LightweightFrame)peer.getTarget()).getScaleFactor(); + int scale =(int) Math.round(((LightweightFrame)peer.getTarget()) + .getScaleFactorX()); Rectangle bounds = ((LightweightFrame)peer.getTarget()).getHostBounds(); for (GraphicsDevice d : ge.getScreenDevices()) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java --- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java Wed Jul 05 22:30:52 2017 +0200 @@ -25,10 +25,12 @@ package sun.lwawt.macosx; +import com.apple.eawt.FullScreenAdapter; +import com.apple.eawt.FullScreenUtilities; +import com.apple.eawt.event.FullScreenEvent; import java.awt.*; import java.awt.Dialog.ModalityType; import java.awt.event.*; -import java.awt.peer.WindowPeer; import java.beans.*; import java.lang.reflect.InvocationTargetException; @@ -44,6 +46,7 @@ import com.apple.laf.*; import com.apple.laf.ClientPropertyApplicator.Property; import com.sun.awt.AWTUtilities; +import sun.lwawt.LWWindowPeer.PeerType; public class CPlatformWindow extends CFRetainedResource implements PlatformWindow { private native long nativeCreateNSWindow(long nsViewPtr,long ownerPtr, long styleBits, double x, double y, double w, double h); @@ -175,10 +178,24 @@ c.setStyleBits(CLOSEABLE, Boolean.parseBoolean(value.toString())); }}, new Property(WINDOW_ZOOMABLE) { public void applyProperty(final CPlatformWindow c, final Object value) { - c.setStyleBits(ZOOMABLE, Boolean.parseBoolean(value.toString())); + boolean zoomable = Boolean.parseBoolean(value.toString()); + if (c.target instanceof RootPaneContainer + && c.getPeer().getPeerType() == PeerType.FRAME) { + if (c.isInFullScreen && !zoomable) { + c.toggleFullScreen(); + } + } + c.setStyleBits(ZOOMABLE, zoomable); }}, new Property(WINDOW_FULLSCREENABLE) { public void applyProperty(final CPlatformWindow c, final Object value) { - c.setStyleBits(FULLSCREENABLE, Boolean.parseBoolean(value.toString())); + boolean fullscrenable = Boolean.parseBoolean(value.toString()); + if (c.target instanceof RootPaneContainer + && c.getPeer().getPeerType() == PeerType.FRAME) { + if (c.isInFullScreen && !fullscrenable) { + c.toggleFullScreen(); + } + } + c.setStyleBits(FULLSCREENABLE, fullscrenable); }}, new Property(WINDOW_SHADOW_REVALIDATE_NOW) { public void applyProperty(final CPlatformWindow c, final Object value) { nativeRevalidateNSWindowShadow(c.getNSWindowPtr()); @@ -210,6 +227,8 @@ private volatile boolean isFullScreenMode; private boolean isFullScreenAnimationOn; + private volatile boolean isInFullScreen; + private Window target; private LWWindowPeer peer; protected CPlatformView contentView; @@ -308,6 +327,8 @@ styleBits = SET(styleBits, RESIZABLE, resizable); if (!resizable) { styleBits = SET(styleBits, ZOOMABLE, false); + } else { + setCanFullscreen(true); } } @@ -680,9 +701,25 @@ updateFocusabilityForAutoRequestFocus(true); } + private void setCanFullscreen(final boolean canFullScreen) { + if (target instanceof RootPaneContainer + && getPeer().getPeerType() == PeerType.FRAME) { + + if (isInFullScreen && !canFullScreen) { + toggleFullScreen(); + } + + final RootPaneContainer rpc = (RootPaneContainer) target; + rpc.getRootPane().putClientProperty( + CPlatformWindow.WINDOW_FULLSCREENABLE, canFullScreen); + } + } + @Override public void setResizable(final boolean resizable) { + setCanFullscreen(resizable); setStyleBits(RESIZABLE, resizable); + setStyleBits(ZOOMABLE, resizable); } @Override @@ -1074,6 +1111,7 @@ } private void windowDidEnterFullScreen() { + isInFullScreen = true; isFullScreenAnimationOn = false; } @@ -1082,6 +1120,7 @@ } private void windowDidExitFullScreen() { + isInFullScreen = false; isFullScreenAnimationOn = false; } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.h --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.h Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.h Wed Jul 05 22:30:52 2017 +0200 @@ -26,6 +26,7 @@ #include #import #import +#import #import "CPopupMenu.h" @@ -64,12 +65,14 @@ @public AWTTrayIcon *trayIcon; NSImage* image; + NSTrackingArea *trackingArea; BOOL isHighlighted; } -(id)initWithTrayIcon:(AWTTrayIcon *)theTrayIcon; -(void)setHighlighted:(BOOL)aFlag; -(void)setImage:(NSImage*)anImage; -(void)setTrayIcon:(AWTTrayIcon*)theTrayIcon; +-(void)addTrackingArea; @end //AWTTrayIconView diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m --- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m Wed Jul 05 22:30:52 2017 +0200 @@ -171,12 +171,27 @@ [self setTrayIcon: theTrayIcon]; isHighlighted = NO; image = nil; + trackingArea = nil; + + [self addTrackingArea]; + + return self; +} - return self; +- (void)addTrackingArea { + NSTrackingAreaOptions options = NSTrackingMouseMoved | + NSTrackingInVisibleRect | + NSTrackingActiveAlways; + trackingArea = [[NSTrackingArea alloc] initWithRect: CGRectZero + options: options + owner: self + userInfo: nil]; + [self addTrackingArea:trackingArea]; } -(void) dealloc { [image release]; + [trackingArea release]; [super dealloc]; } @@ -269,6 +284,10 @@ [trayIcon deliverJavaMouseEvent: event]; } +- (void) mouseMoved: (NSEvent *)event { + [trayIcon deliverJavaMouseEvent: event]; +} + - (void) rightMouseDown:(NSEvent *)event { [trayIcon deliverJavaMouseEvent: event]; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java --- a/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/beans/decoder/DocumentHandler.java Wed Jul 05 22:30:52 2017 +0200 @@ -277,10 +277,12 @@ * @param attributes the attributes attached to the element */ @Override + @SuppressWarnings("deprecation") public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { ElementHandler parent = this.handler; try { - this.handler = getElementHandler(qName).newInstance(); + this.handler = + getElementHandler(qName).newInstance(); this.handler.setOwner(this); this.handler.setParent(parent); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java --- a/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/beans/finder/InstanceFinder.java Wed Jul 05 22:30:52 2017 +0200 @@ -86,6 +86,7 @@ return null; } + @SuppressWarnings("deprecation") protected T instantiate(Class type, String name) { if (type != null) { try { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFFaxDecompressor.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -101,7 +101,8 @@ 0xff // 8 }; - // Table to be used when fillOrder = 2, for flipping bytes. + // Table to be used for flipping bytes when fillOrder is + // BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT (2). static byte flipTable[] = { 0, -128, 64, -64, 32, -96, 96, -32, 16, -112, 80, -48, 48, -80, 112, -16, @@ -597,7 +598,8 @@ TIFFField f; f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_FILL_ORDER); - this.fillOrder = f == null ? 1 : f.getAsInt(0); + this.fillOrder = f == null ? + BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT : f.getAsInt(0); f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_COMPRESSION); this.compression = f == null ? @@ -612,7 +614,7 @@ f = tmetadata.getTIFFField(BaselineTIFFTagSet.TAG_T6_OPTIONS); this.t6Options = f == null ? 0 : f.getAsInt(0); } else { - this.fillOrder = 1; // MSB-to-LSB + this.fillOrder = BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT; this.compression = BaselineTIFFTagSet.COMPRESSION_CCITT_RLE; // RLE @@ -1458,7 +1460,7 @@ int l = data.length - 1; int bp = this.bytePointer; - if (fillOrder == 1) { + if (fillOrder == BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT) { b = data[bp]; if (bp == l) { @@ -1471,7 +1473,7 @@ next = data[bp + 1]; next2next = data[bp + 2]; } - } else if (fillOrder == 2) { + } else if (fillOrder == BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT) { b = flipTable[data[bp] & 0xff]; if (bp == l) { @@ -1527,14 +1529,14 @@ int l = data.length - 1; int bp = this.bytePointer; - if (fillOrder == 1) { + if (fillOrder == BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT) { b = data[bp]; if (bp == l) { next = 0x00; } else { next = data[bp + 1]; } - } else if (fillOrder == 2) { + } else if (fillOrder == BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT) { b = flipTable[data[bp] & 0xff]; if (bp == l) { next = 0x00; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFIFD.java Wed Jul 05 22:30:52 2017 +0200 @@ -49,6 +49,52 @@ private long stripOrTileOffsetsPosition = -1; private long lastPosition = -1; + // + // A set of tag numbers corresponding to tags essential to decoding + // the image and metadata required to interpret its samples. + // + private static volatile Set essentialTags = null; + + private static void initializeEssentialTags() { + Set tags = essentialTags; + if (tags == null) { + essentialTags = tags = Set.of( + BaselineTIFFTagSet.TAG_BITS_PER_SAMPLE, + BaselineTIFFTagSet.TAG_COLOR_MAP, + BaselineTIFFTagSet.TAG_COMPRESSION, + BaselineTIFFTagSet.TAG_EXTRA_SAMPLES, + BaselineTIFFTagSet.TAG_FILL_ORDER, + BaselineTIFFTagSet.TAG_ICC_PROFILE, + BaselineTIFFTagSet.TAG_IMAGE_LENGTH, + BaselineTIFFTagSet.TAG_IMAGE_WIDTH, + BaselineTIFFTagSet.TAG_JPEG_AC_TABLES, + BaselineTIFFTagSet.TAG_JPEG_DC_TABLES, + BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT, + BaselineTIFFTagSet.TAG_JPEG_INTERCHANGE_FORMAT_LENGTH, + BaselineTIFFTagSet.TAG_JPEG_PROC, + BaselineTIFFTagSet.TAG_JPEG_Q_TABLES, + BaselineTIFFTagSet.TAG_JPEG_RESTART_INTERVAL, + BaselineTIFFTagSet.TAG_JPEG_TABLES, + BaselineTIFFTagSet.TAG_PHOTOMETRIC_INTERPRETATION, + BaselineTIFFTagSet.TAG_PLANAR_CONFIGURATION, + BaselineTIFFTagSet.TAG_PREDICTOR, + BaselineTIFFTagSet.TAG_REFERENCE_BLACK_WHITE, + BaselineTIFFTagSet.TAG_ROWS_PER_STRIP, + BaselineTIFFTagSet.TAG_SAMPLES_PER_PIXEL, + BaselineTIFFTagSet.TAG_SAMPLE_FORMAT, + BaselineTIFFTagSet.TAG_STRIP_BYTE_COUNTS, + BaselineTIFFTagSet.TAG_STRIP_OFFSETS, + BaselineTIFFTagSet.TAG_T4_OPTIONS, + BaselineTIFFTagSet.TAG_T6_OPTIONS, + BaselineTIFFTagSet.TAG_TILE_BYTE_COUNTS, + BaselineTIFFTagSet.TAG_TILE_LENGTH, + BaselineTIFFTagSet.TAG_TILE_OFFSETS, + BaselineTIFFTagSet.TAG_TILE_WIDTH, + BaselineTIFFTagSet.TAG_Y_CB_CR_COEFFICIENTS, + BaselineTIFFTagSet.TAG_Y_CB_CR_SUBSAMPLING + ); + } + } /** * Converts a {@code TIFFDirectory} to a {@code TIFFIFD}. @@ -507,6 +553,15 @@ List tagSetList = getTagSetList(); + boolean ensureEssentialTags = false; + TIFFTagSet baselineTagSet = null; + if (isPrimaryIFD && ignoreUnknownFields + && !tagSetList.contains(BaselineTIFFTagSet.getInstance())) { + ensureEssentialTags = true; + initializeEssentialTags(); + baselineTagSet = BaselineTIFFTagSet.getInstance(); + } + List entries = new ArrayList<>(); Object[] entryData = new Object[1]; // allocate once for later reuse. @@ -530,6 +585,11 @@ // Get the associated TIFFTag. TIFFTag tag = getTag(tagNumber, tagSetList); + if (tag == null && ensureEssentialTags + && essentialTags.contains(tagNumber)) { + tag = baselineTagSet.getTag(tagNumber); + } + // Ignore unknown fields, fields with unknown type, and fields // with count out of int range. if((tag == null && ignoreUnknownFields) diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageReader.java --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageReader.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFImageReader.java Wed Jul 05 22:30:52 2017 +0200 @@ -1174,7 +1174,14 @@ int predictor = ((predictorField == null) ? BaselineTIFFTagSet.PREDICTOR_NONE : predictorField.getAsInt(0)); - this.decompressor = new TIFFLZWDecompressor(predictor); + + TIFFField fillOrderField + = imageMetadata.getTIFFField(BaselineTIFFTagSet.TAG_FILL_ORDER); + int fillOrder = ((fillOrderField == null) + ? BaselineTIFFTagSet.FILL_ORDER_LEFT_TO_RIGHT + : fillOrderField.getAsInt(0)); + + this.decompressor = new TIFFLZWDecompressor(predictor, fillOrder); } else if (compression == BaselineTIFFTagSet.COMPRESSION_JPEG) { this.decompressor = new TIFFJPEGDecompressor(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java --- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/tiff/TIFFLZWDecompressor.java Wed Jul 05 22:30:52 2017 +0200 @@ -30,6 +30,10 @@ class TIFFLZWDecompressor extends TIFFDecompressor { + private static final int CLEAR_CODE = 256; + private static final int EOI_CODE = 257; + private static final int FIRST_CODE = 258; + private static final int andTable[] = { 511, 1023, @@ -39,6 +43,10 @@ private int predictor; + // whether to reverse the bits in each byte of the input data, i.e., + // convert right-to-left fill order (lsb) to left-to-right (msb). + private boolean flipBits; + private byte[] srcData; private byte[] dstData; @@ -51,7 +59,8 @@ private int nextData = 0; private int nextBits = 0; - public TIFFLZWDecompressor(int predictor) throws IIOException { + public TIFFLZWDecompressor(int predictor, int fillOrder) + throws IIOException { super(); if (predictor != BaselineTIFFTagSet.PREDICTOR_NONE && @@ -62,6 +71,8 @@ } this.predictor = predictor; + + flipBits = fillOrder == BaselineTIFFTagSet.FILL_ORDER_RIGHT_TO_LEFT; } public void decodeRaw(byte[] b, @@ -88,6 +99,12 @@ byte[] sdata = new byte[byteCount]; stream.readFully(sdata); + if (flipBits) { + for (int i = 0; i < byteCount; i++) { + sdata[i] = TIFFFaxDecompressor.flipTable[sdata[i] & 0xff]; + } + } + int bytesPerRow = (srcWidth*bitsPerPixel + 7)/8; byte[] buf; int bufOffset; @@ -133,11 +150,11 @@ int code, oldCode = 0; byte[] string; - while ((code = getNextCode()) != 257) { - if (code == 256) { + while ((code = getNextCode()) != EOI_CODE) { + if (code == CLEAR_CODE) { initializeStringTable(); code = getNextCode(); - if (code == 257) { + if (code == EOI_CODE) { break; } @@ -186,12 +203,12 @@ public void initializeStringTable() { stringTable = new byte[4096][]; - for (int i = 0; i < 256; i++) { + for (int i = 0; i < CLEAR_CODE; i++) { stringTable[i] = new byte[1]; stringTable[i][0] = (byte)i; } - tableIndex = 258; + tableIndex = FIRST_CODE; bitsToGet = 9; } @@ -281,7 +298,7 @@ return code; } catch (ArrayIndexOutOfBoundsException e) { // Strip not terminated as expected: return EndOfInformation code. - return 257; + return EOI_CODE; } } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/java/swing/SwingUtilities3.java --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/SwingUtilities3.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/SwingUtilities3.java Wed Jul 05 22:30:52 2017 +0200 @@ -88,6 +88,7 @@ * or {@code Applet} * @param isRequested the value to set vsyncRequested state to */ + @SuppressWarnings("deprecation") public static void setVsyncRequested(Container rootContainer, boolean isRequested) { assert (rootContainer instanceof Applet) || (rootContainer instanceof Window); @@ -104,6 +105,7 @@ * @param rootContainer topmost container. Should be either Window or Applet * @return {@code true} if vsync painting is requested for {@code rootContainer} */ + @SuppressWarnings("deprecation") public static boolean isVsyncRequested(Container rootContainer) { assert (rootContainer instanceof Applet) || (rootContainer instanceof Window); return Boolean.TRUE == vsyncedMap.get(rootContainer); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/GTKStyle.java Wed Jul 05 22:30:52 2017 +0200 @@ -1125,6 +1125,7 @@ this.methodName = methodName; } + @SuppressWarnings("deprecation") public Object createValue(UIDefaults table) { try { Class c = Class.forName(className, true,Thread.currentThread(). @@ -1136,11 +1137,7 @@ Method m = c.getMethod(methodName, (Class[])null); return m.invoke(c, (Object[])null); - } catch (ClassNotFoundException cnfe) { - } catch (IllegalAccessException iae) { - } catch (InvocationTargetException ite) { - } catch (NoSuchMethodException nsme) { - } catch (InstantiationException ie) { + } catch (ReflectiveOperationException e) { } return null; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/gtk/Metacity.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -29,6 +29,7 @@ import com.sun.java.swing.plaf.gtk.GTKConstants.ShadowType; import javax.swing.plaf.ColorUIResource; +import javax.swing.plaf.basic.BasicInternalFrameTitlePane; import javax.swing.plaf.synth.*; import java.awt.*; @@ -40,7 +41,6 @@ import java.util.*; import javax.swing.*; -import javax.swing.border.*; import javax.xml.parsers.*; import org.xml.sax.SAXException; @@ -226,12 +226,8 @@ JComponent titlePane = (JComponent)button.getParent(); Container titlePaneParent = titlePane.getParent(); - JInternalFrame jif; - if (titlePaneParent instanceof JInternalFrame) { - jif = (JInternalFrame)titlePaneParent; - } else if (titlePaneParent instanceof JInternalFrame.JDesktopIcon) { - jif = ((JInternalFrame.JDesktopIcon)titlePaneParent).getInternalFrame(); - } else { + JInternalFrame jif = findInternalFrame(titlePaneParent); + if (jif == null) { return; } @@ -332,6 +328,19 @@ } } + JInternalFrame findInternalFrame(Component comp) { + if (comp.getParent() instanceof BasicInternalFrameTitlePane) { + comp = comp.getParent(); + } + if (comp instanceof JInternalFrame) { + return (JInternalFrame)comp; + } else if (comp instanceof JInternalFrame.JDesktopIcon) { + return ((JInternalFrame.JDesktopIcon)comp).getInternalFrame(); + } + assert false : "cannot find the internal frame"; + return null; + } + void paintFrameBorder(SynthContext context, Graphics g, int x0, int y0, int width, int height) { updateFrameGeometry(context); @@ -343,13 +352,8 @@ return; } - JInternalFrame jif = null; - if (comp instanceof JInternalFrame) { - jif = (JInternalFrame)comp; - } else if (comp instanceof JInternalFrame.JDesktopIcon) { - jif = ((JInternalFrame.JDesktopIcon)comp).getInternalFrame(); - } else { - assert false : "component is not JInternalFrame or JInternalFrame.JDesktopIcon"; + JInternalFrame jif = findInternalFrame(comp); + if (jif == null) { return; } @@ -1467,13 +1471,8 @@ JComponent comp = context.getComponent(); JComponent titlePane = findChild(comp, "InternalFrame.northPane"); - JInternalFrame jif = null; - if (comp instanceof JInternalFrame) { - jif = (JInternalFrame)comp; - } else if (comp instanceof JInternalFrame.JDesktopIcon) { - jif = ((JInternalFrame.JDesktopIcon)comp).getInternalFrame(); - } else { - assert false : "component is not JInternalFrame or JInternalFrame.JDesktopIcon"; + JInternalFrame jif = findInternalFrame(comp); + if (jif == null) { return; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java Wed Jul 05 22:30:52 2017 +0200 @@ -124,6 +124,7 @@ * @param g the graphics context * @see #damage */ + @SuppressWarnings("deprecation") public void paint(Graphics g) { if(isVisible()) { try { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextFieldUI.java --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextFieldUI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextFieldUI.java Wed Jul 05 22:30:52 2017 +0200 @@ -132,6 +132,7 @@ this.r = r; } + @SuppressWarnings("deprecation") public void run() { JTextField field = (JTextField) getComponent(); if (field != null) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextUI.java --- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextUI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTextUI.java Wed Jul 05 22:30:52 2017 +0200 @@ -93,6 +93,7 @@ * @param bounds the bounding box for the highlight * @param c the editor */ + @SuppressWarnings("deprecation") public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) { Rectangle alloc = bounds.getBounds(); try { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JARSoundbankReader.java Wed Jul 05 22:30:52 2017 +0200 @@ -70,6 +70,7 @@ } @Override + @SuppressWarnings("deprecation") public Soundbank getSoundbank(URL url) throws InvalidMidiDataException, IOException { if (!isZIP(url)) @@ -93,9 +94,7 @@ Object o = c.newInstance(); soundbanks.add((Soundbank) o); } - } catch (ClassNotFoundException ignored) { - } catch (InstantiationException ignored) { - } catch (IllegalAccessException ignored) { + } catch (ReflectiveOperationException ignored) { } } line = r.readLine(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/JavaSoundAudioClip.java Wed Jul 05 22:30:52 2017 +0200 @@ -55,6 +55,7 @@ * @author Arthur van Hoff, Kara Kytle, Jan Borgersen * @author Florian Bomers */ +@SuppressWarnings("deprecation") public final class JavaSoundAudioClip implements AudioClip, MetaEventListener, LineListener { private static final boolean DEBUG = false; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java --- a/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/com/sun/media/sound/ModelAbstractOscillator.java Wed Jul 05 22:30:52 2017 +0200 @@ -134,13 +134,12 @@ } @Override + @SuppressWarnings("deprecation") public ModelOscillatorStream open(float samplerate) { ModelAbstractOscillator oscs; try { oscs = this.getClass().newInstance(); - } catch (InstantiationException e) { - throw new IllegalArgumentException(e); - } catch (IllegalAccessException e) { + } catch (ReflectiveOperationException e) { throw new IllegalArgumentException(e); } oscs.setSampleRate(samplerate); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/awt/Component.java --- a/jdk/src/java.desktop/share/classes/java/awt/Component.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/awt/Component.java Wed Jul 05 22:30:52 2017 +0200 @@ -4016,6 +4016,7 @@ * {@code true}. * @see #createBuffers(int, BufferCapabilities) */ + @SuppressWarnings("deprecation") protected FlipBufferStrategy(int numBuffers, BufferCapabilities caps) throws AWTException { @@ -8133,6 +8134,7 @@ return res; } + @SuppressWarnings("deprecation") final Component getNextFocusCandidate() { Container rootAncestor = getTraversalRoot(); Component comp = this; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java --- a/jdk/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/awt/DefaultKeyboardFocusManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -75,6 +75,7 @@ private LinkedList enqueuedKeyEvents = new LinkedList(); private LinkedList typeAheadMarkers = new LinkedList(); private boolean consumeNextKeyTyped; + private Component restoreFocusTo; static { AWTAccessor.setDefaultKeyboardFocusManagerAccessor( @@ -145,19 +146,24 @@ } private boolean restoreFocus(Window aWindow, Component vetoedComponent, boolean clearOnFailure) { + restoreFocusTo = null; Component toFocus = KeyboardFocusManager.getMostRecentFocusOwner(aWindow); if (toFocus != null && toFocus != vetoedComponent) { - Component heavyweight = getHeavyweight(aWindow); - if (heavyweight != null) { - setNativeFocusOwner(heavyweight); - Toolkit.getEventQueue().createSecondaryLoop( - () -> getGlobalFocusedWindow() != aWindow, null, 50) - .enter(); - } - if (getGlobalFocusedWindow() == aWindow && - doRestoreFocus(toFocus, vetoedComponent, false)) { + if (getHeavyweight(aWindow) != getNativeFocusOwner()) { + // cannot restore focus synchronously + if (!toFocus.isShowing() || !toFocus.canBeFocusOwner()) { + toFocus = toFocus.getNextFocusCandidate(); + } + if (toFocus != null && toFocus != vetoedComponent) { + if (!toFocus.requestFocus(false, + FocusEvent.Cause.ROLLBACK)) { + restoreFocusTo = toFocus; + } + return true; + } + } else if (doRestoreFocus(toFocus, vetoedComponent, false)) { return true; } } @@ -423,6 +429,8 @@ // may cause deadlock, thus we don't synchronize this block. Component toFocus = KeyboardFocusManager. getMostRecentFocusOwner(newFocusedWindow); + boolean isFocusRestore = restoreFocusTo != null && + toFocus == restoreFocusTo; if ((toFocus == null) && newFocusedWindow.isFocusableWindow()) { @@ -441,7 +449,10 @@ tempLost, toFocus); } if (tempLost != null) { - tempLost.requestFocusInWindow(FocusEvent.Cause.ACTIVATION); + tempLost.requestFocusInWindow( + isFocusRestore && tempLost == toFocus ? + FocusEvent.Cause.ROLLBACK : + FocusEvent.Cause.ACTIVATION); } if (toFocus != null && toFocus != tempLost) { @@ -450,6 +461,7 @@ toFocus.requestFocusInWindow(FocusEvent.Cause.ACTIVATION); } } + restoreFocusTo = null; Window realOppositeWindow = this.realOppositeWindowWR.get(); if (realOppositeWindow != we.getOppositeWindow()) { @@ -499,6 +511,7 @@ } case FocusEvent.FOCUS_GAINED: { + restoreFocusTo = null; FocusEvent fe = (FocusEvent)e; Component oldFocusOwner = getGlobalFocusOwner(); Component newFocusOwner = fe.getComponent(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java --- a/jdk/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/awt/GraphicsEnvironment.java Wed Jul 05 22:30:52 2017 +0200 @@ -108,7 +108,7 @@ ClassLoader cl = ClassLoader.getSystemClassLoader(); geCls = Class.forName(nm, true, cl); } - ge = (GraphicsEnvironment)geCls.newInstance(); + ge = (GraphicsEnvironment)geCls.getConstructor().newInstance(); // long t1 = System.currentTimeMillis(); // System.out.println("GE creation took " + (t1-t0)+ "ms."); if (isHeadless()) { @@ -116,12 +116,9 @@ } } catch (ClassNotFoundException e) { throw new Error("Could not find class: "+nm); - } catch (InstantiationException e) { + } catch (ReflectiveOperationException | IllegalArgumentException e) { throw new Error("Could not instantiate Graphics Environment: " + nm); - } catch (IllegalAccessException e) { - throw new Error ("Could not access Graphics Environment: " - + nm); } return ge; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/awt/Taskbar.java --- a/jdk/src/java.desktop/share/classes/java/awt/Taskbar.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/awt/Taskbar.java Wed Jul 05 22:30:52 2017 +0200 @@ -407,10 +407,21 @@ } /** - * Displays progress for specified window. + * Displays a determinate progress bar in the task area for the specified + * window. + *
    + * The visual behavior is platform and {@link State} dependent. + *
    + * This call cancels the {@link State#INDETERMINATE INDETERMINATE} state + * of the window. + *
    + * Note that when multiple windows is grouped in the task area + * the behavior is platform specific. * * @param w window to update - * @param value from 0 to 100, other to disable progress indication + * @param value from 0 to 100, other to switch to {@link State#OFF} state + * and disable progress indication + * @see #setWindowProgressState(java.awt.Window, State) * @throws SecurityException if a security manager exists and it denies the * {@code RuntimePermission("canProcessApplicationEvents")} permission. * @throws UnsupportedOperationException if the current platform @@ -426,14 +437,21 @@ /** * Sets a progress state for a specified window. + *
    + * Each state displays a progress in a platform-dependent way. + *
    + * Note than switching from {@link State#INDETERMINATE INDETERMINATE} state + * to any of determinate states may reset value set by + * {@link #setWindowProgressValue(java.awt.Window, int) setWindowProgressValue} * * @param w window * @param state to change to * @see State#OFF * @see State#NORMAL * @see State#PAUSED + * @see State#ERROR * @see State#INDETERMINATE - * @see State#ERROR + * @see #setWindowProgressValue(java.awt.Window, int) * @throws SecurityException if a security manager exists and it denies the * {@code RuntimePermission("canProcessApplicationEvents")} permission. * @throws UnsupportedOperationException if the current platform diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/awt/Toolkit.java --- a/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java Wed Jul 05 22:30:52 2017 +0200 @@ -468,7 +468,7 @@ private static void fallbackToLoadClassForAT(String atName) { try { Class c = Class.forName(atName, false, ClassLoader.getSystemClassLoader()); - c.newInstance(); + c.getConstructor().newInstance(); } catch (ClassNotFoundException e) { newAWTError(e, "Assistive Technology not found: " + atName); } catch (InstantiationException e) { @@ -583,15 +583,13 @@ } try { if (cls != null) { - toolkit = (Toolkit)cls.newInstance(); + toolkit = (Toolkit)cls.getConstructor().newInstance(); if (GraphicsEnvironment.isHeadless()) { toolkit = new HeadlessToolkit(toolkit); } } - } catch (final InstantiationException ignored) { - throw new AWTError("Could not instantiate Toolkit: " + nm); - } catch (final IllegalAccessException ignored) { - throw new AWTError("Could not access Toolkit: " + nm); + } catch (final ReflectiveOperationException ignored) { + throw new AWTError("Could not create Toolkit: " + nm); } return null; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/awt/print/PrinterJob.java --- a/jdk/src/java.desktop/share/classes/java/awt/print/PrinterJob.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/awt/print/PrinterJob.java Wed Jul 05 22:30:52 2017 +0200 @@ -79,13 +79,12 @@ public PrinterJob run() { String nm = System.getProperty("java.awt.printerjob", null); try { - return (PrinterJob)Class.forName(nm).newInstance(); + return (PrinterJob)Class.forName(nm). + getConstructor().newInstance(); } catch (ClassNotFoundException e) { throw new AWTError("PrinterJob not found: " + nm); - } catch (InstantiationException e) { + } catch (ReflectiveOperationException e) { throw new AWTError("Could not instantiate PrinterJob: " + nm); - } catch (IllegalAccessException e) { - throw new AWTError("Could not access PrinterJob: " + nm); } } }); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/beans/AppletInitializer.java --- a/jdk/src/java.desktop/share/classes/java/beans/AppletInitializer.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/beans/AppletInitializer.java Wed Jul 05 22:30:52 2017 +0200 @@ -44,6 +44,7 @@ */ +@SuppressWarnings("deprecation") public interface AppletInitializer { /** diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/beans/Beans.java --- a/jdk/src/java.desktop/share/classes/java/beans/Beans.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/beans/Beans.java Wed Jul 05 22:30:52 2017 +0200 @@ -154,7 +154,7 @@ * @exception IOException if an I/O error occurs. * @since 1.2 */ - + @SuppressWarnings("deprecation") public static Object instantiate(ClassLoader cls, String beanName, BeanContext beanContext, AppletInitializer initializer) throws IOException, ClassNotFoundException { @@ -501,7 +501,7 @@ * Package private support class. This provides a default AppletContext * for beans which are applets. */ - +@SuppressWarnings("deprecation") class BeansAppletContext implements AppletContext { Applet target; Hashtable imageCache = new Hashtable<>(); @@ -586,6 +586,7 @@ * Package private support class. This provides an AppletStub * for beans which are applets. */ +@SuppressWarnings("deprecation") class BeansAppletStub implements AppletStub { transient boolean active; transient Applet target; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/beans/Introspector.java --- a/jdk/src/java.desktop/share/classes/java/beans/Introspector.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/beans/Introspector.java Wed Jul 05 22:30:52 2017 +0200 @@ -36,6 +36,7 @@ import java.lang.ref.Reference; import java.lang.ref.SoftReference; import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Type; @@ -1278,8 +1279,10 @@ * First try the classloader of "sibling", then try the system * classloader then the class loader of the current Thread. */ + @SuppressWarnings("deprecation") static Object instantiate(Class sibling, String className) throws InstantiationException, IllegalAccessException, + NoSuchMethodException, InvocationTargetException, ClassNotFoundException { // First check with sibling's classloader (if any). ClassLoader cl = sibling.getClassLoader(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/beans/MetaData.java --- a/jdk/src/java.desktop/share/classes/java/beans/MetaData.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/beans/MetaData.java Wed Jul 05 22:30:52 2017 +0200 @@ -1219,7 +1219,7 @@ internalPersistenceDelegates.put("java.sql.Time", new java_util_Date_PersistenceDelegate()); } - @SuppressWarnings("rawtypes") + @SuppressWarnings({"rawtypes", "deprecation"}) public static synchronized PersistenceDelegate getPersistenceDelegate(Class type) { if (type == null) { return nullPersistenceDelegate; @@ -1261,7 +1261,7 @@ internalPersistenceDelegates.put(typeName, defaultPersistenceDelegate); try { String name = type.getName(); - Class c = Class.forName("java.beans.MetaData$" + name.replace('.', '_') + Class c = Class.forName("java.beans.MetaData$" + name.replace('.', '_') + "_PersistenceDelegate"); pd = (PersistenceDelegate)c.newInstance(); internalPersistenceDelegates.put(typeName, pd); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java --- a/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/java/beans/PropertyDescriptor.java Wed Jul 05 22:30:52 2017 +0200 @@ -461,6 +461,7 @@ * not been defined or cannot be created * @since 1.5 */ + @SuppressWarnings("deprecation") public PropertyEditor createPropertyEditor(Object bean) { Object editor = null; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFileFormat.java --- a/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFileFormat.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFileFormat.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -28,6 +28,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; /** * An instance of the {@code AudioFileFormat} class describes an audio file, @@ -344,7 +345,7 @@ * @param extension the string that commonly marks the file type * without leading dot */ - public Type(String name, String extension) { + public Type(final String name, final String extension) { this.name = name; this.extension = extension; } @@ -353,14 +354,14 @@ * Finalizes the equals method. */ @Override - public final boolean equals(Object obj) { - if (toString() == null) { - return (obj != null) && (obj.toString() == null); + public final boolean equals(final Object obj) { + if (this == obj) { + return true; } - if (obj instanceof Type) { - return toString().equals(obj.toString()); + if (!(obj instanceof Type)) { + return false; } - return false; + return Objects.equals(name, ((Type) obj).name); } /** @@ -368,10 +369,7 @@ */ @Override public final int hashCode() { - if (toString() == null) { - return 0; - } - return toString().hashCode(); + return name != null ? name.hashCode() : 0; } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFormat.java --- a/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFormat.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/sound/sampled/AudioFormat.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -28,6 +28,7 @@ import java.util.Collections; import java.util.HashMap; import java.util.Map; +import java.util.Objects; /** * {@code AudioFormat} is the class that specifies a particular arrangement of @@ -599,7 +600,7 @@ * * @param name the name of the new type of encoding */ - public Encoding(String name) { + public Encoding(final String name) { this.name = name; } @@ -607,14 +608,14 @@ * Finalizes the equals method. */ @Override - public final boolean equals(Object obj) { - if (toString() == null) { - return (obj != null) && (obj.toString() == null); + public final boolean equals(final Object obj) { + if (this == obj) { + return true; } - if (obj instanceof Encoding) { - return toString().equals(obj.toString()); + if (!(obj instanceof Encoding)) { + return false; } - return false; + return Objects.equals(name, ((Encoding) obj).name); } /** @@ -622,10 +623,7 @@ */ @Override public final int hashCode() { - if (toString() == null) { - return 0; - } - return toString().hashCode(); + return name != null ? name.hashCode() : 0; } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/sound/sampled/spi/AudioFileWriter.java --- a/jdk/src/java.desktop/share/classes/javax/sound/sampled/spi/AudioFileWriter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/sound/sampled/spi/AudioFileWriter.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -129,7 +129,7 @@ * system * @throws NullPointerException if {@code stream} or {@code fileType} or * {@code out} are {@code null} - * @see #isFileTypeSupported(AudioFileFormat.Type, AudioInputStream) + * @see #isFileTypeSupported(Type, AudioInputStream) * @see #getAudioFileTypes */ public abstract int write(AudioInputStream stream, Type fileType, @@ -149,7 +149,7 @@ * the system * @throws NullPointerException if {@code stream} or {@code fileType} or * {@code out} are {@code null} - * @see #isFileTypeSupported + * @see #isFileTypeSupported(Type, AudioInputStream) * @see #getAudioFileTypes */ public abstract int write(AudioInputStream stream, Type fileType, File out) diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/JComponent.java --- a/jdk/src/java.desktop/share/classes/javax/swing/JComponent.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/JComponent.java Wed Jul 05 22:30:52 2017 +0200 @@ -555,6 +555,7 @@ * @see #setComponentPopupMenu * @since 1.5 */ + @SuppressWarnings("deprecation") public JPopupMenu getComponentPopupMenu() { if(!getInheritsPopupMenu()) { @@ -2913,6 +2914,7 @@ * @param pressed true if the key is pressed * @return true if there is a key binding for e */ + @SuppressWarnings("deprecation") boolean processKeyBindings(KeyEvent e, boolean pressed) { if (!SwingUtilities.isValidKeyEventForKeyBindings(e)) { return false; @@ -4457,6 +4459,7 @@ * return value for this method * @see #getVisibleRect */ + @SuppressWarnings("deprecation") static final void computeVisibleRect(Component c, Rectangle visibleRect) { Container p = c.getParent(); Rectangle bounds = c.getBounds(); @@ -4625,6 +4628,7 @@ * or null if not in any container */ @BeanProperty(bound = false) + @SuppressWarnings("deprecation") public Container getTopLevelAncestor() { for(Container p = this; p != null; p = p.getParent()) { if(p instanceof Window || p instanceof Applet) { @@ -5032,6 +5036,7 @@ this.paintingChild = paintingChild; } + @SuppressWarnings("deprecation") void _paintImmediately(int x, int y, int w, int h) { Graphics g; Container c; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java --- a/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/JEditorPane.java Wed Jul 05 22:30:52 2017 +0200 @@ -825,6 +825,7 @@ * * @param reference the named location to scroll to */ + @SuppressWarnings("deprecation") public void scrollToReference(String reference) { Document d = getDocument(); if (d instanceof HTMLDocument) { @@ -1179,6 +1180,7 @@ * @return the editor kit, or null if there is nothing * registered for the given type */ + @SuppressWarnings("deprecation") public static EditorKit createEditorKitForContentType(String type) { Hashtable kitRegistry = getKitRegisty(); EditorKit k = kitRegistry.get(type); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/JTable.java --- a/jdk/src/java.desktop/share/classes/javax/swing/JTable.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/JTable.java Wed Jul 05 22:30:52 2017 +0200 @@ -6043,6 +6043,7 @@ this.focusManager = fm; } + @SuppressWarnings("deprecation") public void propertyChange(PropertyChangeEvent ev) { if (!isEditing() || getClientProperty("terminateEditOnFocusLost") != Boolean.TRUE) { return; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/JViewport.java --- a/jdk/src/java.desktop/share/classes/javax/swing/JViewport.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/JViewport.java Wed Jul 05 22:30:52 2017 +0200 @@ -27,6 +27,12 @@ import java.awt.*; import java.awt.event.*; +import java.awt.geom.AffineTransform; +import static java.awt.geom.AffineTransform.TYPE_FLIP; +import static java.awt.geom.AffineTransform.TYPE_MASK_SCALE; +import static java.awt.geom.AffineTransform.TYPE_TRANSLATION; +import java.awt.image.AbstractMultiResolutionImage; +import java.awt.image.ImageObserver; import java.awt.peer.ComponentPeer; import java.beans.BeanProperty; import java.beans.Transient; @@ -37,6 +43,8 @@ import javax.accessibility.*; import java.io.Serializable; +import java.util.Arrays; +import java.util.Collections; import sun.awt.AWTAccessor; @@ -739,7 +747,43 @@ g.clipRect(0, 0, viewBounds.width, viewBounds.height); } - if (backingStoreImage == null) { + boolean recreateBackingStoreImage = (backingStoreImage == null); + int scaledWidth = width; + int scaledHeight = height; + + if (g instanceof Graphics2D) { + double sw = width; + double sh = height; + Graphics2D g2d = (Graphics2D) g; + AffineTransform tx = g2d.getTransform(); + int type = tx.getType(); + if ((type & ~(TYPE_TRANSLATION | TYPE_FLIP)) == 0) { + // skip + } else if ((type & ~(TYPE_TRANSLATION | TYPE_FLIP | TYPE_MASK_SCALE)) == 0) { + sw = Math.abs(width * tx.getScaleX()); + sh = Math.abs(height * tx.getScaleY()); + } else { + sw = Math.abs(width * Math.hypot(tx.getScaleX(), tx.getShearY())); + sh = Math.abs(height * Math.hypot(tx.getShearX(), tx.getScaleY())); + } + + scaledWidth = (int) Math.ceil(sw); + scaledHeight = (int) Math.ceil(sh); + + if (!recreateBackingStoreImage) { + if (backingStoreImage instanceof BackingStoreMultiResolutionImage) { + BackingStoreMultiResolutionImage mrImage + = (BackingStoreMultiResolutionImage) backingStoreImage; + recreateBackingStoreImage = (mrImage.scaledWidth != scaledWidth + || mrImage.scaledHeight != scaledHeight); + } else { + recreateBackingStoreImage = (width != scaledWidth + || height != scaledHeight); + } + } + } + + if (recreateBackingStoreImage) { // Backing store is enabled but this is the first call to paint. // Create the backing store, paint it and then copy to g. // The backing store image will be created with the size of @@ -747,7 +791,8 @@ // same size, otherwise when scrolling the backing image // the region outside of the clipped region will not be painted, // and result in empty areas. - backingStoreImage = createImage(width, height); + backingStoreImage = createScaledImage(width, height, + scaledWidth, scaledHeight); Rectangle clip = g.getClipBounds(); if (clip.width != width || clip.height != height) { if (!isOpaque()) { @@ -815,6 +860,74 @@ scrollUnderway = false; } + private Image createScaledImage(final int width, final int height, + int scaledWidth, int scaledHeight) + { + if (scaledWidth == width && scaledHeight == height) { + return createImage(width, height); + } + + Image rvImage = createImage(scaledWidth, scaledHeight); + + return new BackingStoreMultiResolutionImage(width, height, + scaledWidth, scaledHeight, rvImage); + } + + static class BackingStoreMultiResolutionImage + extends AbstractMultiResolutionImage { + + private final int width; + private final int height; + private final int scaledWidth; + private final int scaledHeight; + private final Image rvImage; + + public BackingStoreMultiResolutionImage(int width, int height, + int scaledWidth, int scaledHeight, Image rvImage) { + this.width = width; + this.height = height; + this.scaledWidth = scaledWidth; + this.scaledHeight = scaledHeight; + this.rvImage = rvImage; + } + + @Override + public int getWidth(ImageObserver observer) { + return width; + } + + @Override + public int getHeight(ImageObserver observer) { + return height; + } + + @Override + protected Image getBaseImage() { + return rvImage; + } + + @Override + public Graphics getGraphics() { + Graphics graphics = rvImage.getGraphics(); + if (graphics instanceof Graphics2D) { + double sx = (double) scaledWidth / width; + double sy = (double) scaledHeight / height; + ((Graphics2D) graphics).scale(sx, sy); + } + return graphics; + } + + @Override + public Image getResolutionVariant(double w, double h) { + return rvImage; + } + + @Override + public java.util.List getResolutionVariants() { + return Collections.unmodifiableList(Arrays.asList(rvImage)); + } + } + /** * Sets the bounds of this viewport. If the viewport's width diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java --- a/jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -137,6 +137,7 @@ /** * Find the top focusable Window, Applet, or InternalFrame */ + @SuppressWarnings("deprecation") private static Container getTopAncestor(JComponent c) { for(Container p = c.getParent(); p != null; p = p.getParent()) { if (p instanceof Window && ((Window)p).isFocusableWindow() || diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/PopupFactory.java --- a/jdk/src/java.desktop/share/classes/javax/swing/PopupFactory.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/PopupFactory.java Wed Jul 05 22:30:52 2017 +0200 @@ -614,6 +614,7 @@ * Returns true if popup can fit the screen and the owner's top parent. * It determines can popup be lightweight or mediumweight. */ + @SuppressWarnings("deprecation") boolean fitsOnScreen() { boolean result = false; Component component = getComponent(); @@ -783,6 +784,8 @@ component.removeAll(); recycleLightWeightPopup(this); } + + @SuppressWarnings("deprecation") public void show() { Container parent = null; @@ -938,6 +941,8 @@ rootPane.getContentPane().removeAll(); recycleMediumWeightPopup(this); } + + @SuppressWarnings("deprecation") public void show() { Component component = getComponent(); Container parent = null; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/RepaintManager.java --- a/jdk/src/java.desktop/share/classes/javax/swing/RepaintManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/RepaintManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -408,6 +408,7 @@ * * @see JComponent#repaint */ + @SuppressWarnings("deprecation") private void addDirtyRegion0(Container c, int x, int y, int w, int h) { /* Special cases we don't have to bother with. */ @@ -521,10 +522,12 @@ * @see JApplet#repaint * @since 1.6 */ + @SuppressWarnings("deprecation") public void addDirtyRegion(Applet applet, int x, int y, int w, int h) { addDirtyRegion0(applet, x, y, w, h); } + @SuppressWarnings("deprecation") void scheduleHeavyWeightPaints() { Map hws; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java --- a/jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java Wed Jul 05 22:30:52 2017 +0200 @@ -416,6 +416,7 @@ * @param p a Point object (converted to the new coordinate system) * @param c a Component object */ + @SuppressWarnings("deprecation") public static void convertPointToScreen(Point p,Component c) { Rectangle b; int x,y; @@ -455,6 +456,7 @@ * @param p a Point object (converted to the new coordinate system) * @param c a Component object */ + @SuppressWarnings("deprecation") public static void convertPointFromScreen(Point p,Component c) { Rectangle b; int x,y; @@ -1655,6 +1657,7 @@ * @param c the component * @return the first ancestor of c that's a Window or the last Applet ancestor */ + @SuppressWarnings("deprecation") public static Component getRoot(Component c) { Component applet = null; for(Component p = c; p != null; p = p.getParent()) { @@ -1695,6 +1698,7 @@ * @return true if a binding has found and processed * @since 1.4 */ + @SuppressWarnings("deprecation") public static boolean processKeyBindings(KeyEvent event) { if (event != null) { if (event.isConsumed()) { @@ -2209,6 +2213,7 @@ * @see java.awt.Component#isVisible() * @since 1.7 */ + @SuppressWarnings("deprecation") static Container getValidateRoot(Container c, boolean visibleOnly) { Container root = null; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java --- a/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -753,6 +753,7 @@ // Returns: 0 no adjust // -1 can't fit // >0 adjust value by amount returned + @SuppressWarnings("deprecation") private int getPopupFitWidth(Rectangle popupRectInScreen, Component invoker){ if (invoker != null){ Container parent; @@ -778,6 +779,7 @@ // Returns: 0 no adjust // >0 adjust by value return + @SuppressWarnings("deprecation") private int getPopupFitHeight(Rectangle popupRectInScreen, Component invoker){ if (invoker != null){ Container parent; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/UIManager.java --- a/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/UIManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -513,6 +513,7 @@ * * @since 9 */ + @SuppressWarnings("deprecation") public static LookAndFeel createLookAndFeel(String name) throws UnsupportedLookAndFeelException { Objects.requireNonNull(name); @@ -526,14 +527,16 @@ if (info.getName().equals(name)) { Class cls = Class.forName(UIManager.class.getModule(), info.getClassName()); - LookAndFeel laf = (LookAndFeel) cls.newInstance(); + LookAndFeel laf = + (LookAndFeel) cls.newInstance(); if (!laf.isSupportedLookAndFeel()) { break; } return laf; } } - } catch (InstantiationException | IllegalAccessException ignore) { + } catch (ReflectiveOperationException | + IllegalArgumentException ignore) { } throw new UnsupportedLookAndFeelException(name); @@ -613,6 +616,7 @@ * @throws ClassCastException if {@code className} does not identify * a class that extends {@code LookAndFeel} */ + @SuppressWarnings("deprecation") public static void setLookAndFeel(String className) throws ClassNotFoundException, InstantiationException, @@ -625,7 +629,16 @@ } else { Class lnfClass = SwingUtilities.loadSystemClass(className); - setLookAndFeel((LookAndFeel)(lnfClass.newInstance())); + try { + LookAndFeel laf = + (LookAndFeel)lnfClass.newInstance(); + setLookAndFeel(laf); + } catch (ReflectiveOperationException | IllegalArgumentException e) { + InstantiationException ex = + new InstantiationException("Wrapped Exception"); + ex.initCause(e); + throw ex; + } } } @@ -1086,6 +1099,7 @@ /** * Finds the Multiplexing LookAndFeel. */ + @SuppressWarnings("deprecation") private static LookAndFeel getMultiLookAndFeel() { LookAndFeel multiLookAndFeel = getLAFState().multiLookAndFeel; if (multiLookAndFeel == null) { @@ -1093,7 +1107,8 @@ String className = getLAFState().swingProps.getProperty(multiplexingLAFKey, defaultName); try { Class lnfClass = SwingUtilities.loadSystemClass(className); - multiLookAndFeel = (LookAndFeel)lnfClass.newInstance(); + multiLookAndFeel = + (LookAndFeel)lnfClass.newInstance(); } catch (Exception exc) { System.err.println("UIManager: failed loading " + className); } @@ -1408,6 +1423,7 @@ } + @SuppressWarnings("deprecation") private static void initializeAuxiliaryLAFs(Properties swingProps) { String auxLookAndFeelNames = swingProps.getProperty(auxiliaryLAFsKey); @@ -1427,7 +1443,8 @@ String className = p.nextToken(); try { Class lnfClass = SwingUtilities.loadSystemClass(className); - LookAndFeel newLAF = (LookAndFeel)lnfClass.newInstance(); + LookAndFeel newLAF = + (LookAndFeel)lnfClass.newInstance(); newLAF.initialize(); auxLookAndFeels.addElement(newLAF); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java Wed Jul 05 22:30:52 2017 +0200 @@ -403,7 +403,7 @@ */ public static void drawString(JComponent c, Graphics2D g, String string, float x, float y) { - SwingUtilities2.drawString(c, g, string, (int) x, (int) y); + SwingUtilities2.drawString(c, g, string, x, y, true); } /** @@ -439,7 +439,7 @@ public static void drawStringUnderlineCharAt(JComponent c, Graphics2D g, String string, int underlinedIndex, float x, float y) { SwingUtilities2.drawStringUnderlineCharAt(c, g, string, underlinedIndex, - (int) x, (int) y); + x, y, true); } /** @@ -482,6 +482,6 @@ * @since 9 */ public static float getStringWidth(JComponent c, FontMetrics fm, String string) { - return SwingUtilities2.stringWidth(c, fm, string); + return SwingUtilities2.stringWidth(c, fm, string, true); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java Wed Jul 05 22:30:52 2017 +0200 @@ -926,6 +926,7 @@ } } + @SuppressWarnings("deprecation") boolean isInPopup(Component src) { for (Component c=src; c!=null; c=c.getParent()) { if (c instanceof Applet || c instanceof Window) { @@ -1143,6 +1144,7 @@ } } + @SuppressWarnings("deprecation") public void stateChanged(ChangeEvent ev) { if (!(UIManager.getLookAndFeel() instanceof BasicLookAndFeel)) { uninstall(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java Wed Jul 05 22:30:52 2017 +0200 @@ -1309,6 +1309,7 @@ * @see javax.swing.text.View#getToolTipText * @since 1.4 */ + @SuppressWarnings("deprecation") public String getToolTipText(JTextComponent t, Point pt) { if (!painted) { return null; @@ -2264,6 +2265,7 @@ *
  1. the press event is located over a selection * */ + @SuppressWarnings("deprecation") protected boolean isDragPossible(MouseEvent e) { JTextComponent c = (JTextComponent)e.getSource(); if (c.isEnabled()) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiTextUI.java --- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiTextUI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/multi/MultiTextUI.java Wed Jul 05 22:30:52 2017 +0200 @@ -85,6 +85,7 @@ * the UI obtained from the default LookAndFeel * @since 1.4 */ + @SuppressWarnings("deprecation") public String getToolTipText(JTextComponent a, Point b) { String returnValue = ((TextUI) (uis.elementAt(0))).getToolTipText(a,b); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java Wed Jul 05 22:30:52 2017 +0200 @@ -304,6 +304,7 @@ * * @param e the mouse event */ + @SuppressWarnings("deprecation") protected void positionCaret(MouseEvent e) { Point pt = new Point(e.getX(), e.getY()); Position.Bias[] biasRet = new Position.Bias[1]; @@ -323,6 +324,7 @@ * * @param e the mouse event */ + @SuppressWarnings("deprecation") protected void moveCaret(MouseEvent e) { Point pt = new Point(e.getX(), e.getY()); Position.Bias[] biasRet = new Position.Bias[1]; @@ -615,6 +617,7 @@ * @param g the graphics context * @see #damage */ + @SuppressWarnings("deprecation") public void paint(Graphics g) { if(isVisible()) { try { @@ -959,6 +962,7 @@ * @see #isActive * @see Caret#setVisible */ + @SuppressWarnings("deprecation") public void setVisible(boolean e) { // focus lost notification can come in later after the // caret has been deinstalled, in which case the component @@ -1301,6 +1305,7 @@ * event thread so that calling modelToView * is safe. */ + @SuppressWarnings("deprecation") void repaintNewCaret() { if (component != null) { TextUI mapper = component.getUI(); @@ -1664,6 +1669,7 @@ * * @param e the action event */ + @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { if (width == 0 || height == 0) { // setVisible(true) will cause a scroll, only do this if the diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultEditorKit.java Wed Jul 05 22:30:52 2017 +0200 @@ -1429,6 +1429,7 @@ } /** The operation to perform when this action is triggered. */ + @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if (target != null) { @@ -1542,6 +1543,7 @@ * Returns adjustsed {@code y} position that indicates the location to scroll to * after selecting index. */ + @SuppressWarnings("deprecation") private int getAdjustedY(JTextComponent text, Rectangle visible, int index) { int result = visible.y; @@ -1589,6 +1591,7 @@ } /** The operation to perform when this action is triggered. */ + @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if (target != null) { @@ -1672,6 +1675,7 @@ } /** The operation to perform when this action is triggered. */ + @SuppressWarnings("deprecation") public void actionPerformed(ActionEvent e) { JTextComponent target = getTextComponent(e); if (target != null) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultHighlighter.java Wed Jul 05 22:30:52 2017 +0200 @@ -405,6 +405,7 @@ * @param bounds the bounding box for the highlight * @param c the editor */ + @SuppressWarnings("deprecation") public void paint(Graphics g, int offs0, int offs1, Shape bounds, JTextComponent c) { Rectangle alloc = bounds.getBounds(); try { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/FieldView.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/FieldView.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/FieldView.java Wed Jul 05 22:30:52 2017 +0200 @@ -205,6 +205,7 @@ * that is returned, although there is no guarantee. * The parent may choose to resize or break the view. */ + @SuppressWarnings("deprecation") public float getPreferredSpan(int axis) { switch (axis) { case View.X_AXIS: diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java Wed Jul 05 22:30:52 2017 +0200 @@ -785,6 +785,7 @@ * @param p the point to calculate a drop location for * @return the drop location, or null */ + @SuppressWarnings("deprecation") DropLocation dropLocationForPoint(Point p) { Position.Bias[] bias = new Position.Bias[1]; int index = getUI().viewToModel(this, p, bias); @@ -1959,6 +1960,7 @@ * @see javax.swing.plaf.TextUI#getToolTipText * @see javax.swing.ToolTipManager#registerComponent */ + @SuppressWarnings("deprecation") public String getToolTipText(MouseEvent event) { String retValue = super.getToolTipText(event); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/ParagraphView.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/ParagraphView.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/ParagraphView.java Wed Jul 05 22:30:52 2017 +0200 @@ -178,6 +178,7 @@ * @return the location in the model that represents the * next location visual position */ + @SuppressWarnings("deprecation") protected int getNextNorthSouthVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) @@ -252,6 +253,7 @@ // NOTE: This will not properly work if ParagraphView contains // other ParagraphViews. It won't raise, but this does not message // the children views with getNextVisualPositionFrom. + @SuppressWarnings("deprecation") protected int getClosestPositionTo(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet, int rowIndex, int x) diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/PasswordView.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/PasswordView.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/PasswordView.java Wed Jul 05 22:30:52 2017 +0200 @@ -84,6 +84,7 @@ return drawUnselectedTextImpl(g, x, y, p0, p1, true); } + @SuppressWarnings("deprecation") private float drawUnselectedTextImpl(Graphics g, float x, float y, int p0, int p1, boolean useFPAPI) @@ -152,6 +153,7 @@ return drawSelectedTextImpl(g, x, y, p0, p1, true); } + @SuppressWarnings("deprecation") private float drawSelectedTextImpl(Graphics g, float x, float y, int p0, int p1, boolean useFPAPI) diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/PlainView.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/PlainView.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/PlainView.java Wed Jul 05 22:30:52 2017 +0200 @@ -471,6 +471,7 @@ * represent a valid location in the associated document * @see View#modelToView */ + @SuppressWarnings("deprecation") public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { // line coordinates Document doc = getDocument(); @@ -798,6 +799,7 @@ * the given element. It is assumed that the font * and font metrics are up-to-date. */ + @SuppressWarnings("deprecation") private int getLineWidth(Element line) { if (line == null) { return 0; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/Utilities.java Wed Jul 05 22:30:52 2017 +0200 @@ -107,7 +107,7 @@ TabExpander e, int startOffset) { - return drawTabbedText(s, (int) x, (int) y, (Graphics) g, e, startOffset); + return drawTabbedText(null, s, x, y, g, e, startOffset, null, true); } /** @@ -672,6 +672,7 @@ * a value of -1 will be returned. * @exception BadLocationException if the offset is out of range */ + @SuppressWarnings("deprecation") public static final int getRowStart(JTextComponent c, int offs) throws BadLocationException { Rectangle r = c.modelToView(offs); if (r == null) { @@ -702,6 +703,7 @@ * a value of -1 will be returned. * @exception BadLocationException if the offset is out of range */ + @SuppressWarnings("deprecation") public static final int getRowEnd(JTextComponent c, int offs) throws BadLocationException { Rectangle2D r = c.modelToView2D(offs); if (r == null) { @@ -744,6 +746,7 @@ return getPositionAbove(c, offs, x, false); } + @SuppressWarnings("deprecation") static final int getPositionAbove(JTextComponent c, int offs, float x, boolean useFPAPI) throws BadLocationException { @@ -818,6 +821,7 @@ return getPositionBelow(c, offs, x, false); } + @SuppressWarnings("deprecation") static final int getPositionBelow(JTextComponent c, int offs, float x, boolean useFPAPI) throws BadLocationException { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/View.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/View.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/View.java Wed Jul 05 22:30:52 2017 +0200 @@ -501,6 +501,7 @@ * @exception IllegalArgumentException if direction * doesn't have one of the legal values above */ + @SuppressWarnings("deprecation") public int getNextVisualPositionFrom(int pos, Position.Bias b, Shape a, int direction, Position.Bias[] biasRet) throws BadLocationException { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/WrappedPlainView.java Wed Jul 05 22:30:52 2017 +0200 @@ -352,6 +352,7 @@ * @param p1 the ending document location to use * @return the break position */ + @SuppressWarnings("deprecation") protected int calculateBreakPosition(int p0, int p1) { int p; Segment segment = SegmentCache.getSharedSegment(); @@ -749,6 +750,7 @@ * valid location in the associated document * @see View#modelToView */ + @SuppressWarnings("deprecation") public Shape modelToView(int pos, Shape a, Position.Bias b) throws BadLocationException { Rectangle alloc = a.getBounds(); @@ -793,6 +795,7 @@ * given point in the view * @see View#viewToModel */ + @SuppressWarnings("deprecation") public int viewToModel(float fx, float fy, Shape a, Position.Bias[] bias) { // PENDING(prinz) implement bias properly bias[0] = Position.Bias.Forward; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/html/AccessibleHTML.java Wed Jul 05 22:30:52 2017 +0200 @@ -936,6 +936,7 @@ * @return the screen coordinates of the character's the bounding box, * if index is invalid returns an empty rectangle. */ + @SuppressWarnings("deprecation") public Rectangle getCharacterBounds(int i) { try { return editor.getUI().modelToView(editor, i); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/html/HTMLEditorKit.java Wed Jul 05 22:30:52 2017 +0200 @@ -683,6 +683,7 @@ * @param e the mouse event * @see MouseListener#mouseClicked */ + @SuppressWarnings("deprecation") public void mouseClicked(MouseEvent e) { JEditorPane editor = (JEditorPane) e.getSource(); @@ -701,6 +702,7 @@ } // track the moving of the mouse. + @SuppressWarnings("deprecation") public void mouseMoved(MouseEvent e) { JEditorPane editor = (JEditorPane) e.getSource(); if (!editor.isEnabled()) { @@ -773,6 +775,7 @@ * Returns a string anchor if the passed in element has a * USEMAP that contains the passed in location. */ + @SuppressWarnings("deprecation") private String getMapHREF(JEditorPane html, HTMLDocument hdoc, Element elem, AttributeSet attr, int offset, int x, int y) { @@ -813,6 +816,7 @@ * the location x, y. offset * gives the offset into the Document to check for. */ + @SuppressWarnings("deprecation") private boolean doesElementContainLocation(JEditorPane editor, Element e, int offset, int x, int y) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java --- a/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/javax/swing/text/html/ObjectView.java Wed Jul 05 22:30:52 2017 +0200 @@ -85,6 +85,7 @@ * as a specification of the classname, which * we try to load. */ + @SuppressWarnings("deprecation") protected Component createComponent() { AttributeSet attr = getElement().getAttributes(); String classname = (String) attr.getAttribute(HTML.Attribute.CLASSID); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/applet/AppletAudioClip.java --- a/jdk/src/java.desktop/share/classes/sun/applet/AppletAudioClip.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/applet/AppletAudioClip.java Wed Jul 05 22:30:52 2017 +0200 @@ -41,6 +41,7 @@ * @author Arthur van Hoff, Kara Kytle */ +@SuppressWarnings("deprecation") public class AppletAudioClip implements AudioClip { // url that this AudioClip is based on diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/applet/AppletPanel.java --- a/jdk/src/java.desktop/share/classes/sun/applet/AppletPanel.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/applet/AppletPanel.java Wed Jul 05 22:30:52 2017 +0200 @@ -54,7 +54,7 @@ * * @author Arthur van Hoff */ -@SuppressWarnings("serial") // JDK implementation class +@SuppressWarnings({"serial", "deprecation"}) // JDK implementation class public abstract class AppletPanel extends Panel implements AppletStub, Runnable { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/applet/AppletViewer.java --- a/jdk/src/java.desktop/share/classes/sun/applet/AppletViewer.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/applet/AppletViewer.java Wed Jul 05 22:30:52 2017 +0200 @@ -117,7 +117,7 @@ * (The document named appletviewertags.html in the JDK's docs/tooldocs directory, * once the JDK docs have been installed.) */ -@SuppressWarnings("serial") // JDK implementation class +@SuppressWarnings({"serial", "deprecation"}) // JDK-implementation class public class AppletViewer extends Frame implements AppletContext, Printable { /** @@ -157,7 +157,6 @@ /** * Create the applet viewer. */ - @SuppressWarnings("deprecation") public AppletViewer(int x, int y, URL doc, Hashtable atts, PrintStream statusMsgStream, AppletViewerFactory factory) { this.factory = factory; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/applet/AppletViewerPanel.java --- a/jdk/src/java.desktop/share/classes/sun/applet/AppletViewerPanel.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/applet/AppletViewerPanel.java Wed Jul 05 22:30:52 2017 +0200 @@ -197,6 +197,7 @@ * Get the applet context. For now this is * also implemented by the AppletPanel class. */ + @SuppressWarnings("deprecation") public AppletContext getAppletContext() { return (AppletContext)getParent(); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/awt/EmbeddedFrame.java --- a/jdk/src/java.desktop/share/classes/sun/awt/EmbeddedFrame.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/awt/EmbeddedFrame.java Wed Jul 05 22:30:52 2017 +0200 @@ -499,6 +499,7 @@ * @return the parent applet or {@ null} * @since 1.6 */ + @SuppressWarnings("deprecation") public static Applet getAppletIfAncestorOf(Component comp) { Container parent = comp.getParent(); Applet applet = null; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/awt/FontConfiguration.java --- a/jdk/src/java.desktop/share/classes/sun/awt/FontConfiguration.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/awt/FontConfiguration.java Wed Jul 05 22:30:52 2017 +0200 @@ -971,7 +971,7 @@ if (fcc != null) { try { - fc = (Charset) fcc.newInstance(); + fc = (Charset) fcc.getDeclaredConstructor().newInstance(); } catch (Exception e) { } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/awt/LightweightFrame.java --- a/jdk/src/java.desktop/share/classes/sun/awt/LightweightFrame.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/awt/LightweightFrame.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 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 @@ -141,17 +141,52 @@ * * @return the scale factor * @see #notifyDisplayChanged(int) + * @Depricated replaced by {@link #getScaleFactorX()} and + * {@link #getScaleFactorY} */ + @Deprecated(since = "9") public abstract int getScaleFactor(); /** + * Returns the scale factor of this frame along x coordinate. The default + * value is 1. + * + * @return the x coordinate scale factor + * @see #notifyDisplayChanged(double, double) + * @since 9 + */ + public abstract double getScaleFactorX(); + + /** + * Returns the scale factor of this frame along y coordinate. The default + * value is 1. + * + * @return the y coordinate scale factor + * @see #notifyDisplayChanged(double, double) + * @since 9 + */ + public abstract double getScaleFactorY(); + + /** * Called when display of the hosted frame is changed. * * @param scaleFactor the scale factor + * @Depricated replaced by {@link #notifyDisplayChanged(double, double)} */ + @Deprecated(since = "9") public abstract void notifyDisplayChanged(int scaleFactor); /** + * Called when display of the hosted frame is changed. + * + * @param scaleFactorX the scale factor + * @param scaleFactorY the scale factor + * @since 9 + */ + public abstract void notifyDisplayChanged(double scaleFactorX, + double scaleFactorY); + + /** * Host window absolute bounds. */ private int hostX, hostY, hostW, hostH; @@ -202,4 +237,5 @@ * Removes a drop target from the lightweight frame. */ public abstract void removeDropTarget(DropTarget dt); + } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java --- a/jdk/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/awt/image/GifImageDecoder.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -31,7 +31,6 @@ */ package sun.awt.image; -import java.util.Vector; import java.util.Hashtable; import java.io.InputStream; import java.io.IOException; @@ -620,7 +619,6 @@ class GifFrame { private static final boolean verbose = false; - private static IndexColorModel trans_model; static final int DISPOSAL_NONE = 0x00; static final int DISPOSAL_SAVE = 0x01; @@ -718,12 +716,6 @@ case DISPOSAL_BGCOLOR: byte tpix; if (model.getTransparentPixel() < 0) { - model = trans_model; - if (model == null) { - model = new IndexColorModel(8, 1, - new byte[4], 0, true); - trans_model = model; - } tpix = 0; } else { tpix = (byte) model.getTransparentPixel(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/awt/image/VolatileSurfaceManager.java --- a/jdk/src/java.desktop/share/classes/sun/awt/image/VolatileSurfaceManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/awt/image/VolatileSurfaceManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -55,6 +55,15 @@ protected SunVolatileImage vImg; /** + * A reference to the AffineTransform corresponding to the graphics + * configuration of the volatile image. Affine Transformation is usually + * derived from the screen device. During the displayChanged() callback, + * the existing transform is compared with the updated screen transform to + * determine whether the software backed surface needs to be re-created + */ + protected AffineTransform atCurrent; + + /** * The accelerated SurfaceData object. */ protected SurfaceData sdAccel; @@ -93,6 +102,7 @@ protected VolatileSurfaceManager(SunVolatileImage vImg, Object context) { this.vImg = vImg; this.context = context; + this.atCurrent = vImg.getGraphicsConfig().getDefaultTransform(); GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); @@ -210,6 +220,10 @@ sdCurrent = getBackupSurface(); sdAccel = null; returnCode = VolatileImage.IMAGE_RESTORED; + } else if (lostSurfaceTmp) { + // A software surface has been restored. This could be due to + // display mode change on a non-accelerated volatile image. + returnCode = VolatileImage.IMAGE_RESTORED; } if ((returnCode != VolatileImage.IMAGE_INCOMPATIBLE) && @@ -326,9 +340,6 @@ * method in the rendering process to recreate the surface. */ public void displayChanged() { - if (!isAccelerationEnabled()) { - return; - } lostSurface = true; if (sdAccel != null) { // First, nullify the software surface. This guards against @@ -345,6 +356,28 @@ // Update graphicsConfig for the vImg in case it changed due to // this display change event vImg.updateGraphicsConfig(); + + // Compare the Graphics configuration transforms to determine + // whether the software backed surface needs to be invalidated. + AffineTransform atUpdated = vImg.getGraphicsConfig() + .getDefaultTransform(); + if (!isAccelerationEnabled()) { + if (!atUpdated.equals(atCurrent)) { + // Ideally there is no need to re-create a software surface. + // But some OSs allow changes to display state at runtime. Such + // a provision would cause mismatch in graphics configuration of + // the display and the surface. Hence we re-create the software + // surface as well. + sdBackup = null; + sdCurrent = getBackupSurface(); + } else { + // Software backed surface was not invalidated. + lostSurface = false; + } + } + + // Update the AffineTransformation backing the volatile image + atCurrent = atUpdated; } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java --- a/jdk/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/awt/shell/ShellFolder.java Wed Jul 05 22:30:52 2017 +0200 @@ -226,13 +226,10 @@ } try { shellFolderManager = - (ShellFolderManager)managerClass.newInstance(); - } catch (InstantiationException e) { + (ShellFolderManager)managerClass.getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException e) { throw new Error("Could not instantiate Shell Folder Manager: " + managerClass.getName()); - } catch (IllegalAccessException e) { - throw new Error ("Could not access Shell Folder Manager: " - + managerClass.getName()); } invoker = shellFolderManager.createInvoker(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/font/FontManagerFactory.java --- a/jdk/src/java.desktop/share/classes/sun/font/FontManagerFactory.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/font/FontManagerFactory.java Wed Jul 05 22:30:52 2017 +0200 @@ -80,10 +80,9 @@ DEFAULT_CLASS); ClassLoader cl = ClassLoader.getSystemClassLoader(); Class fmClass = Class.forName(fmClassName, true, cl); - instance = (FontManager) fmClass.newInstance(); - } catch (ClassNotFoundException | - InstantiationException | - IllegalAccessException ex) { + instance = + (FontManager) fmClass.getDeclaredConstructor().newInstance(); + } catch (ReflectiveOperationException ex) { throw new InternalError(ex); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java --- a/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/font/SunFontManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -362,6 +362,14 @@ }); } + /** + * If the module image layout changes the location of JDK fonts, + * this will be updated to reflect that. + */ + public static final String getJDKFontDir() { + return jreFontDirName; + } + public TrueTypeFont getEUDCFont() { // Overridden in Windows. return null; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/font/lookup/JDKFontLookup.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/java.desktop/share/classes/sun/font/lookup/JDKFontLookup.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. Oracle designates this + * particular file as subject to the "Classpath" exception as provided + * by Oracle in the LICENSE file that accompanied this code. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package sun.font.lookup; + +import sun.font.SunFontManager; + +/** + * Implementation-class accessed by other JDK modules to + * locate the JDK-provided fonts. + */ +public final class JDKFontLookup { + + public final static String getJDKFontDir() { + return SunFontManager.getJDKFontDir(); + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java --- a/jdk/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/java2d/cmm/CMSManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -57,7 +57,7 @@ if (cmmProviderClass != null) { try { Class cls = Class.forName(cmmProviderClass); - provider = (CMMServiceProvider)cls.newInstance(); + provider = (CMMServiceProvider)cls.getConstructor().newInstance(); } catch (ReflectiveOperationException e) { } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveProxy.java --- a/jdk/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveProxy.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/java2d/loops/GraphicsPrimitiveProxy.java Wed Jul 05 22:30:52 2017 +0200 @@ -81,18 +81,15 @@ + relativeClassName; try { Class clazz = Class.forName(name); - GraphicsPrimitive p = (GraphicsPrimitive) clazz.newInstance(); + GraphicsPrimitive p = + (GraphicsPrimitive) clazz.getDeclaredConstructor().newInstance(); if (!satisfiesSameAs(p)) { throw new RuntimeException("Primitive " + p + " incompatible with proxy for " + name); } return p; - } catch (ClassNotFoundException ex) { - throw new RuntimeException(ex.toString()); - } catch (InstantiationException ex) { - throw new RuntimeException(ex.toString()); - } catch (IllegalAccessException ex) { + } catch (ReflectiveOperationException ex) { throw new RuntimeException(ex.toString()); } // A RuntimeException should never happen in a deployed JDK, because diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java --- a/jdk/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/java2d/pipe/RenderingEngine.java Wed Jul 05 22:30:52 2017 +0200 @@ -127,7 +127,7 @@ if (reClass != null) { try { Class cls = Class.forName(reClass); - reImpl = (RenderingEngine) cls.newInstance(); + reImpl = (RenderingEngine) cls.getConstructor().newInstance(); } catch (ReflectiveOperationException ignored0) { } } @@ -135,7 +135,7 @@ final String marlinREClass = "sun.java2d.marlin.MarlinRenderingEngine"; try { Class cls = Class.forName(marlinREClass); - reImpl = (RenderingEngine) cls.newInstance(); + reImpl = (RenderingEngine) cls.getConstructor().newInstance(); } catch (ReflectiveOperationException ignored1) { } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java --- a/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/swing/JLightweightFrame.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 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 @@ -25,18 +25,7 @@ package sun.swing; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Container; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.MouseInfo; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.Window; +import java.awt.*; import java.awt.dnd.DragGestureEvent; import java.awt.dnd.DragGestureListener; import java.awt.dnd.DragGestureRecognizer; @@ -46,6 +35,7 @@ import java.awt.dnd.peer.DragSourceContextPeer; import java.awt.event.ContainerEvent; import java.awt.event.ContainerListener; +import java.awt.geom.AffineTransform; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.beans.PropertyChangeEvent; @@ -89,7 +79,8 @@ private BufferedImage bbImage; - private volatile int scaleFactor = 1; + private volatile double scaleFactorX; + private volatile double scaleFactorY; /** * {@code copyBufferEnabled}, true by default, defines the following strategy. @@ -124,6 +115,10 @@ */ public JLightweightFrame() { super(); + AffineTransform defaultTransform = + getGraphicsConfiguration().getDefaultTransform(); + scaleFactorX = defaultTransform.getScaleX(); + scaleFactorY = defaultTransform.getScaleY(); copyBufferEnabled = "true".equals(AccessController. doPrivileged(new GetPropertyAction("swing.jlf.copyBufferEnabled", "true"))); @@ -157,8 +152,9 @@ } Point p = SwingUtilities.convertPoint(c, x, y, jlf); Rectangle r = new Rectangle(p.x, p.y, w, h).intersection( - new Rectangle(0, 0, bbImage.getWidth() / scaleFactor, - bbImage.getHeight() / scaleFactor)); + new Rectangle(0, 0, + (int)Math.round(bbImage.getWidth() / scaleFactorX), + (int)Math.round(bbImage.getHeight() / scaleFactorY))); if (!r.isEmpty()) { notifyImageUpdated(r.x, r.y, r.width, r.height); @@ -212,7 +208,7 @@ g.setBackground(getBackground()); g.setColor(getForeground()); g.setFont(getFont()); - g.scale(scaleFactor, scaleFactor); + g.scale(scaleFactorX, scaleFactorY); return g; } @@ -237,28 +233,53 @@ } @Override + @SuppressWarnings("deprecation") public int getScaleFactor() { - return scaleFactor; + return (int)scaleFactorX; + } + + @Override + public double getScaleFactorX() { + return scaleFactorX; + } + + @Override + public double getScaleFactorY() { + return scaleFactorY; } @Override + @SuppressWarnings("deprecation") public void notifyDisplayChanged(final int scaleFactor) { - if (scaleFactor != this.scaleFactor) { + notifyDisplayChanged(scaleFactor, scaleFactor); + } + + @Override + public void notifyDisplayChanged(final double scaleFactorX, + final double scaleFactorY) { + if (Double.compare(scaleFactorX, this.scaleFactorX) != 0 || + Double.compare(scaleFactorY, this.scaleFactorY) != 0) { if (!copyBufferEnabled) content.paintLock(); try { if (bbImage != null) { - resizeBuffer(getWidth(), getHeight(), scaleFactor); + resizeBuffer(getWidth(), getHeight(), scaleFactorX, + scaleFactorY); } } finally { if (!copyBufferEnabled) content.paintUnlock(); } - this.scaleFactor = scaleFactor; + this.scaleFactorX = scaleFactorX; + this.scaleFactorY = scaleFactorY; + + if(isVisible()) { + final Object peer = + AWTAccessor.getComponentAccessor().getPeer(this); + if (peer instanceof DisplayChangedListener) { + ((DisplayChangedListener) peer).displayChanged(); + } + repaint(); + } } - final Object peer = AWTAccessor.getComponentAccessor().getPeer(this); - if (peer instanceof DisplayChangedListener) { - ((DisplayChangedListener) peer).displayChanged(); - } - repaint(); } @Override @@ -270,7 +291,8 @@ } } - private void syncCopyBuffer(boolean reset, int x, int y, int w, int h, int scale) { + private void syncCopyBuffer(boolean reset, int x, int y, int w, int h, + double scaleX, double scaleY) { content.paintLock(); try { int[] srcBuffer = ((DataBufferInt)bbImage.getRaster().getDataBuffer()).getData(); @@ -279,14 +301,14 @@ } int linestride = bbImage.getWidth(); - x *= scale; - y *= scale; - w *= scale; - h *= scale; + int startX = (int)Math.floor(x * scaleX); + int startY = (int)Math.floor(y * scaleY); + int width = (int)Math.ceil((x + w) * scaleX) - startX; + int height = (int)Math.ceil((y + h) * scaleY) - startY; - for (int i=0; i + * The method reports a reference to the pixel data buffer, the content + * image bounds within the buffer and the line stride of the buffer. + * These values have the following correlation. + * The {@code width} and {@code height} matches the layout size of the + * content (the component returned from the {@link #getComponent} method). + * The {@code x} and {@code y} is the origin of the content, {@code (0, 0)} + * in the layout coordinate space of the content, appearing at + * {@code data[y * scaleY * linestride + x * scaleX]} in the buffer. + * A pixel with indices {@code (i, j)}, where {@code (0 <= i < width)} and + * {@code (0 <= j < height)}, in the layout coordinate space of the content + * is represented by a {@code scaleX * scaleY} square of pixels in the + * physical coordinate space of the buffer. The top-left corner of the + * square has the following physical coordinate in the buffer: + * {@code data[(y + j) * scaleY * linestride + (x + i) * scaleX]}. + * + * @param data the content pixel data buffer of INT_ARGB_PRE type + * @param x the logical x coordinate of the image + * @param y the logical y coordinate of the image + * @param width the logical width of the image + * @param height the logical height of the image + * @param linestride the line stride of the pixel buffer + * @param scaleX the x coordinate scale factor of the pixel buffer + * @param scaleY the y coordinate scale factor of the pixel buffer + * @since 9 + */ + @SuppressWarnings("deprecation") + default public void imageBufferReset(int[] data, + int x, int y, + int width, int height, + int linestride, + double scaleX, double scaleY) + { + imageBufferReset(data, x, y, width, height, linestride, + (int)Math.round(scaleX)); + } + + /** * The default implementation for #imageBufferReset uses a hard-coded value * of 1 for the scale factor. Both the old and the new methods provide * default implementations in order to allow a client application to run * with any JDK version without breaking backward compatibility. */ + @SuppressWarnings("deprecation") default public void imageBufferReset(int[] data, int x, int y, int width, int height, diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java --- a/jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java Wed Jul 05 22:30:52 2017 +0200 @@ -318,7 +318,21 @@ * @param fm FontMetrics used to measure the String width * @param string String to get the width of */ - public static int stringWidth(JComponent c, FontMetrics fm, String string){ + public static int stringWidth(JComponent c, FontMetrics fm, String string) { + return (int) stringWidth(c, fm, string, false); + } + + /** + * Returns the width of the passed in String. + * If the passed String is {@code null}, returns zero. + * + * @param c JComponent that will display the string, may be null + * @param fm FontMetrics used to measure the String width + * @param string String to get the width of + * @param useFPAPI use floating point API + */ + public static float stringWidth(JComponent c, FontMetrics fm, String string, + boolean useFPAPI){ if (string == null || string.equals("")) { return 0; } @@ -333,9 +347,9 @@ if (needsTextLayout) { TextLayout layout = createTextLayout(c, string, fm.getFont(), fm.getFontRenderContext()); - return (int) layout.getAdvance(); + return layout.getAdvance(); } else { - return fm.stringWidth(string); + return getFontStringWidth(string, fm, useFPAPI); } } @@ -426,6 +440,21 @@ */ public static void drawString(JComponent c, Graphics g, String text, int x, int y) { + drawString(c, g, text, x, y, false); + } + + /** + * Draws the string at the specified location. + * + * @param c JComponent that will display the string, may be null + * @param g Graphics to draw the text to + * @param text String to display + * @param x X coordinate to draw the text at + * @param y Y coordinate to draw the text at + * @param useFPAPI use floating point API + */ + public static void drawString(JComponent c, Graphics g, String text, + float x, float y, boolean useFPAPI) { // c may be null // All non-editable widgets that draw strings call into this @@ -509,7 +538,7 @@ g2.getFontRenderContext()); layout.draw(g2, x, y); } else { - g.drawString(text, x, y); + g2.drawString(text, x, y); } if (oldAAValue != null) { @@ -530,7 +559,7 @@ } } - g.drawString(text, x, y); + g.drawString(text, (int) x, (int) y); } /** @@ -544,17 +573,36 @@ * @param x X coordinate to draw the text at * @param y Y coordinate to draw the text at */ + public static void drawStringUnderlineCharAt(JComponent c,Graphics g, - String text, int underlinedIndex, int x,int y) { + String text, int underlinedIndex, int x, int y) { + drawStringUnderlineCharAt(c, g, text, underlinedIndex, x, y, false); + } + /** + * Draws the string at the specified location underlining the specified + * character. + * + * @param c JComponent that will display the string, may be null + * @param g Graphics to draw the text to + * @param text String to display + * @param underlinedIndex Index of a character in the string to underline + * @param x X coordinate to draw the text at + * @param y Y coordinate to draw the text at + * @param useFPAPI use floating point API + */ + public static void drawStringUnderlineCharAt(JComponent c, Graphics g, + String text, int underlinedIndex, + float x, float y, + boolean useFPAPI) { if (text == null || text.length() <= 0) { return; } - SwingUtilities2.drawString(c, g, text, x, y); + SwingUtilities2.drawString(c, g, text, x, y, useFPAPI); int textLength = text.length(); if (underlinedIndex >= 0 && underlinedIndex < textLength ) { - int underlineRectY = y; + float underlineRectY = y; int underlineRectHeight = 1; - int underlineRectX = 0; + float underlineRectX = 0; int underlineRectWidth = 0; boolean isPrinting = isPrinting(g); boolean needsTextLayout = isPrinting; @@ -594,7 +642,7 @@ underlineRectWidth = rect.width; } } - g.fillRect(underlineRectX, underlineRectY + 1, + g.fillRect((int) underlineRectX, (int) underlineRectY + 1, underlineRectWidth, underlineRectHeight); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java --- a/jdk/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/share/classes/sun/swing/text/TextComponentPrintable.java Wed Jul 05 22:30:52 2017 +0200 @@ -753,6 +753,7 @@ * First step is to find yStart and yEnd for the every document position. * Second step is to merge all intersected segments ( [yStart, yEnd] ). */ + @SuppressWarnings("deprecation") private void calculateRowsMetrics() { final int documentLength = printShell.getDocument().getLength(); List documentMetrics = new ArrayList(LIST_SIZE); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/unix/classes/sun/font/XMap.java --- a/jdk/src/java.desktop/unix/classes/sun/font/XMap.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/unix/classes/sun/font/XMap.java Wed Jul 05 22:30:52 2017 +0200 @@ -172,7 +172,8 @@ if (className != null) { try { if (className.startsWith("sun.awt")) { - enc = ((Charset)Class.forName(className).newInstance()).newEncoder(); + enc = ((Charset)Class.forName(className).getDeclaredConstructor(). + newInstance()).newEncoder(); } else { enc = Charset.forName(className).newEncoder(); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/windows/native/libawt/java2d/windows/GDIWindowSurfaceData.cpp --- a/jdk/src/java.desktop/windows/native/libawt/java2d/windows/GDIWindowSurfaceData.cpp Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/windows/native/libawt/java2d/windows/GDIWindowSurfaceData.cpp Wed Jul 05 22:30:52 2017 +0200 @@ -128,7 +128,7 @@ return; } hDC = comp->GetDCFromComponent(); - if (hDC != NULL) { + if (hDC != NULL && wsdo->device != NULL) { ::SelectObject(hDC, nullbrush); ::SelectObject(hDC, nullpen); ::SelectClipRgn(hDC, (HRGN) NULL); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp Wed Jul 05 22:30:52 2017 +0200 @@ -3523,7 +3523,7 @@ WORD wChar[2]; int converted = 1; - UINT ch = ::MapVirtualKey(wkey, 2); + UINT ch = ::MapVirtualKeyEx(wkey, 2, GetKeyboardLayout()); if (ch & 0x80000000) { // Dead key which is handled as a normal key isDeadKey = deadKeyActive = TRUE; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.cpp --- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.cpp Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Taskbar.cpp Wed Jul 05 22:30:52 2017 +0200 @@ -58,7 +58,11 @@ JNIEXPORT void JNICALL Java_sun_awt_windows_WTaskbarPeer_setProgressValue (JNIEnv *, jobject, jlong window, jint value) { - m_Taskbar->SetProgressValue((HWND)window, value, 100); + if (value < 0 || value > 100) { + m_Taskbar->SetProgressState((HWND)window, TBPF_NOPROGRESS); + } else { + m_Taskbar->SetProgressValue((HWND)window, value, 100); + } } @@ -88,6 +92,9 @@ flag = TBPF_NOPROGRESS; } else if (strcmp(valueNative, "NORMAL") == 0) { flag = TBPF_NORMAL; + + // Switching from TBPF_INDETERMINATE to TBPF_NORMAL has no effect + m_Taskbar->SetProgressState((HWND)window, TBPF_PAUSED); } else if (strcmp(valueNative, "PAUSED") == 0) { flag = TBPF_PAUSED; } else if (strcmp(valueNative, "INDETERMINATE") == 0) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.accessibility/windows/native/bridge/AccessBridgeCalls.c --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/src/jdk.accessibility/windows/native/bridge/AccessBridgeCalls.c Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,1130 @@ +/* + * + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * - Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * - Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * - Neither the name of Oracle nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS + * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, + * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR + * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR + * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, + * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, + * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR + * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING + * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +/* + * Wrapper functions around calls to the AccessBridge DLL + */ + + +#include +#include + + +//#define ACCESSBRIDGE_32 +//#define ACCESSBRIDGE_64 + +#include "AccessBridgeCalls.h" + +#ifdef __cplusplus +extern "C" { +#endif + + HINSTANCE theAccessBridgeInstance; + AccessBridgeFPs theAccessBridge; + + BOOL theAccessBridgeInitializedFlag = FALSE; + +#define LOAD_FP(result, type, name) \ + if ((theAccessBridge.result = \ + (type) GetProcAddress(theAccessBridgeInstance, name)) == (type) 0) { \ + return FALSE; \ + } + + BOOL initializeAccessBridge() { + +#ifdef ACCESSBRIDGE_ARCH_32 // For 32 bit AT interfacing with Java on 64 bit OS + theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE-32"); +#else +#ifdef ACCESSBRIDGE_ARCH_64 // For 64 bit AT interfacing with Java on 64 bit OS + theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE-64"); +#else // For 32 bit AT interfacing with Java on 32 bit OS + theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE"); +#endif +#endif + if (theAccessBridgeInstance != 0) { + LOAD_FP(Windows_run, Windows_runFP, "Windows_run"); + + LOAD_FP(SetJavaShutdown, SetJavaShutdownFP, "setJavaShutdownFP"); + LOAD_FP(SetFocusGained, SetFocusGainedFP, "setFocusGainedFP"); + LOAD_FP(SetFocusLost, SetFocusLostFP, "setFocusLostFP"); + + LOAD_FP(SetCaretUpdate, SetCaretUpdateFP, "setCaretUpdateFP"); + + LOAD_FP(SetMouseClicked, SetMouseClickedFP, "setMouseClickedFP"); + LOAD_FP(SetMouseEntered, SetMouseEnteredFP, "setMouseEnteredFP"); + LOAD_FP(SetMouseExited, SetMouseExitedFP, "setMouseExitedFP"); + LOAD_FP(SetMousePressed, SetMousePressedFP, "setMousePressedFP"); + LOAD_FP(SetMouseReleased, SetMouseReleasedFP, "setMouseReleasedFP"); + + LOAD_FP(SetMenuCanceled, SetMenuCanceledFP, "setMenuCanceledFP"); + LOAD_FP(SetMenuDeselected, SetMenuDeselectedFP, "setMenuDeselectedFP"); + LOAD_FP(SetMenuSelected, SetMenuSelectedFP, "setMenuSelectedFP"); + LOAD_FP(SetPopupMenuCanceled, SetPopupMenuCanceledFP, "setPopupMenuCanceledFP"); + LOAD_FP(SetPopupMenuWillBecomeInvisible, SetPopupMenuWillBecomeInvisibleFP, "setPopupMenuWillBecomeInvisibleFP"); + LOAD_FP(SetPopupMenuWillBecomeVisible, SetPopupMenuWillBecomeVisibleFP, "setPopupMenuWillBecomeVisibleFP"); + + LOAD_FP(SetPropertyNameChange, SetPropertyNameChangeFP, "setPropertyNameChangeFP"); + LOAD_FP(SetPropertyDescriptionChange, SetPropertyDescriptionChangeFP, "setPropertyDescriptionChangeFP"); + LOAD_FP(SetPropertyStateChange, SetPropertyStateChangeFP, "setPropertyStateChangeFP"); + LOAD_FP(SetPropertyValueChange, SetPropertyValueChangeFP, "setPropertyValueChangeFP"); + LOAD_FP(SetPropertySelectionChange, SetPropertySelectionChangeFP, "setPropertySelectionChangeFP"); + LOAD_FP(SetPropertyTextChange, SetPropertyTextChangeFP, "setPropertyTextChangeFP"); + LOAD_FP(SetPropertyCaretChange, SetPropertyCaretChangeFP, "setPropertyCaretChangeFP"); + LOAD_FP(SetPropertyVisibleDataChange, SetPropertyVisibleDataChangeFP, "setPropertyVisibleDataChangeFP"); + LOAD_FP(SetPropertyChildChange, SetPropertyChildChangeFP, "setPropertyChildChangeFP"); + LOAD_FP(SetPropertyActiveDescendentChange, SetPropertyActiveDescendentChangeFP, "setPropertyActiveDescendentChangeFP"); + + LOAD_FP(SetPropertyTableModelChange, SetPropertyTableModelChangeFP, "setPropertyTableModelChangeFP"); + + LOAD_FP(ReleaseJavaObject, ReleaseJavaObjectFP, "releaseJavaObject"); + LOAD_FP(GetVersionInfo, GetVersionInfoFP, "getVersionInfo"); + + LOAD_FP(IsJavaWindow, IsJavaWindowFP, "isJavaWindow"); + LOAD_FP(IsSameObject, IsSameObjectFP, "isSameObject"); + LOAD_FP(GetAccessibleContextFromHWND, GetAccessibleContextFromHWNDFP, "getAccessibleContextFromHWND"); + LOAD_FP(getHWNDFromAccessibleContext, getHWNDFromAccessibleContextFP, "getHWNDFromAccessibleContext"); + + LOAD_FP(GetAccessibleContextAt, GetAccessibleContextAtFP, "getAccessibleContextAt"); + LOAD_FP(GetAccessibleContextWithFocus, GetAccessibleContextWithFocusFP, "getAccessibleContextWithFocus"); + LOAD_FP(GetAccessibleContextInfo, GetAccessibleContextInfoFP, "getAccessibleContextInfo"); + LOAD_FP(GetAccessibleChildFromContext, GetAccessibleChildFromContextFP, "getAccessibleChildFromContext"); + LOAD_FP(GetAccessibleParentFromContext, GetAccessibleParentFromContextFP, "getAccessibleParentFromContext"); + + /* begin AccessibleTable */ + LOAD_FP(getAccessibleTableInfo, getAccessibleTableInfoFP, "getAccessibleTableInfo"); + LOAD_FP(getAccessibleTableCellInfo, getAccessibleTableCellInfoFP, "getAccessibleTableCellInfo"); + + LOAD_FP(getAccessibleTableRowHeader, getAccessibleTableRowHeaderFP, "getAccessibleTableRowHeader"); + LOAD_FP(getAccessibleTableColumnHeader, getAccessibleTableColumnHeaderFP, "getAccessibleTableColumnHeader"); + + LOAD_FP(getAccessibleTableRowDescription, getAccessibleTableRowDescriptionFP, "getAccessibleTableRowDescription"); + LOAD_FP(getAccessibleTableColumnDescription, getAccessibleTableColumnDescriptionFP, "getAccessibleTableColumnDescription"); + + LOAD_FP(getAccessibleTableRowSelectionCount, getAccessibleTableRowSelectionCountFP, + "getAccessibleTableRowSelectionCount"); + LOAD_FP(isAccessibleTableRowSelected, isAccessibleTableRowSelectedFP, + "isAccessibleTableRowSelected"); + LOAD_FP(getAccessibleTableRowSelections, getAccessibleTableRowSelectionsFP, + "getAccessibleTableRowSelections"); + + LOAD_FP(getAccessibleTableColumnSelectionCount, getAccessibleTableColumnSelectionCountFP, + "getAccessibleTableColumnSelectionCount"); + LOAD_FP(isAccessibleTableColumnSelected, isAccessibleTableColumnSelectedFP, + "isAccessibleTableColumnSelected"); + LOAD_FP(getAccessibleTableColumnSelections, getAccessibleTableColumnSelectionsFP, + "getAccessibleTableColumnSelections"); + + LOAD_FP(getAccessibleTableRow, getAccessibleTableRowFP, + "getAccessibleTableRow"); + LOAD_FP(getAccessibleTableColumn, getAccessibleTableColumnFP, + "getAccessibleTableColumn"); + LOAD_FP(getAccessibleTableIndex, getAccessibleTableIndexFP, + "getAccessibleTableIndex"); + + /* end AccessibleTable */ + + /* AccessibleRelationSet */ + LOAD_FP(getAccessibleRelationSet, getAccessibleRelationSetFP, "getAccessibleRelationSet"); + + /* AccessibleHypertext */ + LOAD_FP(getAccessibleHypertext, getAccessibleHypertextFP, "getAccessibleHypertext"); + LOAD_FP(activateAccessibleHyperlink, activateAccessibleHyperlinkFP, "activateAccessibleHyperlink"); + LOAD_FP(getAccessibleHyperlinkCount, getAccessibleHyperlinkCountFP, "getAccessibleHyperlinkCount"); + LOAD_FP(getAccessibleHypertextExt, getAccessibleHypertextExtFP, "getAccessibleHypertextExt"); + LOAD_FP(getAccessibleHypertextLinkIndex, getAccessibleHypertextLinkIndexFP, "getAccessibleHypertextLinkIndex"); + LOAD_FP(getAccessibleHyperlink, getAccessibleHyperlinkFP, "getAccessibleHyperlink"); + + /* Accessible KeyBinding, Icon and Action */ + LOAD_FP(getAccessibleKeyBindings, getAccessibleKeyBindingsFP, "getAccessibleKeyBindings"); + LOAD_FP(getAccessibleIcons, getAccessibleIconsFP, "getAccessibleIcons"); + LOAD_FP(getAccessibleActions, getAccessibleActionsFP, "getAccessibleActions"); + LOAD_FP(doAccessibleActions, doAccessibleActionsFP, "doAccessibleActions"); + + /* AccessibleText */ + LOAD_FP(GetAccessibleTextInfo, GetAccessibleTextInfoFP, "getAccessibleTextInfo"); + LOAD_FP(GetAccessibleTextItems, GetAccessibleTextItemsFP, "getAccessibleTextItems"); + LOAD_FP(GetAccessibleTextSelectionInfo, GetAccessibleTextSelectionInfoFP, "getAccessibleTextSelectionInfo"); + LOAD_FP(GetAccessibleTextAttributes, GetAccessibleTextAttributesFP, "getAccessibleTextAttributes"); + LOAD_FP(GetAccessibleTextRect, GetAccessibleTextRectFP, "getAccessibleTextRect"); + LOAD_FP(GetAccessibleTextLineBounds, GetAccessibleTextLineBoundsFP, "getAccessibleTextLineBounds"); + LOAD_FP(GetAccessibleTextRange, GetAccessibleTextRangeFP, "getAccessibleTextRange"); + + LOAD_FP(GetCurrentAccessibleValueFromContext, GetCurrentAccessibleValueFromContextFP, "getCurrentAccessibleValueFromContext"); + LOAD_FP(GetMaximumAccessibleValueFromContext, GetMaximumAccessibleValueFromContextFP, "getMaximumAccessibleValueFromContext"); + LOAD_FP(GetMinimumAccessibleValueFromContext, GetMinimumAccessibleValueFromContextFP, "getMinimumAccessibleValueFromContext"); + + LOAD_FP(AddAccessibleSelectionFromContext, AddAccessibleSelectionFromContextFP, "addAccessibleSelectionFromContext"); + LOAD_FP(ClearAccessibleSelectionFromContext, ClearAccessibleSelectionFromContextFP, "clearAccessibleSelectionFromContext"); + LOAD_FP(GetAccessibleSelectionFromContext, GetAccessibleSelectionFromContextFP, "getAccessibleSelectionFromContext"); + LOAD_FP(GetAccessibleSelectionCountFromContext, GetAccessibleSelectionCountFromContextFP, "getAccessibleSelectionCountFromContext"); + LOAD_FP(IsAccessibleChildSelectedFromContext, IsAccessibleChildSelectedFromContextFP, "isAccessibleChildSelectedFromContext"); + LOAD_FP(RemoveAccessibleSelectionFromContext, RemoveAccessibleSelectionFromContextFP, "removeAccessibleSelectionFromContext"); + LOAD_FP(SelectAllAccessibleSelectionFromContext, SelectAllAccessibleSelectionFromContextFP, "selectAllAccessibleSelectionFromContext"); + + LOAD_FP(setTextContents, setTextContentsFP, "setTextContents"); + LOAD_FP(getParentWithRole, getParentWithRoleFP, "getParentWithRole"); + LOAD_FP(getTopLevelObject, getTopLevelObjectFP, "getTopLevelObject"); + LOAD_FP(getParentWithRoleElseRoot, getParentWithRoleElseRootFP, "getParentWithRoleElseRoot"); + LOAD_FP(getObjectDepth, getObjectDepthFP, "getObjectDepth"); + LOAD_FP(getActiveDescendent, getActiveDescendentFP, "getActiveDescendent"); + + // additional methods for Teton + LOAD_FP(getVirtualAccessibleName, getVirtualAccessibleNameFP, "getVirtualAccessibleName"); + LOAD_FP(requestFocus, requestFocusFP, "requestFocus"); + LOAD_FP(selectTextRange, selectTextRangeFP, "selectTextRange"); + LOAD_FP(getTextAttributesInRange, getTextAttributesInRangeFP, "getTextAttributesInRange"); + LOAD_FP(getVisibleChildrenCount, getVisibleChildrenCountFP, "getVisibleChildrenCount"); + LOAD_FP(getVisibleChildren, getVisibleChildrenFP, "getVisibleChildren"); + LOAD_FP(setCaretPosition, setCaretPositionFP, "setCaretPosition"); + LOAD_FP(getCaretLocation, getCaretLocationFP, "getCaretLocation"); + + LOAD_FP(getEventsWaiting, getEventsWaitingFP, "getEventsWaiting"); + + theAccessBridge.Windows_run(); + + theAccessBridgeInitializedFlag = TRUE; + return TRUE; + } else { + return FALSE; + } + } + + + BOOL shutdownAccessBridge() { + BOOL result; + DWORD error; + theAccessBridgeInitializedFlag = FALSE; + if (theAccessBridgeInstance != (HANDLE) 0) { + result = FreeLibrary(theAccessBridgeInstance); + if (result != TRUE) { + error = GetLastError(); + } + return TRUE; + } + return FALSE; + } + + + void SetJavaShutdown(AccessBridge_JavaShutdownFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetJavaShutdown(fp); + } + } + + void SetFocusGained(AccessBridge_FocusGainedFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetFocusGained(fp); + } + } + + void SetFocusLost(AccessBridge_FocusLostFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetFocusLost(fp); + } + } + + + void SetCaretUpdate(AccessBridge_CaretUpdateFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetCaretUpdate(fp); + } + } + + + void SetMouseClicked(AccessBridge_MouseClickedFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetMouseClicked(fp); + } + } + + void SetMouseEntered(AccessBridge_MouseEnteredFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetMouseEntered(fp); + } + } + + void SetMouseExited(AccessBridge_MouseExitedFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetMouseExited(fp); + } + } + + void SetMousePressed(AccessBridge_MousePressedFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetMousePressed(fp); + } + } + + void SetMouseReleased(AccessBridge_MouseReleasedFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetMouseReleased(fp); + } + } + + + void SetMenuCanceled(AccessBridge_MenuCanceledFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetMenuCanceled(fp); + } + } + + void SetMenuDeselected(AccessBridge_MenuDeselectedFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetMenuDeselected(fp); + } + } + + void SetMenuSelected(AccessBridge_MenuSelectedFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetMenuSelected(fp); + } + } + + void SetPopupMenuCanceled(AccessBridge_PopupMenuCanceledFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPopupMenuCanceled(fp); + } + } + + void SetPopupMenuWillBecomeInvisible(AccessBridge_PopupMenuWillBecomeInvisibleFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPopupMenuWillBecomeInvisible(fp); + } + } + + void SetPopupMenuWillBecomeVisible(AccessBridge_PopupMenuWillBecomeVisibleFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPopupMenuWillBecomeVisible(fp); + } + } + + + void SetPropertyNameChange(AccessBridge_PropertyNameChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyNameChange(fp); + } + } + + void SetPropertyDescriptionChange(AccessBridge_PropertyDescriptionChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyDescriptionChange(fp); + } + } + + void SetPropertyStateChange(AccessBridge_PropertyStateChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyStateChange(fp); + } + } + + void SetPropertyValueChange(AccessBridge_PropertyValueChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyValueChange(fp); + } + } + + void SetPropertySelectionChange(AccessBridge_PropertySelectionChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertySelectionChange(fp); + } + } + + void SetPropertyTextChange(AccessBridge_PropertyTextChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyTextChange(fp); + } + } + + void SetPropertyCaretChange(AccessBridge_PropertyCaretChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyCaretChange(fp); + } + } + + void SetPropertyVisibleDataChange(AccessBridge_PropertyVisibleDataChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyVisibleDataChange(fp); + } + } + + void SetPropertyChildChange(AccessBridge_PropertyChildChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyChildChange(fp); + } + } + + void SetPropertyActiveDescendentChange(AccessBridge_PropertyActiveDescendentChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyActiveDescendentChange(fp); + } + } + + void SetPropertyTableModelChange(AccessBridge_PropertyTableModelChangeFP fp) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SetPropertyTableModelChange(fp); + } + } + + /** + * General routines + */ + void ReleaseJavaObject(long vmID, Java_Object object) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.ReleaseJavaObject(vmID, object); + } + } + + BOOL GetVersionInfo(long vmID, AccessBridgeVersionInfo *info) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetVersionInfo(vmID, info); + } + return FALSE; + } + + + /** + * Window routines + */ + BOOL IsJavaWindow(HWND window) { + if (theAccessBridgeInitializedFlag == TRUE) { + BOOL ret ; + ret = theAccessBridge.IsJavaWindow(window); + return ret ; + + } + return FALSE; + } + + + /** + * Returns the virtual machine ID and AccessibleContext for a top-level window + */ + BOOL GetAccessibleContextFromHWND(HWND target, long *vmID, AccessibleContext *ac) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleContextFromHWND(target, vmID, ac); + } + return FALSE; + } + + /** + * Returns the HWND from the AccessibleContext of a top-level window. Returns 0 + * on error or if the AccessibleContext does not refer to a top-level window. + */ + HWND getHWNDFromAccessibleContext(long vmID, JOBJECT64 accesibleContext) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getHWNDFromAccessibleContext(vmID, accesibleContext); + } + return (HWND)0; + } + + /** + * returns whether two objects are the same + */ + BOOL IsSameObject(long vmID, JOBJECT64 obj1, JOBJECT64 obj2) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.IsSameObject(vmID, obj1, obj2); + } + return FALSE; + } + + /** + * Sets editable text contents. The AccessibleContext must implement AccessibleEditableText and + * be editable. The maximum text length is MAX_STRING_SIZE - 1. + * Returns whether successful + */ + BOOL setTextContents (const long vmID, const AccessibleContext accessibleContext, const wchar_t *text) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.setTextContents(vmID, accessibleContext, text); + } + return FALSE; + } + + /** + * Returns the Accessible Context with the specified role that is the + * ancestor of a given object. The role is one of the role strings + * defined in AccessBridgePackages.h + * If there is no ancestor object that has the specified role, + * returns (AccessibleContext)0. + */ + AccessibleContext getParentWithRole (const long vmID, const AccessibleContext accessibleContext, + const wchar_t *role) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getParentWithRole(vmID, accessibleContext, role); + } + return (AccessibleContext)0; + } + + /** + * Returns the Accessible Context with the specified role that is the + * ancestor of a given object. The role is one of the role strings + * defined in AccessBridgePackages.h. If an object with the specified + * role does not exist, returns the top level object for the Java Window. + * Returns (AccessibleContext)0 on error. + */ + AccessibleContext getParentWithRoleElseRoot (const long vmID, const AccessibleContext accessibleContext, + const wchar_t *role) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getParentWithRoleElseRoot(vmID, accessibleContext, role); + } + return (AccessibleContext)0; + } + + /** + * Returns the Accessible Context for the top level object in + * a Java Window. This is same Accessible Context that is obtained + * from GetAccessibleContextFromHWND for that window. Returns + * (AccessibleContext)0 on error. + */ + AccessibleContext getTopLevelObject (const long vmID, const AccessibleContext accessibleContext) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getTopLevelObject(vmID, accessibleContext); + } + return (AccessibleContext)0; + } + + /** + * Returns how deep in the object hierarchy a given object is. + * The top most object in the object hierarchy has an object depth of 0. + * Returns -1 on error. + */ + int getObjectDepth (const long vmID, const AccessibleContext accessibleContext) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getObjectDepth(vmID, accessibleContext); + } + return -1; + } + + /** + * Returns the Accessible Context of the current ActiveDescendent of an object. + * This method assumes the ActiveDescendent is the component that is currently + * selected in a container object. + * Returns (AccessibleContext)0 on error or if there is no selection. + */ + AccessibleContext getActiveDescendent (const long vmID, const AccessibleContext accessibleContext) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getActiveDescendent(vmID, accessibleContext); + } + return (AccessibleContext)0; + } + + + /** + * Accessible Context routines + */ + BOOL GetAccessibleContextAt(long vmID, AccessibleContext acParent, + jint x, jint y, AccessibleContext *ac) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleContextAt(vmID, acParent, x, y, ac); + } + return FALSE; + } + + BOOL GetAccessibleContextWithFocus(HWND window, long *vmID, AccessibleContext *ac) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleContextWithFocus(window, vmID, ac); + } + return FALSE; + } + + BOOL GetAccessibleContextInfo(long vmID, AccessibleContext ac, AccessibleContextInfo *info) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleContextInfo(vmID, ac, info); + } + return FALSE; + } + + AccessibleContext GetAccessibleChildFromContext(long vmID, AccessibleContext ac, jint index) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleChildFromContext(vmID, ac, index); + } + return (AccessibleContext) 0; + } + + AccessibleContext GetAccessibleParentFromContext(long vmID, AccessibleContext ac) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleParentFromContext(vmID, ac); + } + return (AccessibleContext) 0; + } + + /* begin AccessibleTable routines */ + + /* + * get information about an AccessibleTable + */ + BOOL getAccessibleTableInfo(long vmID, AccessibleContext acParent, AccessibleTableInfo *tableInfo) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableInfo(vmID, acParent, tableInfo); + } + return FALSE; + } + + /* + * get information about an AccessibleTable cell + */ + BOOL getAccessibleTableCellInfo(long vmID, AccessibleTable accessibleTable, + jint row, jint column, AccessibleTableCellInfo *tableCellInfo) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableCellInfo(vmID, accessibleTable, row, column, tableCellInfo); + } + return FALSE; + } + + /* + * get information about an AccessibleTable row header + */ + BOOL getAccessibleTableRowHeader(long vmID, AccessibleContext acParent, AccessibleTableInfo *tableInfo) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableRowHeader(vmID, acParent, tableInfo); + } + return FALSE; + } + + /* + * get information about an AccessibleTable column header + */ + BOOL getAccessibleTableColumnHeader(long vmID, AccessibleContext acParent, AccessibleTableInfo *tableInfo) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableColumnHeader(vmID, acParent, tableInfo); + } + return FALSE; + } + + /* + * return a description of an AccessibleTable row header + */ + AccessibleContext getAccessibleTableRowDescription(long vmID, AccessibleContext acParent, jint row) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableRowDescription(vmID, acParent, row); + } + return (AccessibleContext)0; + } + + /* + * return a description of an AccessibleTable column header + */ + AccessibleContext getAccessibleTableColumnDescription(long vmID, AccessibleContext acParent, jint column) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableColumnDescription(vmID, acParent, column); + } + return (AccessibleContext)0; + } + + /* + * return the number of rows selected in an AccessibleTable + */ + jint getAccessibleTableRowSelectionCount(long vmID, AccessibleTable table) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableRowSelectionCount(vmID, table); + } + return -1; + } + + /* + * return whether a row is selected in an AccessibleTable + */ + BOOL isAccessibleTableRowSelected(long vmID, AccessibleTable table, jint row) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.isAccessibleTableRowSelected(vmID, table, row); + } + return FALSE; + } + + /* + * get an array of selected rows in an AccessibleTable + */ + BOOL getAccessibleTableRowSelections(long vmID, AccessibleTable table, jint count, jint *selections) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableRowSelections(vmID, table, count, selections); + } + return FALSE; + } + + /* + * return the number of columns selected in an AccessibleTable + */ + jint getAccessibleTableColumnSelectionCount(long vmID, AccessibleTable table) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableColumnSelectionCount(vmID, table); + } + return -1; + } + + /* + * return whether a column is selected in an AccessibleTable + */ + BOOL isAccessibleTableColumnSelected(long vmID, AccessibleTable table, jint column) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.isAccessibleTableColumnSelected(vmID, table, column); + } + return FALSE; + } + + /* + * get an array of columns selected in an AccessibleTable + */ + BOOL getAccessibleTableColumnSelections(long vmID, AccessibleTable table, jint count, jint *selections) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableColumnSelections(vmID, table, count, selections); + } + return FALSE; + } + + /* + * return the row number for a cell at a given index + */ + jint + getAccessibleTableRow(long vmID, AccessibleTable table, jint index) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableRow(vmID, table, index); + } + return -1; + } + + /* + * return the column number for a cell at a given index + */ + jint + getAccessibleTableColumn(long vmID, AccessibleTable table, jint index) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableColumn(vmID, table, index); + } + return -1; + } + + /* + * return the index of a cell at a given row and column + */ + jint + getAccessibleTableIndex(long vmID, AccessibleTable table, jint row, jint column) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleTableIndex(vmID, table, row, column); + } + return -1; + } + + /* end AccessibleTable routines */ + + + /** + * Accessible Text routines + */ + BOOL GetAccessibleTextInfo(long vmID, AccessibleText at, AccessibleTextInfo *textInfo, jint x, jint y) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleTextInfo(vmID, at, textInfo, x, y); + } + return FALSE; + } + + BOOL GetAccessibleTextItems(long vmID, AccessibleText at, AccessibleTextItemsInfo *textItems, jint index) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleTextItems(vmID, at, textItems, index); + } + return FALSE; + } + + BOOL GetAccessibleTextSelectionInfo(long vmID, AccessibleText at, AccessibleTextSelectionInfo *textSelection) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleTextSelectionInfo(vmID, at, textSelection); + } + return FALSE; + } + + BOOL GetAccessibleTextAttributes(long vmID, AccessibleText at, jint index, AccessibleTextAttributesInfo *attributes) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleTextAttributes(vmID, at, index, attributes); + } + return FALSE; + } + + BOOL GetAccessibleTextRect(long vmID, AccessibleText at, AccessibleTextRectInfo *rectInfo, jint index) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleTextRect(vmID, at, rectInfo, index); + } + return FALSE; + } + + BOOL GetAccessibleTextLineBounds(long vmID, AccessibleText at, jint index, jint *startIndex, jint *endIndex) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleTextLineBounds(vmID, at, index, startIndex, endIndex); + } + return FALSE; + } + + BOOL GetAccessibleTextRange(long vmID, AccessibleText at, jint start, jint end, wchar_t *text, short len) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleTextRange(vmID, at, start, end, text, len); + } + return FALSE; + } + + /** + * AccessibleRelationSet routines + */ + BOOL getAccessibleRelationSet(long vmID, AccessibleContext accessibleContext, + AccessibleRelationSetInfo *relationSetInfo) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleRelationSet(vmID, accessibleContext, relationSetInfo); + } + return FALSE; + } + + /** + * AccessibleHypertext routines + */ + + // Gets AccessibleHypertext for an AccessibleContext + BOOL getAccessibleHypertext(long vmID, AccessibleContext accessibleContext, + AccessibleHypertextInfo *hypertextInfo) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleHypertext(vmID, accessibleContext, hypertextInfo); + } + return FALSE; + } + + // Activates an AccessibleHyperlink for an AccessibleContext + BOOL activateAccessibleHyperlink(long vmID, AccessibleContext accessibleContext, + AccessibleHyperlink accessibleHyperlink) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.activateAccessibleHyperlink(vmID, accessibleContext, accessibleHyperlink); + } + return FALSE; + } + + /* + * Returns the number of hyperlinks in a component + * Maps to AccessibleHypertext.getLinkCount. + * Returns -1 on error. + */ + jint getAccessibleHyperlinkCount(const long vmID, + const AccessibleContext accessibleContext) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleHyperlinkCount(vmID, accessibleContext); + } + return -1; + } + + /* + * This method is used to iterate through the hyperlinks in a component. It + * returns hypertext information for a component starting at hyperlink index + * nStartIndex. No more than MAX_HYPERLINKS AccessibleHypertextInfo objects will + * be returned for each call to this method. + * returns FALSE on error. + */ + BOOL getAccessibleHypertextExt(const long vmID, + const AccessibleContext accessibleContext, + const jint nStartIndex, + /* OUT */ AccessibleHypertextInfo *hypertextInfo) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleHypertextExt(vmID, + accessibleContext, + nStartIndex, + hypertextInfo); + } + return FALSE; + } + + /* + * Returns the index into an array of hyperlinks that is associated with + * a character index in document; + * Maps to AccessibleHypertext.getLinkIndex. + * Returns -1 on error. + */ + jint getAccessibleHypertextLinkIndex(const long vmID, + const AccessibleHypertext hypertext, + const jint nIndex) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleHypertextLinkIndex(vmID, + hypertext, + nIndex); + } + return -1; + } + + /* + * Returns the nth hyperlink in a document. + * Maps to AccessibleHypertext.getLink. + * Returns -1 on error + */ + BOOL getAccessibleHyperlink(const long vmID, + const AccessibleHypertext hypertext, + const jint nIndex, + /* OUT */ AccessibleHyperlinkInfo *hyperlinkInfo) { + + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleHyperlink(vmID, + hypertext, + nIndex, + hyperlinkInfo); + } + return FALSE; + } + + + /* Accessible KeyBindings, Icons and Actions */ + BOOL getAccessibleKeyBindings(long vmID, AccessibleContext accessibleContext, + AccessibleKeyBindings *keyBindings) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleKeyBindings(vmID, accessibleContext, keyBindings); + } + return FALSE; + } + + BOOL getAccessibleIcons(long vmID, AccessibleContext accessibleContext, + AccessibleIcons *icons) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleIcons(vmID, accessibleContext, icons); + } + return FALSE; + } + + BOOL getAccessibleActions(long vmID, AccessibleContext accessibleContext, + AccessibleActions *actions) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getAccessibleActions(vmID, accessibleContext, actions); + } + return FALSE; + } + + BOOL doAccessibleActions(long vmID, AccessibleContext accessibleContext, + AccessibleActionsToDo *actionsToDo, jint *failure) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.doAccessibleActions(vmID, accessibleContext, actionsToDo, failure); + } + return FALSE; + } + + /** + * Accessible Value routines + */ + BOOL GetCurrentAccessibleValueFromContext(long vmID, AccessibleValue av, wchar_t *value, short len) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetCurrentAccessibleValueFromContext(vmID, av, value, len); + } + return FALSE; + } + + BOOL GetMaximumAccessibleValueFromContext(long vmID, AccessibleValue av, wchar_t *value, short len) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetMaximumAccessibleValueFromContext(vmID, av, value, len); + } + return FALSE; + } + + BOOL GetMinimumAccessibleValueFromContext(long vmID, AccessibleValue av, wchar_t *value, short len) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetMinimumAccessibleValueFromContext(vmID, av, value, len); + } + return FALSE; + } + + + /** + * Accessible Selection routines + */ + void addAccessibleSelectionFromContext(long vmID, AccessibleSelection as, int i) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.AddAccessibleSelectionFromContext(vmID, as, i); + } + } + + void clearAccessibleSelectionFromContext(long vmID, AccessibleSelection as) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.ClearAccessibleSelectionFromContext(vmID, as); + } + } + + JOBJECT64 GetAccessibleSelectionFromContext(long vmID, AccessibleSelection as, int i) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleSelectionFromContext(vmID, as, i); + } + return (JOBJECT64) 0; + } + + int GetAccessibleSelectionCountFromContext(long vmID, AccessibleSelection as) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.GetAccessibleSelectionCountFromContext(vmID, as); + } + return -1; + } + + BOOL IsAccessibleChildSelectedFromContext(long vmID, AccessibleSelection as, int i) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.IsAccessibleChildSelectedFromContext(vmID, as, i); + } + return FALSE; + } + + void RemoveAccessibleSelectionFromContext(long vmID, AccessibleSelection as, int i) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.RemoveAccessibleSelectionFromContext(vmID, as, i); + } + } + + void SelectAllAccessibleSelectionFromContext(long vmID, AccessibleSelection as) { + if (theAccessBridgeInitializedFlag == TRUE) { + theAccessBridge.SelectAllAccessibleSelectionFromContext(vmID, as); + } + } + + /** + * Additional methods for Teton + */ + + /** + * Gets the AccessibleName for a component based upon the JAWS algorithm. Returns + * whether successful. + * + * Bug ID 4916682 - Implement JAWS AccessibleName policy + */ + BOOL getVirtualAccessibleName(const long vmID, const AccessibleContext accessibleContext, + wchar_t *name, int len) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getVirtualAccessibleName(vmID, accessibleContext, name, len); + } + return FALSE; + } + + /** + * Request focus for a component. Returns whether successful; + * + * Bug ID 4944757 - requestFocus method needed + */ + BOOL requestFocus(const long vmID, const AccessibleContext accessibleContext) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.requestFocus(vmID, accessibleContext); + } + return FALSE; + } + + /** + * Selects text between two indices. Selection includes the text at the start index + * and the text at the end index. Returns whether successful; + * + * Bug ID 4944758 - selectTextRange method needed + */ + BOOL selectTextRange(const long vmID, const AccessibleContext accessibleContext, + const int startIndex, const int endIndex) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.selectTextRange(vmID, accessibleContext, startIndex, endIndex); + } + return FALSE; + } + + /** + * Get text attributes between two indices. The attribute list includes the text at the + * start index and the text at the end index. Returns whether successful; + * + * Bug ID 4944761 - getTextAttributes between two indices method needed + */ + BOOL getTextAttributesInRange(const long vmID, const AccessibleContext accessibleContext, + const int startIndex, const int endIndex, + AccessibleTextAttributesInfo *attributes, short *len) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getTextAttributesInRange(vmID, accessibleContext, startIndex, + endIndex, attributes, len); + } + return FALSE; + } + + /** + * Returns the number of visible children of a component. Returns -1 on error. + * + * Bug ID 4944762- getVisibleChildren for list-like components needed + */ + int getVisibleChildrenCount(const long vmID, const AccessibleContext accessibleContext) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getVisibleChildrenCount(vmID, accessibleContext); + } + return FALSE; + } + + /** + * Gets the visible children of an AccessibleContext. Returns whether successful; + * + * Bug ID 4944762- getVisibleChildren for list-like components needed + */ + BOOL getVisibleChildren(const long vmID, const AccessibleContext accessibleContext, + const int startIndex, VisibleChildrenInfo *visibleChildrenInfo) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getVisibleChildren(vmID, accessibleContext, startIndex, + visibleChildrenInfo); + } + return FALSE; + } + + /** + * Set the caret to a text position. Returns whether successful; + * + * Bug ID 4944770 - setCaretPosition method needed + */ + BOOL setCaretPosition(const long vmID, const AccessibleContext accessibleContext, + const int position) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.setCaretPosition(vmID, accessibleContext, position); + } + return FALSE; + } + + /** + * Gets the text caret location + */ + BOOL getCaretLocation(long vmID, AccessibleContext ac, AccessibleTextRectInfo *rectInfo, jint index) { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getCaretLocation(vmID, ac, rectInfo, index); + } + return FALSE; + } + + /** + * Gets the number of events waiting to fire + */ + int getEventsWaiting() { + if (theAccessBridgeInitializedFlag == TRUE) { + return theAccessBridge.getEventsWaiting(); + } + return FALSE; + } + +#ifdef __cplusplus +} +#endif diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCallbacks.h --- a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCallbacks.h Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCallbacks.h Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -24,10 +24,6 @@ */ /* - * AccessBridgeCallbacks.h 1.17 05/03/21 - */ - -/* * Header file defining callback typedefs for Windows routines * which are called from Java (responding to events, etc.). */ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.c --- a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.c Wed Jul 05 22:29:12 2017 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,1131 +0,0 @@ -/* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute 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. - */ - -/* - * @(#)AccessBridgeCalls.c 1.25 05/08/22 - */ - -/* - * Wrapper functions around calls to the AccessBridge DLL - */ - - -#include -#include - - -//#define ACCESSBRIDGE_32 -//#define ACCESSBRIDGE_64 - -#include "AccessBridgeCalls.h" -#include "AccessBridgeDebug.h" - -#ifdef __cplusplus -extern "C" { -#endif - - HINSTANCE theAccessBridgeInstance; - AccessBridgeFPs theAccessBridge; - - BOOL theAccessBridgeInitializedFlag = FALSE; - -#define LOAD_FP(result, type, name) \ - PrintDebugString("LOAD_FP loading: %s ...", name); \ - if ((theAccessBridge.result = \ - (type) GetProcAddress(theAccessBridgeInstance, name)) == (type) 0) { \ - PrintDebugString("LOAD_FP failed: %s", name); \ - return FALSE; \ - } - - BOOL initializeAccessBridge() { - -#ifdef ACCESSBRIDGE_ARCH_32 // For 32bit AT new bridge - theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE-32"); -#else -#ifdef ACCESSBRIDGE_ARCH_64 // For 64bit AT new bridge - theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE-64"); -#else // legacy - theAccessBridgeInstance = LoadLibrary("WINDOWSACCESSBRIDGE"); -#endif -#endif - if (theAccessBridgeInstance != 0) { - LOAD_FP(Windows_run, Windows_runFP, "Windows_run"); - - LOAD_FP(SetJavaShutdown, SetJavaShutdownFP, "setJavaShutdownFP"); - LOAD_FP(SetFocusGained, SetFocusGainedFP, "setFocusGainedFP"); - LOAD_FP(SetFocusLost, SetFocusLostFP, "setFocusLostFP"); - - LOAD_FP(SetCaretUpdate, SetCaretUpdateFP, "setCaretUpdateFP"); - - LOAD_FP(SetMouseClicked, SetMouseClickedFP, "setMouseClickedFP"); - LOAD_FP(SetMouseEntered, SetMouseEnteredFP, "setMouseEnteredFP"); - LOAD_FP(SetMouseExited, SetMouseExitedFP, "setMouseExitedFP"); - LOAD_FP(SetMousePressed, SetMousePressedFP, "setMousePressedFP"); - LOAD_FP(SetMouseReleased, SetMouseReleasedFP, "setMouseReleasedFP"); - - LOAD_FP(SetMenuCanceled, SetMenuCanceledFP, "setMenuCanceledFP"); - LOAD_FP(SetMenuDeselected, SetMenuDeselectedFP, "setMenuDeselectedFP"); - LOAD_FP(SetMenuSelected, SetMenuSelectedFP, "setMenuSelectedFP"); - LOAD_FP(SetPopupMenuCanceled, SetPopupMenuCanceledFP, "setPopupMenuCanceledFP"); - LOAD_FP(SetPopupMenuWillBecomeInvisible, SetPopupMenuWillBecomeInvisibleFP, "setPopupMenuWillBecomeInvisibleFP"); - LOAD_FP(SetPopupMenuWillBecomeVisible, SetPopupMenuWillBecomeVisibleFP, "setPopupMenuWillBecomeVisibleFP"); - - LOAD_FP(SetPropertyNameChange, SetPropertyNameChangeFP, "setPropertyNameChangeFP"); - LOAD_FP(SetPropertyDescriptionChange, SetPropertyDescriptionChangeFP, "setPropertyDescriptionChangeFP"); - LOAD_FP(SetPropertyStateChange, SetPropertyStateChangeFP, "setPropertyStateChangeFP"); - LOAD_FP(SetPropertyValueChange, SetPropertyValueChangeFP, "setPropertyValueChangeFP"); - LOAD_FP(SetPropertySelectionChange, SetPropertySelectionChangeFP, "setPropertySelectionChangeFP"); - LOAD_FP(SetPropertyTextChange, SetPropertyTextChangeFP, "setPropertyTextChangeFP"); - LOAD_FP(SetPropertyCaretChange, SetPropertyCaretChangeFP, "setPropertyCaretChangeFP"); - LOAD_FP(SetPropertyVisibleDataChange, SetPropertyVisibleDataChangeFP, "setPropertyVisibleDataChangeFP"); - LOAD_FP(SetPropertyChildChange, SetPropertyChildChangeFP, "setPropertyChildChangeFP"); - LOAD_FP(SetPropertyActiveDescendentChange, SetPropertyActiveDescendentChangeFP, "setPropertyActiveDescendentChangeFP"); - - LOAD_FP(SetPropertyTableModelChange, SetPropertyTableModelChangeFP, "setPropertyTableModelChangeFP"); - - LOAD_FP(ReleaseJavaObject, ReleaseJavaObjectFP, "releaseJavaObject"); - LOAD_FP(GetVersionInfo, GetVersionInfoFP, "getVersionInfo"); - - LOAD_FP(IsJavaWindow, IsJavaWindowFP, "isJavaWindow"); - LOAD_FP(IsSameObject, IsSameObjectFP, "isSameObject"); - LOAD_FP(GetAccessibleContextFromHWND, GetAccessibleContextFromHWNDFP, "getAccessibleContextFromHWND"); - LOAD_FP(getHWNDFromAccessibleContext, getHWNDFromAccessibleContextFP, "getHWNDFromAccessibleContext"); - - LOAD_FP(GetAccessibleContextAt, GetAccessibleContextAtFP, "getAccessibleContextAt"); - LOAD_FP(GetAccessibleContextWithFocus, GetAccessibleContextWithFocusFP, "getAccessibleContextWithFocus"); - LOAD_FP(GetAccessibleContextInfo, GetAccessibleContextInfoFP, "getAccessibleContextInfo"); - LOAD_FP(GetAccessibleChildFromContext, GetAccessibleChildFromContextFP, "getAccessibleChildFromContext"); - LOAD_FP(GetAccessibleParentFromContext, GetAccessibleParentFromContextFP, "getAccessibleParentFromContext"); - - /* begin AccessibleTable */ - LOAD_FP(getAccessibleTableInfo, getAccessibleTableInfoFP, "getAccessibleTableInfo"); - LOAD_FP(getAccessibleTableCellInfo, getAccessibleTableCellInfoFP, "getAccessibleTableCellInfo"); - - LOAD_FP(getAccessibleTableRowHeader, getAccessibleTableRowHeaderFP, "getAccessibleTableRowHeader"); - LOAD_FP(getAccessibleTableColumnHeader, getAccessibleTableColumnHeaderFP, "getAccessibleTableColumnHeader"); - - LOAD_FP(getAccessibleTableRowDescription, getAccessibleTableRowDescriptionFP, "getAccessibleTableRowDescription"); - LOAD_FP(getAccessibleTableColumnDescription, getAccessibleTableColumnDescriptionFP, "getAccessibleTableColumnDescription"); - - LOAD_FP(getAccessibleTableRowSelectionCount, getAccessibleTableRowSelectionCountFP, - "getAccessibleTableRowSelectionCount"); - LOAD_FP(isAccessibleTableRowSelected, isAccessibleTableRowSelectedFP, - "isAccessibleTableRowSelected"); - LOAD_FP(getAccessibleTableRowSelections, getAccessibleTableRowSelectionsFP, - "getAccessibleTableRowSelections"); - - LOAD_FP(getAccessibleTableColumnSelectionCount, getAccessibleTableColumnSelectionCountFP, - "getAccessibleTableColumnSelectionCount"); - LOAD_FP(isAccessibleTableColumnSelected, isAccessibleTableColumnSelectedFP, - "isAccessibleTableColumnSelected"); - LOAD_FP(getAccessibleTableColumnSelections, getAccessibleTableColumnSelectionsFP, - "getAccessibleTableColumnSelections"); - - LOAD_FP(getAccessibleTableRow, getAccessibleTableRowFP, - "getAccessibleTableRow"); - LOAD_FP(getAccessibleTableColumn, getAccessibleTableColumnFP, - "getAccessibleTableColumn"); - LOAD_FP(getAccessibleTableIndex, getAccessibleTableIndexFP, - "getAccessibleTableIndex"); - - /* end AccessibleTable */ - - /* AccessibleRelationSet */ - LOAD_FP(getAccessibleRelationSet, getAccessibleRelationSetFP, "getAccessibleRelationSet"); - - /* AccessibleHypertext */ - LOAD_FP(getAccessibleHypertext, getAccessibleHypertextFP, "getAccessibleHypertext"); - LOAD_FP(activateAccessibleHyperlink, activateAccessibleHyperlinkFP, "activateAccessibleHyperlink"); - LOAD_FP(getAccessibleHyperlinkCount, getAccessibleHyperlinkCountFP, "getAccessibleHyperlinkCount"); - LOAD_FP(getAccessibleHypertextExt, getAccessibleHypertextExtFP, "getAccessibleHypertextExt"); - LOAD_FP(getAccessibleHypertextLinkIndex, getAccessibleHypertextLinkIndexFP, "getAccessibleHypertextLinkIndex"); - LOAD_FP(getAccessibleHyperlink, getAccessibleHyperlinkFP, "getAccessibleHyperlink"); - - /* Accessible KeyBinding, Icon and Action */ - LOAD_FP(getAccessibleKeyBindings, getAccessibleKeyBindingsFP, "getAccessibleKeyBindings"); - LOAD_FP(getAccessibleIcons, getAccessibleIconsFP, "getAccessibleIcons"); - LOAD_FP(getAccessibleActions, getAccessibleActionsFP, "getAccessibleActions"); - LOAD_FP(doAccessibleActions, doAccessibleActionsFP, "doAccessibleActions"); - - /* AccessibleText */ - LOAD_FP(GetAccessibleTextInfo, GetAccessibleTextInfoFP, "getAccessibleTextInfo"); - LOAD_FP(GetAccessibleTextItems, GetAccessibleTextItemsFP, "getAccessibleTextItems"); - LOAD_FP(GetAccessibleTextSelectionInfo, GetAccessibleTextSelectionInfoFP, "getAccessibleTextSelectionInfo"); - LOAD_FP(GetAccessibleTextAttributes, GetAccessibleTextAttributesFP, "getAccessibleTextAttributes"); - LOAD_FP(GetAccessibleTextRect, GetAccessibleTextRectFP, "getAccessibleTextRect"); - LOAD_FP(GetAccessibleTextLineBounds, GetAccessibleTextLineBoundsFP, "getAccessibleTextLineBounds"); - LOAD_FP(GetAccessibleTextRange, GetAccessibleTextRangeFP, "getAccessibleTextRange"); - - LOAD_FP(GetCurrentAccessibleValueFromContext, GetCurrentAccessibleValueFromContextFP, "getCurrentAccessibleValueFromContext"); - LOAD_FP(GetMaximumAccessibleValueFromContext, GetMaximumAccessibleValueFromContextFP, "getMaximumAccessibleValueFromContext"); - LOAD_FP(GetMinimumAccessibleValueFromContext, GetMinimumAccessibleValueFromContextFP, "getMinimumAccessibleValueFromContext"); - - LOAD_FP(AddAccessibleSelectionFromContext, AddAccessibleSelectionFromContextFP, "addAccessibleSelectionFromContext"); - LOAD_FP(ClearAccessibleSelectionFromContext, ClearAccessibleSelectionFromContextFP, "clearAccessibleSelectionFromContext"); - LOAD_FP(GetAccessibleSelectionFromContext, GetAccessibleSelectionFromContextFP, "getAccessibleSelectionFromContext"); - LOAD_FP(GetAccessibleSelectionCountFromContext, GetAccessibleSelectionCountFromContextFP, "getAccessibleSelectionCountFromContext"); - LOAD_FP(IsAccessibleChildSelectedFromContext, IsAccessibleChildSelectedFromContextFP, "isAccessibleChildSelectedFromContext"); - LOAD_FP(RemoveAccessibleSelectionFromContext, RemoveAccessibleSelectionFromContextFP, "removeAccessibleSelectionFromContext"); - LOAD_FP(SelectAllAccessibleSelectionFromContext, SelectAllAccessibleSelectionFromContextFP, "selectAllAccessibleSelectionFromContext"); - - LOAD_FP(setTextContents, setTextContentsFP, "setTextContents"); - LOAD_FP(getParentWithRole, getParentWithRoleFP, "getParentWithRole"); - LOAD_FP(getTopLevelObject, getTopLevelObjectFP, "getTopLevelObject"); - LOAD_FP(getParentWithRoleElseRoot, getParentWithRoleElseRootFP, "getParentWithRoleElseRoot"); - LOAD_FP(getObjectDepth, getObjectDepthFP, "getObjectDepth"); - LOAD_FP(getActiveDescendent, getActiveDescendentFP, "getActiveDescendent"); - - // additional methods for Teton - LOAD_FP(getVirtualAccessibleName, getVirtualAccessibleNameFP, "getVirtualAccessibleName"); - LOAD_FP(requestFocus, requestFocusFP, "requestFocus"); - LOAD_FP(selectTextRange, selectTextRangeFP, "selectTextRange"); - LOAD_FP(getTextAttributesInRange, getTextAttributesInRangeFP, "getTextAttributesInRange"); - LOAD_FP(getVisibleChildrenCount, getVisibleChildrenCountFP, "getVisibleChildrenCount"); - LOAD_FP(getVisibleChildren, getVisibleChildrenFP, "getVisibleChildren"); - LOAD_FP(setCaretPosition, setCaretPositionFP, "setCaretPosition"); - LOAD_FP(getCaretLocation, getCaretLocationFP, "getCaretLocation"); - - LOAD_FP(getEventsWaiting, getEventsWaitingFP, "getEventsWaiting"); - - theAccessBridge.Windows_run(); - - theAccessBridgeInitializedFlag = TRUE; - PrintDebugString("theAccessBridgeInitializedFlag = TRUE"); - return TRUE; - } else { - return FALSE; - } - } - - - BOOL shutdownAccessBridge() { - BOOL result; - DWORD error; - theAccessBridgeInitializedFlag = FALSE; - if (theAccessBridgeInstance != (HANDLE) 0) { - result = FreeLibrary(theAccessBridgeInstance); - if (result != TRUE) { - error = GetLastError(); - } - return TRUE; - } - return FALSE; - } - - - void SetJavaShutdown(AccessBridge_JavaShutdownFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetJavaShutdown(fp); - } - } - - void SetFocusGained(AccessBridge_FocusGainedFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetFocusGained(fp); - } - } - - void SetFocusLost(AccessBridge_FocusLostFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetFocusLost(fp); - } - } - - - void SetCaretUpdate(AccessBridge_CaretUpdateFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetCaretUpdate(fp); - } - } - - - void SetMouseClicked(AccessBridge_MouseClickedFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetMouseClicked(fp); - } - } - - void SetMouseEntered(AccessBridge_MouseEnteredFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetMouseEntered(fp); - } - } - - void SetMouseExited(AccessBridge_MouseExitedFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetMouseExited(fp); - } - } - - void SetMousePressed(AccessBridge_MousePressedFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetMousePressed(fp); - } - } - - void SetMouseReleased(AccessBridge_MouseReleasedFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetMouseReleased(fp); - } - } - - - void SetMenuCanceled(AccessBridge_MenuCanceledFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetMenuCanceled(fp); - } - } - - void SetMenuDeselected(AccessBridge_MenuDeselectedFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetMenuDeselected(fp); - } - } - - void SetMenuSelected(AccessBridge_MenuSelectedFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetMenuSelected(fp); - } - } - - void SetPopupMenuCanceled(AccessBridge_PopupMenuCanceledFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPopupMenuCanceled(fp); - } - } - - void SetPopupMenuWillBecomeInvisible(AccessBridge_PopupMenuWillBecomeInvisibleFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPopupMenuWillBecomeInvisible(fp); - } - } - - void SetPopupMenuWillBecomeVisible(AccessBridge_PopupMenuWillBecomeVisibleFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPopupMenuWillBecomeVisible(fp); - } - } - - - void SetPropertyNameChange(AccessBridge_PropertyNameChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyNameChange(fp); - } - } - - void SetPropertyDescriptionChange(AccessBridge_PropertyDescriptionChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyDescriptionChange(fp); - } - } - - void SetPropertyStateChange(AccessBridge_PropertyStateChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyStateChange(fp); - } - } - - void SetPropertyValueChange(AccessBridge_PropertyValueChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyValueChange(fp); - } - } - - void SetPropertySelectionChange(AccessBridge_PropertySelectionChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertySelectionChange(fp); - } - } - - void SetPropertyTextChange(AccessBridge_PropertyTextChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyTextChange(fp); - } - } - - void SetPropertyCaretChange(AccessBridge_PropertyCaretChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyCaretChange(fp); - } - } - - void SetPropertyVisibleDataChange(AccessBridge_PropertyVisibleDataChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyVisibleDataChange(fp); - } - } - - void SetPropertyChildChange(AccessBridge_PropertyChildChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyChildChange(fp); - } - } - - void SetPropertyActiveDescendentChange(AccessBridge_PropertyActiveDescendentChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyActiveDescendentChange(fp); - } - } - - void SetPropertyTableModelChange(AccessBridge_PropertyTableModelChangeFP fp) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SetPropertyTableModelChange(fp); - } - } - - /** - * General routines - */ - void ReleaseJavaObject(long vmID, Java_Object object) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.ReleaseJavaObject(vmID, object); - } - } - - BOOL GetVersionInfo(long vmID, AccessBridgeVersionInfo *info) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetVersionInfo(vmID, info); - } - return FALSE; - } - - - /** - * Window routines - */ - BOOL IsJavaWindow(HWND window) { - if (theAccessBridgeInitializedFlag == TRUE) { - BOOL ret ; - ret = theAccessBridge.IsJavaWindow(window); - return ret ; - - } - return FALSE; - } - - - /** - * Returns the virtual machine ID and AccessibleContext for a top-level window - */ - BOOL GetAccessibleContextFromHWND(HWND target, long *vmID, AccessibleContext *ac) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleContextFromHWND(target, vmID, ac); - } - return FALSE; - } - - /** - * Returns the HWND from the AccessibleContext of a top-level window. Returns 0 - * on error or if the AccessibleContext does not refer to a top-level window. - */ - HWND getHWNDFromAccessibleContext(long vmID, JOBJECT64 accesibleContext) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getHWNDFromAccessibleContext(vmID, accesibleContext); - } - return (HWND)0; - } - - /** - * returns whether two objects are the same - */ - BOOL IsSameObject(long vmID, JOBJECT64 obj1, JOBJECT64 obj2) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.IsSameObject(vmID, obj1, obj2); - } - return FALSE; - } - - /** - * Sets editable text contents. The AccessibleContext must implement AccessibleEditableText and - * be editable. The maximum text length is MAX_STRING_SIZE - 1. - * Returns whether successful - */ - BOOL setTextContents (const long vmID, const AccessibleContext accessibleContext, const wchar_t *text) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.setTextContents(vmID, accessibleContext, text); - } - return FALSE; - } - - /** - * Returns the Accessible Context with the specified role that is the - * ancestor of a given object. The role is one of the role strings - * defined in AccessBridgePackages.h - * If there is no ancestor object that has the specified role, - * returns (AccessibleContext)0. - */ - AccessibleContext getParentWithRole (const long vmID, const AccessibleContext accessibleContext, - const wchar_t *role) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getParentWithRole(vmID, accessibleContext, role); - } - return (AccessibleContext)0; - } - - /** - * Returns the Accessible Context with the specified role that is the - * ancestor of a given object. The role is one of the role strings - * defined in AccessBridgePackages.h. If an object with the specified - * role does not exist, returns the top level object for the Java Window. - * Returns (AccessibleContext)0 on error. - */ - AccessibleContext getParentWithRoleElseRoot (const long vmID, const AccessibleContext accessibleContext, - const wchar_t *role) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getParentWithRoleElseRoot(vmID, accessibleContext, role); - } - return (AccessibleContext)0; - } - - /** - * Returns the Accessible Context for the top level object in - * a Java Window. This is same Accessible Context that is obtained - * from GetAccessibleContextFromHWND for that window. Returns - * (AccessibleContext)0 on error. - */ - AccessibleContext getTopLevelObject (const long vmID, const AccessibleContext accessibleContext) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getTopLevelObject(vmID, accessibleContext); - } - return (AccessibleContext)0; - } - - /** - * Returns how deep in the object hierarchy a given object is. - * The top most object in the object hierarchy has an object depth of 0. - * Returns -1 on error. - */ - int getObjectDepth (const long vmID, const AccessibleContext accessibleContext) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getObjectDepth(vmID, accessibleContext); - } - return -1; - } - - /** - * Returns the Accessible Context of the current ActiveDescendent of an object. - * This method assumes the ActiveDescendent is the component that is currently - * selected in a container object. - * Returns (AccessibleContext)0 on error or if there is no selection. - */ - AccessibleContext getActiveDescendent (const long vmID, const AccessibleContext accessibleContext) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getActiveDescendent(vmID, accessibleContext); - } - return (AccessibleContext)0; - } - - - /** - * Accessible Context routines - */ - BOOL GetAccessibleContextAt(long vmID, AccessibleContext acParent, - jint x, jint y, AccessibleContext *ac) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleContextAt(vmID, acParent, x, y, ac); - } - return FALSE; - } - - BOOL GetAccessibleContextWithFocus(HWND window, long *vmID, AccessibleContext *ac) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleContextWithFocus(window, vmID, ac); - } - return FALSE; - } - - BOOL GetAccessibleContextInfo(long vmID, AccessibleContext ac, AccessibleContextInfo *info) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleContextInfo(vmID, ac, info); - } - return FALSE; - } - - AccessibleContext GetAccessibleChildFromContext(long vmID, AccessibleContext ac, jint index) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleChildFromContext(vmID, ac, index); - } - return (AccessibleContext) 0; - } - - AccessibleContext GetAccessibleParentFromContext(long vmID, AccessibleContext ac) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleParentFromContext(vmID, ac); - } - return (AccessibleContext) 0; - } - - /* begin AccessibleTable routines */ - - /* - * get information about an AccessibleTable - */ - BOOL getAccessibleTableInfo(long vmID, AccessibleContext acParent, AccessibleTableInfo *tableInfo) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableInfo(vmID, acParent, tableInfo); - } - return FALSE; - } - - /* - * get information about an AccessibleTable cell - */ - BOOL getAccessibleTableCellInfo(long vmID, AccessibleTable accessibleTable, - jint row, jint column, AccessibleTableCellInfo *tableCellInfo) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableCellInfo(vmID, accessibleTable, row, column, tableCellInfo); - } - return FALSE; - } - - /* - * get information about an AccessibleTable row header - */ - BOOL getAccessibleTableRowHeader(long vmID, AccessibleContext acParent, AccessibleTableInfo *tableInfo) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableRowHeader(vmID, acParent, tableInfo); - } - return FALSE; - } - - /* - * get information about an AccessibleTable column header - */ - BOOL getAccessibleTableColumnHeader(long vmID, AccessibleContext acParent, AccessibleTableInfo *tableInfo) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableColumnHeader(vmID, acParent, tableInfo); - } - return FALSE; - } - - /* - * return a description of an AccessibleTable row header - */ - AccessibleContext getAccessibleTableRowDescription(long vmID, AccessibleContext acParent, jint row) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableRowDescription(vmID, acParent, row); - } - return (AccessibleContext)0; - } - - /* - * return a description of an AccessibleTable column header - */ - AccessibleContext getAccessibleTableColumnDescription(long vmID, AccessibleContext acParent, jint column) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableColumnDescription(vmID, acParent, column); - } - return (AccessibleContext)0; - } - - /* - * return the number of rows selected in an AccessibleTable - */ - jint getAccessibleTableRowSelectionCount(long vmID, AccessibleTable table) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableRowSelectionCount(vmID, table); - } - return -1; - } - - /* - * return whether a row is selected in an AccessibleTable - */ - BOOL isAccessibleTableRowSelected(long vmID, AccessibleTable table, jint row) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.isAccessibleTableRowSelected(vmID, table, row); - } - return FALSE; - } - - /* - * get an array of selected rows in an AccessibleTable - */ - BOOL getAccessibleTableRowSelections(long vmID, AccessibleTable table, jint count, jint *selections) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableRowSelections(vmID, table, count, selections); - } - return FALSE; - } - - /* - * return the number of columns selected in an AccessibleTable - */ - jint getAccessibleTableColumnSelectionCount(long vmID, AccessibleTable table) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableColumnSelectionCount(vmID, table); - } - return -1; - } - - /* - * return whether a column is selected in an AccessibleTable - */ - BOOL isAccessibleTableColumnSelected(long vmID, AccessibleTable table, jint column) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.isAccessibleTableColumnSelected(vmID, table, column); - } - return FALSE; - } - - /* - * get an array of columns selected in an AccessibleTable - */ - BOOL getAccessibleTableColumnSelections(long vmID, AccessibleTable table, jint count, jint *selections) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableColumnSelections(vmID, table, count, selections); - } - return FALSE; - } - - /* - * return the row number for a cell at a given index - */ - jint - getAccessibleTableRow(long vmID, AccessibleTable table, jint index) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableRow(vmID, table, index); - } - return -1; - } - - /* - * return the column number for a cell at a given index - */ - jint - getAccessibleTableColumn(long vmID, AccessibleTable table, jint index) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableColumn(vmID, table, index); - } - return -1; - } - - /* - * return the index of a cell at a given row and column - */ - jint - getAccessibleTableIndex(long vmID, AccessibleTable table, jint row, jint column) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleTableIndex(vmID, table, row, column); - } - return -1; - } - - /* end AccessibleTable routines */ - - - /** - * Accessible Text routines - */ - BOOL GetAccessibleTextInfo(long vmID, AccessibleText at, AccessibleTextInfo *textInfo, jint x, jint y) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleTextInfo(vmID, at, textInfo, x, y); - } - return FALSE; - } - - BOOL GetAccessibleTextItems(long vmID, AccessibleText at, AccessibleTextItemsInfo *textItems, jint index) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleTextItems(vmID, at, textItems, index); - } - return FALSE; - } - - BOOL GetAccessibleTextSelectionInfo(long vmID, AccessibleText at, AccessibleTextSelectionInfo *textSelection) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleTextSelectionInfo(vmID, at, textSelection); - } - return FALSE; - } - - BOOL GetAccessibleTextAttributes(long vmID, AccessibleText at, jint index, AccessibleTextAttributesInfo *attributes) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleTextAttributes(vmID, at, index, attributes); - } - return FALSE; - } - - BOOL GetAccessibleTextRect(long vmID, AccessibleText at, AccessibleTextRectInfo *rectInfo, jint index) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleTextRect(vmID, at, rectInfo, index); - } - return FALSE; - } - - BOOL GetAccessibleTextLineBounds(long vmID, AccessibleText at, jint index, jint *startIndex, jint *endIndex) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleTextLineBounds(vmID, at, index, startIndex, endIndex); - } - return FALSE; - } - - BOOL GetAccessibleTextRange(long vmID, AccessibleText at, jint start, jint end, wchar_t *text, short len) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleTextRange(vmID, at, start, end, text, len); - } - return FALSE; - } - - /** - * AccessibleRelationSet routines - */ - BOOL getAccessibleRelationSet(long vmID, AccessibleContext accessibleContext, - AccessibleRelationSetInfo *relationSetInfo) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleRelationSet(vmID, accessibleContext, relationSetInfo); - } - return FALSE; - } - - /** - * AccessibleHypertext routines - */ - - // Gets AccessibleHypertext for an AccessibleContext - BOOL getAccessibleHypertext(long vmID, AccessibleContext accessibleContext, - AccessibleHypertextInfo *hypertextInfo) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleHypertext(vmID, accessibleContext, hypertextInfo); - } - return FALSE; - } - - // Activates an AccessibleHyperlink for an AccessibleContext - BOOL activateAccessibleHyperlink(long vmID, AccessibleContext accessibleContext, - AccessibleHyperlink accessibleHyperlink) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.activateAccessibleHyperlink(vmID, accessibleContext, accessibleHyperlink); - } - return FALSE; - } - - /* - * Returns the number of hyperlinks in a component - * Maps to AccessibleHypertext.getLinkCount. - * Returns -1 on error. - */ - jint getAccessibleHyperlinkCount(const long vmID, - const AccessibleContext accessibleContext) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleHyperlinkCount(vmID, accessibleContext); - } - return -1; - } - - /* - * This method is used to iterate through the hyperlinks in a component. It - * returns hypertext information for a component starting at hyperlink index - * nStartIndex. No more than MAX_HYPERLINKS AccessibleHypertextInfo objects will - * be returned for each call to this method. - * returns FALSE on error. - */ - BOOL getAccessibleHypertextExt(const long vmID, - const AccessibleContext accessibleContext, - const jint nStartIndex, - /* OUT */ AccessibleHypertextInfo *hypertextInfo) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleHypertextExt(vmID, - accessibleContext, - nStartIndex, - hypertextInfo); - } - return FALSE; - } - - /* - * Returns the index into an array of hyperlinks that is associated with - * a character index in document; - * Maps to AccessibleHypertext.getLinkIndex. - * Returns -1 on error. - */ - jint getAccessibleHypertextLinkIndex(const long vmID, - const AccessibleHypertext hypertext, - const jint nIndex) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleHypertextLinkIndex(vmID, - hypertext, - nIndex); - } - return -1; - } - - /* - * Returns the nth hyperlink in a document. - * Maps to AccessibleHypertext.getLink. - * Returns -1 on error - */ - BOOL getAccessibleHyperlink(const long vmID, - const AccessibleHypertext hypertext, - const jint nIndex, - /* OUT */ AccessibleHyperlinkInfo *hyperlinkInfo) { - - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleHyperlink(vmID, - hypertext, - nIndex, - hyperlinkInfo); - } - return FALSE; - } - - - /* Accessible KeyBindings, Icons and Actions */ - BOOL getAccessibleKeyBindings(long vmID, AccessibleContext accessibleContext, - AccessibleKeyBindings *keyBindings) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleKeyBindings(vmID, accessibleContext, keyBindings); - } - return FALSE; - } - - BOOL getAccessibleIcons(long vmID, AccessibleContext accessibleContext, - AccessibleIcons *icons) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleIcons(vmID, accessibleContext, icons); - } - return FALSE; - } - - BOOL getAccessibleActions(long vmID, AccessibleContext accessibleContext, - AccessibleActions *actions) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getAccessibleActions(vmID, accessibleContext, actions); - } - return FALSE; - } - - BOOL doAccessibleActions(long vmID, AccessibleContext accessibleContext, - AccessibleActionsToDo *actionsToDo, jint *failure) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.doAccessibleActions(vmID, accessibleContext, actionsToDo, failure); - } - return FALSE; - } - - /** - * Accessible Value routines - */ - BOOL GetCurrentAccessibleValueFromContext(long vmID, AccessibleValue av, wchar_t *value, short len) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetCurrentAccessibleValueFromContext(vmID, av, value, len); - } - return FALSE; - } - - BOOL GetMaximumAccessibleValueFromContext(long vmID, AccessibleValue av, wchar_t *value, short len) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetMaximumAccessibleValueFromContext(vmID, av, value, len); - } - return FALSE; - } - - BOOL GetMinimumAccessibleValueFromContext(long vmID, AccessibleValue av, wchar_t *value, short len) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetMinimumAccessibleValueFromContext(vmID, av, value, len); - } - return FALSE; - } - - - /** - * Accessible Selection routines - */ - void addAccessibleSelectionFromContext(long vmID, AccessibleSelection as, int i) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.AddAccessibleSelectionFromContext(vmID, as, i); - } - } - - void clearAccessibleSelectionFromContext(long vmID, AccessibleSelection as) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.ClearAccessibleSelectionFromContext(vmID, as); - } - } - - JOBJECT64 GetAccessibleSelectionFromContext(long vmID, AccessibleSelection as, int i) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleSelectionFromContext(vmID, as, i); - } - return (JOBJECT64) 0; - } - - int GetAccessibleSelectionCountFromContext(long vmID, AccessibleSelection as) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.GetAccessibleSelectionCountFromContext(vmID, as); - } - return -1; - } - - BOOL IsAccessibleChildSelectedFromContext(long vmID, AccessibleSelection as, int i) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.IsAccessibleChildSelectedFromContext(vmID, as, i); - } - return FALSE; - } - - void RemoveAccessibleSelectionFromContext(long vmID, AccessibleSelection as, int i) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.RemoveAccessibleSelectionFromContext(vmID, as, i); - } - } - - void SelectAllAccessibleSelectionFromContext(long vmID, AccessibleSelection as) { - if (theAccessBridgeInitializedFlag == TRUE) { - theAccessBridge.SelectAllAccessibleSelectionFromContext(vmID, as); - } - } - - /** - * Additional methods for Teton - */ - - /** - * Gets the AccessibleName for a component based upon the JAWS algorithm. Returns - * whether successful. - * - * Bug ID 4916682 - Implement JAWS AccessibleName policy - */ - BOOL getVirtualAccessibleName(const long vmID, const AccessibleContext accessibleContext, - wchar_t *name, int len) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getVirtualAccessibleName(vmID, accessibleContext, name, len); - } - return FALSE; - } - - /** - * Request focus for a component. Returns whether successful; - * - * Bug ID 4944757 - requestFocus method needed - */ - BOOL requestFocus(const long vmID, const AccessibleContext accessibleContext) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.requestFocus(vmID, accessibleContext); - } - return FALSE; - } - - /** - * Selects text between two indices. Selection includes the text at the start index - * and the text at the end index. Returns whether successful; - * - * Bug ID 4944758 - selectTextRange method needed - */ - BOOL selectTextRange(const long vmID, const AccessibleContext accessibleContext, - const int startIndex, const int endIndex) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.selectTextRange(vmID, accessibleContext, startIndex, endIndex); - } - return FALSE; - } - - /** - * Get text attributes between two indices. The attribute list includes the text at the - * start index and the text at the end index. Returns whether successful; - * - * Bug ID 4944761 - getTextAttributes between two indices method needed - */ - BOOL getTextAttributesInRange(const long vmID, const AccessibleContext accessibleContext, - const int startIndex, const int endIndex, - AccessibleTextAttributesInfo *attributes, short *len) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getTextAttributesInRange(vmID, accessibleContext, startIndex, - endIndex, attributes, len); - } - return FALSE; - } - - /** - * Returns the number of visible children of a component. Returns -1 on error. - * - * Bug ID 4944762- getVisibleChildren for list-like components needed - */ - int getVisibleChildrenCount(const long vmID, const AccessibleContext accessibleContext) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getVisibleChildrenCount(vmID, accessibleContext); - } - return FALSE; - } - - /** - * Gets the visible children of an AccessibleContext. Returns whether successful; - * - * Bug ID 4944762- getVisibleChildren for list-like components needed - */ - BOOL getVisibleChildren(const long vmID, const AccessibleContext accessibleContext, - const int startIndex, VisibleChildrenInfo *visibleChildrenInfo) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getVisibleChildren(vmID, accessibleContext, startIndex, - visibleChildrenInfo); - } - return FALSE; - } - - /** - * Set the caret to a text position. Returns whether successful; - * - * Bug ID 4944770 - setCaretPosition method needed - */ - BOOL setCaretPosition(const long vmID, const AccessibleContext accessibleContext, - const int position) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.setCaretPosition(vmID, accessibleContext, position); - } - return FALSE; - } - - /** - * Gets the text caret location - */ - BOOL getCaretLocation(long vmID, AccessibleContext ac, AccessibleTextRectInfo *rectInfo, jint index) { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getCaretLocation(vmID, ac, rectInfo, index); - } - return FALSE; - } - - /** - * Gets the number of events waiting to fire - */ - int getEventsWaiting() { - if (theAccessBridgeInitializedFlag == TRUE) { - return theAccessBridge.getEventsWaiting(); - } - return FALSE; - } - -#ifdef __cplusplus -} -#endif diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.h --- a/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.h Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.accessibility/windows/native/include/bridge/AccessBridgeCalls.h Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -23,6 +23,25 @@ * questions. */ +/* Note: In addition to this header file AccessBridgeCalls.c must be compiled and + * linked to your application. AccessBridgeCalls.c implements the Java Access + * Bridge API and also hides the complexities associated with interfacing to the + * associated Java Access Bridge DLL which is installed when Java is installed. + * + * AccessBridgeCalls.c is available for download from the OpenJDK repository using + * the following link: + * + * http://hg.openjdk.java.net/jdk9/jdk9/jdk/raw-file/tip/src/jdk.accessibility/windows/native/bridge/AccessBridgeCalls.c + * + * Also note that the API is used in the jaccessinspector and jaccesswalker tools. + * The source for those tools is available in the OpenJDK repository at these links: + * + * http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/tip/src/jdk.accessibility/windows/native/jaccessinspector/jaccessinspector.cpp + * http://hg.openjdk.java.net/jdk9/jdk9/jdk/file/tip/src/jdk.accessibility/windows/native/jaccesswalker/jaccesswalker.cpp + * + * + */ + /* * Wrapper functions around calls to the AccessBridge DLL */ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java --- a/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.crypto.mscapi/windows/classes/sun/security/mscapi/SunMSCAPI.java Wed Jul 05 22:30:52 2017 +0200 @@ -33,6 +33,8 @@ import java.security.ProviderException; import java.util.HashMap; import java.util.Arrays; +import java.util.Map; + import static sun.security.util.SecurityConstants.PROVIDER_VER; /** @@ -133,8 +135,11 @@ /* * Secure random */ + HashMap srattrs = new HashMap<>(1); + srattrs.put("ThreadSafe", "true"); putService(new ProviderService(p, "SecureRandom", - "Windows-PRNG", "sun.security.mscapi.PRNG")); + "Windows-PRNG", "sun.security.mscapi.PRNG", + null, srattrs)); /* * Key store diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java --- a/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.crypto.pkcs11/share/classes/sun/security/pkcs11/SunPKCS11.java Wed Jul 05 22:30:52 2017 +0200 @@ -987,7 +987,8 @@ P11Service(Token token, String type, String algorithm, String className, String[] al, long mechanism) { - super(token.provider, type, algorithm, className, toList(al), null); + super(token.provider, type, algorithm, className, toList(al), + type.equals(SR) ? Map.of("ThreadSafe", "true") : null); this.token = token; this.mechanism = mechanism & 0xFFFFFFFFL; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/JImageTask.java Wed Jul 05 22:30:52 2017 +0200 @@ -32,6 +32,7 @@ import java.nio.file.Files; import java.nio.file.PathMatcher; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.MissingResourceException; @@ -190,19 +191,12 @@ if (options.help) { if (unhandled.isEmpty()) { log.println(TASK_HELPER.getMessage("main.usage", PROGNAME)); - - for (Option o : RECOGNIZED_OPTIONS) { - String name = o.aliases()[0]; - - if (name.startsWith("--")) { - name = name.substring(2); - } else if (name.startsWith("-")) { - name = name.substring(1); - } - - log.println(TASK_HELPER.getMessage("main.opt." + name)); - } - + Arrays.asList(RECOGNIZED_OPTIONS).stream() + .filter(option -> !option.isHidden()) + .sorted() + .forEach(option -> { + log.println(TASK_HELPER.getMessage(option.resourceName())); + }); log.println(TASK_HELPER.getMessage("main.opt.footer")); } else { try { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties Wed Jul 05 22:30:52 2017 +0200 @@ -60,34 +60,36 @@ warn.prefix=Warning: main.opt.dir=\ -\ --dir Target directory for extract directive +\ --dir Target directory for extract directive main.opt.include=\ -\ --include Pattern list for filtering entries. +\ --include Pattern list for filtering entries. + +main.opt.full-version=\ +\ --full-version Print full version information + +main.opt.help=\ +\ -h, --help Print usage message + +main.opt.verbose=\ +\ --verbose Listing prints entry size and offset\n\ +\ attributes + +main.opt.version=\ +\ --version Print version information + +main.command.files=\ +\ @ Read options from file main.opt.footer=\ \n\ -\For options requiring a , the value will be a comma\ -\ separated list of elements each using one the following forms:\n\ +\For options requiring a , the value will be a comma separated\n\ +\list of elements each using one the following forms:\n\ \ \n\ \ glob:\n\ \ regex: -main.opt.full-version=\ -\ --full-version Print full version information - -main.opt.help=\ -\ -h, --help Print usage message - -main.opt.verbose=\ -\ --verbose Listing prints entry size and offset attributes - -main.opt.version=\ -\ --version Print version information - -main.command.files=\ -\ @ Read options from file err.not.a.task=task must be one of : {0} err.missing.arg=no value given for {0} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/Jlink.java Wed Jul 05 22:30:52 2017 +0200 @@ -27,6 +27,7 @@ import java.lang.reflect.Layer; import java.nio.ByteOrder; import java.nio.file.Path; +import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; @@ -278,6 +279,13 @@ */ public void build(JlinkConfiguration config, PluginsConfiguration pluginsConfig) { Objects.requireNonNull(config); + if (pluginsConfig == null) { + pluginsConfig = new PluginsConfiguration(); + } + + // add all auto-enabled plugins from boot layer + pluginsConfig = addAutoEnabledPlugins(pluginsConfig); + try { JlinkTask.createImage(config, pluginsConfig); } catch (Exception ex) { @@ -285,6 +293,19 @@ } } + private PluginsConfiguration addAutoEnabledPlugins(PluginsConfiguration pluginsConfig) { + List plugins = new ArrayList<>(pluginsConfig.getPlugins()); + List bootPlugins = PluginRepository.getPlugins(Layer.boot()); + for (Plugin bp : bootPlugins) { + if (Utils.isAutoEnabled(bp)) { + bp.configure(Collections.emptyMap()); + plugins.add(bp); + } + } + return new PluginsConfiguration(plugins, pluginsConfig.getImageBuilder(), + pluginsConfig.getLastSorterPluginName()); + } + /** * Post process the image with a plugin configuration. * diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java Wed Jul 05 22:30:52 2017 +0200 @@ -134,7 +134,7 @@ }, true, "--full-version"), new Option(false, (task, opt, arg) -> { task.options.ignoreSigning = true; - }, true, "--ignore-signing-information"),}; + }, "--ignore-signing-information"),}; private static final String PROGNAME = "jlink"; private final OptionsValues options = new OptionsValues(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java Wed Jul 05 22:30:52 2017 +0200 @@ -46,8 +46,8 @@ import java.util.MissingResourceException; import java.util.ResourceBundle; import java.util.Set; +import java.util.stream.Stream; -import jdk.tools.jlink.internal.plugins.ExcludeFilesPlugin; import jdk.tools.jlink.internal.plugins.ExcludeJmodSectionPlugin; import jdk.tools.jlink.plugin.Plugin; import jdk.tools.jlink.plugin.Plugin.Category; @@ -90,8 +90,7 @@ public boolean showUsage; } - public static class Option { - + public static class Option implements Comparable { public interface Processing { void process(T task, String opt, String arg) throws BadArgs; @@ -100,17 +99,34 @@ final boolean hasArg; final Processing processing; final boolean hidden; - final String[] aliases; + final String name; + final String shortname; - public Option(boolean hasArg, Processing processing, boolean hidden, String... aliases) { + public Option(boolean hasArg, Processing processing, boolean hidden, String name, String shortname) { + if (!name.startsWith("--")) { + throw new RuntimeException("option name missing --, " + name); + } + if (!shortname.isEmpty() && !shortname.startsWith("-")) { + throw new RuntimeException("short name missing -, " + shortname); + } + this.hasArg = hasArg; this.processing = processing; - this.aliases = aliases; this.hidden = hidden; + this.name = name; + this.shortname = shortname; } - public Option(boolean hasArg, Processing processing, String... aliases) { - this(hasArg, processing, false, aliases); + public Option(boolean hasArg, Processing processing, String name, String shortname) { + this(hasArg, processing, false, name, shortname); + } + + public Option(boolean hasArg, Processing processing, boolean hidden, String name) { + this(hasArg, processing, hidden, name, ""); + } + + public Option(boolean hasArg, Processing processing, String name) { + this(hasArg, processing, false, name, ""); } public boolean isHidden() { @@ -118,16 +134,10 @@ } public boolean matches(String opt) { - for (String a : aliases) { - if (a.equals(opt)) { - return true; - } else if (opt.startsWith("--") - && (hasArg && opt.startsWith(a + "="))) { - return true; - } - } - return false; - } + return opt.equals(name) || + opt.equals(shortname) || + hasArg && opt.startsWith("--") && opt.startsWith(name + "="); + } public boolean ignoreRest() { return false; @@ -137,28 +147,54 @@ processing.process(task, opt, arg); } - public String[] aliases() { - return aliases; + public String getName() { + return name; + } + + public String resourceName() { + return resourcePrefix() + name.substring(2); + } + + public String getShortname() { + return shortname; + } + + public String resourcePrefix() { + return "main.opt."; + } + + @Override + public int compareTo(Object object) { + if (!(object instanceof Option)) { + throw new RuntimeException("comparing non-Option"); + } + + Option option = (Option)object; + + return name.compareTo(option.name); + } + + } + + private static class PluginOption extends Option { + public PluginOption(boolean hasArg, + Processing processing, boolean hidden, String name, String shortname) { + super(hasArg, processing, hidden, name, shortname); + } + + public PluginOption(boolean hasArg, + Processing processing, boolean hidden, String name) { + super(hasArg, processing, hidden, name, ""); + } + + public String resourcePrefix() { + return "plugin.opt."; } } - private static class PlugOption extends Option { - - public PlugOption(boolean hasArg, - Processing processing, boolean hidden, String... aliases) { - super(hasArg, processing, hidden, aliases); - } - - public PlugOption(boolean hasArg, - Processing processing, String... aliases) { - super(hasArg, processing, aliases); - } - } - - private final class PluginsOptions { + private final class PluginsHelper { private static final String PLUGINS_PATH = "--plugin-module-path"; - private static final String POST_PROCESS = "--post-process-path"; private Layer pluginsLayer = Layer.boot(); private final List plugins; @@ -170,10 +206,10 @@ // Each such occurrence results in a Map of arguments. So, there could be multiple // args maps per plugin instance. private final Map>> pluginToMaps = new HashMap<>(); - private final List pluginsOptions = new ArrayList<>(); - private final List mainOptions = new ArrayList<>(); + private final List pluginsOptions = new ArrayList<>(); + private final List mainOptions = new ArrayList<>(); - private PluginsOptions(String pp) throws BadArgs { + private PluginsHelper(String pp) throws BadArgs { if (pp != null) { String[] dirs = pp.split(File.pathSeparator); @@ -193,13 +229,13 @@ addOrderedPluginOptions(plugin, optionsSeen); } } - mainOptions.add(new PlugOption(false, + mainOptions.add(new PluginOption(false, (task, opt, arg) -> { // This option is handled prior // to have the options parsed. }, - "--plugin-module-path")); - mainOptions.add(new PlugOption(true, (task, opt, arg) -> { + false, "--plugin-module-path")); + mainOptions.add(new PluginOption(true, (task, opt, arg) -> { for (Plugin plugin : plugins) { if (plugin.getName().equals(arg)) { pluginToMaps.remove(plugin); @@ -208,24 +244,24 @@ } throw newBadArgs("err.no.such.plugin", arg); }, - "--disable-plugin")); - mainOptions.add(new PlugOption(true, (task, opt, arg) -> { + false, "--disable-plugin")); + mainOptions.add(new PluginOption(true, (task, opt, arg) -> { Path path = Paths.get(arg); if (!Files.exists(path) || !Files.isDirectory(path)) { throw newBadArgs("err.image.must.exist", path); } existingImage = path.toAbsolutePath(); - }, true, POST_PROCESS)); - mainOptions.add(new PlugOption(true, + }, true, "--post-process-path")); + mainOptions.add(new PluginOption(true, (task, opt, arg) -> { lastSorter = arg; }, true, "--resources-last-sorter")); - mainOptions.add(new PlugOption(false, + mainOptions.add(new PluginOption(false, (task, opt, arg) -> { listPlugins = true; }, - "--list-plugins")); + false, "--list-plugins")); } private List> argListFor(Plugin plugin) { @@ -261,8 +297,8 @@ } optionsSeen.add(option); - PlugOption plugOption - = new PlugOption(plugin.hasArguments(), + PluginOption plugOption + = new PluginOption(plugin.hasArguments(), (task, opt, arg) -> { if (!Utils.isFunctional(plugin)) { throw newBadArgs("err.provider.not.functional", @@ -312,7 +348,7 @@ } } }, - "--" + option); + false, "--" + option); pluginsOptions.add(plugOption); if (Utils.isFunctional(plugin)) { @@ -322,44 +358,44 @@ if (plugin instanceof DefaultCompressPlugin) { plugOption - = new PlugOption(false, + = new PluginOption(false, (task, opt, arg) -> { Map m = addArgumentMap(plugin); m.put(DefaultCompressPlugin.NAME, DefaultCompressPlugin.LEVEL_2); - }, "-c"); + }, false, "--compress", "-c"); mainOptions.add(plugOption); } else if (plugin instanceof StripDebugPlugin) { plugOption - = new PlugOption(false, + = new PluginOption(false, (task, opt, arg) -> { addArgumentMap(plugin); - }, "-G"); + }, false, "--strip-debug", "-G"); mainOptions.add(plugOption); } else if (plugin instanceof ExcludeJmodSectionPlugin) { - plugOption = new PlugOption(false, (task, opt, arg) -> { + plugOption = new PluginOption(false, (task, opt, arg) -> { Map m = addArgumentMap(plugin); m.put(ExcludeJmodSectionPlugin.NAME, ExcludeJmodSectionPlugin.MAN_PAGES); - }, "--no-man-pages"); + }, false, "--no-man-pages"); mainOptions.add(plugOption); - plugOption = new PlugOption(false, (task, opt, arg) -> { + plugOption = new PluginOption(false, (task, opt, arg) -> { Map m = addArgumentMap(plugin); m.put(ExcludeJmodSectionPlugin.NAME, ExcludeJmodSectionPlugin.INCLUDE_HEADER_FILES); - }, "--no-header-files"); + }, false, "--no-header-files"); mainOptions.add(plugOption); } } } - private PlugOption getOption(String name) throws BadArgs { - for (PlugOption o : pluginsOptions) { + private PluginOption getOption(String name) throws BadArgs { + for (PluginOption o : pluginsOptions) { if (o.matches(name)) { return o; } } - for (PlugOption o : mainOptions) { + for (PluginOption o : mainOptions) { if (o.matches(name)) { return o; } @@ -461,7 +497,7 @@ private String getPluginsPath(String[] args) throws BadArgs { String pp = null; for (int i = 0; i < args.length; i++) { - if (args[i].equals(PluginsOptions.PLUGINS_PATH)) { + if (args[i].equals(PluginsHelper.PLUGINS_PATH)) { if (i == args.length - 1) { throw new BadArgs("err.no.plugins.path").showUsage(true); } else { @@ -498,13 +534,13 @@ // Must extract it prior to do any option analysis. // Required to interpret custom plugin options. // Unit tests can call Task multiple time in same JVM. - pluginOptions = new PluginsOptions(getPluginsPath(args)); + pluginOptions = new PluginsHelper(getPluginsPath(args)); // First extract plugins path if any String pp = null; List filteredArgs = new ArrayList<>(); for (int i = 0; i < args.length; i++) { - if (args[i].equals(PluginsOptions.PLUGINS_PATH)) { + if (args[i].equals(PluginsHelper.PLUGINS_PATH)) { if (i == args.length - 1) { throw new BadArgs("err.no.plugins.path").showUsage(true); } else { @@ -529,7 +565,7 @@ for (int i = 0; i < args.length; i++) { if (args[i].charAt(0) == '-') { String name = args[i]; - PlugOption pluginOption = null; + PluginOption pluginOption = null; Option option = getOption(name); if (option == null) { pluginOption = pluginOptions.getOption(name); @@ -585,32 +621,13 @@ } public void showHelp(String progName) { - showHelp(progName, true); - } - - private void showHelp(String progName, boolean showsImageBuilder) { log.println(bundleHelper.getMessage("main.usage", progName)); - for (Option o : options) { - String name = o.aliases[0].substring(1); // there must always be at least one name - name = name.charAt(0) == '-' ? name.substring(1) : name; - if (o.isHidden() || name.equals("h")) { - continue; - } - log.println(bundleHelper.getMessage("main.opt." + name)); - } - - for (Option o : pluginOptions.mainOptions) { - if (o.aliases[0].equals(PluginsOptions.POST_PROCESS) - && !showsImageBuilder) { - continue; - } - String name = o.aliases[0].substring(1); // there must always be at least one name - name = name.charAt(0) == '-' ? name.substring(1) : name; - if (o.isHidden()) { - continue; - } - log.println(bundleHelper.getMessage("plugin.opt." + name)); - } + Stream.concat(options.stream(), pluginOptions.mainOptions.stream()) + .filter(option -> !option.isHidden()) + .sorted() + .forEach(option -> { + log.println(bundleHelper.getMessage(option.resourceName())); + }); log.println(bundleHelper.getMessage("main.command.files")); } @@ -619,6 +636,7 @@ log.println("\n" + bundleHelper.getMessage("main.extended.help")); List pluginList = PluginRepository. getPlugins(pluginOptions.pluginsLayer); + for (Plugin plugin : Utils.getSortedPlugins(pluginList)) { showPlugin(plugin, log); } @@ -671,7 +689,7 @@ } } - private PluginsOptions pluginOptions; + private PluginsHelper pluginOptions; private PrintWriter log; private final ResourceBundleHelper bundleHelper; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/packager/AppRuntimeImageBuilder.java Wed Jul 05 22:30:52 2017 +0200 @@ -118,8 +118,6 @@ null)); } - plugins.add(Jlink.newPlugin("installed-modules", Collections.emptyMap(), null)); - // build the image Jlink.PluginsConfiguration pluginConfig = new Jlink.PluginsConfiguration( plugins, new DefaultImageBuilder(outputDir), null); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/jlink.properties Wed Jul 05 22:30:52 2017 +0200 @@ -24,46 +24,51 @@ # main.usage.summary=\ -Usage: {0} --module-path --add-modules --output \n\ -use --help for a list of possible options +Usage: {0} --module-path --add-modules --output\n\ +\ use --help for a list of possible options main.usage=\ -Usage: {0} --module-path --add-modules --output \n\ -\Possible options include: +Usage: {0} --module-path --add-modules --output +\ Possible options include: error.prefix=Error: warn.prefix=Warning: main.opt.help=\ -\ -h, --help Print this help message +\ -h, --help Print this help message main.opt.version=\ -\ --version Version information +\ --version Version information main.opt.module-path=\ -\ -p \n\ -\ --module-path Module path +\ -p, --module-path Module path main.opt.add-modules=\ -\ --add-modules [,...] Root modules to resolve +\ --add-modules [,...] Root modules to resolve main.opt.limit-modules=\ -\ --limit-modules [,...] Limit the universe of observable modules +\ --limit-modules [,...] Limit the universe of observable\n\ +\ modules main.opt.output=\ -\ --output Location of output path +\ --output Location of output path main.command.files=\ -\ @ Read options from file +\ @ Read options from file main.opt.endian=\ -\ --endian Byte order of generated jimage (default:native) +\ --endian Byte order of generated jimage\n\ +\ (default:native) main.opt.save-opts=\ -\ --save-opts Save jlink options in the given file +\ --save-opts Save jlink options in the given file main.opt.ignore-signing-information=\ -\ --ignore-signing-information Ignore signing information in modular JARs +\ --ignore-signing-information Suppress a fatal error when signed\n\ +\ modular JARs are linked in the image.\n\ +\ The signature related files of the\n\ +\ signed modular JARs are not copied to\n\ +\ the runtime image. main.msg.bug=\ An exception has occurred in jlink. \ @@ -75,13 +80,13 @@ \List of available plugins: main.extended.help.footer=\ -\For options requiring a , the value will be a comma\ -\ separated list of elements each using one the following forms:\n\ +\For options requiring a , the value will be a comma separated\n\ +\list of elements each using one the following forms:\n\ \ \n\ \ glob:\n\ \ regex:\n\ -\ @ where filename is the name of a file containing patterns to be\ -\ used, one pattern per line\n\ +\ @ where filename is the name of a file containing patterns to be\n\ +\ used, one pattern per line\n\ \n\ @@ -110,6 +115,6 @@ err.not.modular.format=selected module {0} ({1}) not in jmod or modular JAR format err.signing=signed modular JAR {0} is currently not supported,\ \ use --ignore-signing-information to suppress error -warn.signing=signed modular JAR {0} is currently not supported +warn.signing=WARNING: signed modular JAR {0} is currently not supported warn.invalid.arg=invalid classname or pathname not exist: {0} warn.split.package=package {0} defined in {1} {2} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties --- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties Wed Jul 05 22:30:52 2017 +0200 @@ -132,32 +132,33 @@ List of available plugin options: plugin.opt.list-plugins=\ -\ --list-plugins List available plugins +\ --list-plugins List available plugins plugin.opt.post-process-path=\ -\ --post-process-path Post process an existing image +\ --post-process-path Post process an existing image plugin.opt.resources-last-sorter=\ -\ --resources-last-sorter The last plugin allowed to sort resources +\ --resources-last-sorter The last plugin allowed to sort\n\ +\ resources plugin.opt.plugin-module-path=\ -\ --plugin-module-path Custom plugin module path +\ --plugin-module-path Custom plugin module path plugin.opt.disable-plugin=\ -\ --disable-plugin Disable the plugin mentioned +\ --disable-plugin Disable the plugin mentioned -plugin.opt.c=\ -\ -c, --compress=<0|1|2> Enable compression of resources\ -\n More details in --list-plugins option +plugin.opt.compress=\ +\ -c, --compress=<0|1|2> Enable compression of resources\n\ +\ More details in --list-plugins option -plugin.opt.G=\ -\ -G, --strip-debug Strip debug information +plugin.opt.strip-debug=\ +\ -G, --strip-debug Strip debug information plugin.opt.no-man-pages=\ -\ --no-man-pages Exclude man pages +\ --no-man-pages Exclude man pages plugin.opt.no-header-files=\ -\ --no-header-files Exclude include header files +\ --no-header-files Exclude include header files main.plugin.name=\ \Plugin Name diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/src/jdk.localedata/share/classes/sun/util/resources/ext/CurrencyNames_de_GR.properties --- a/jdk/src/jdk.localedata/share/classes/sun/util/resources/ext/CurrencyNames_de_GR.properties Wed Jul 05 22:29:12 2017 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,39 +0,0 @@ -# -# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. -# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. -# -# This code is free software; you can redistribute it and/or modify it -# under the terms of the GNU General Public License version 2 only, as -# published by the Free Software Foundation. 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. -# - -# (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved -# (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved -# -# The original version of this source code and documentation -# is copyrighted and owned by Taligent, Inc., a wholly-owned -# subsidiary of IBM. These materials are provided under terms -# of a License Agreement between Taligent and Sun. This technology -# is protected by multiple US and International patents. -# -# This notice and attribution to Taligent may not be removed. -# Taligent is a registered trademark of Taligent, Inc. - -EUR=\u20AC -GRD=\u03B4\u03C1\u03C7 diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/Makefile --- a/jdk/test/Makefile Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/Makefile Wed Jul 05 22:30:52 2017 +0200 @@ -55,7 +55,7 @@ UNAME = uname UNIQ = uniq WC = wc -ZIP = zip +ZIPEXE = zip # Get OS name from uname (Cygwin inexplicably adds _NT-5.1) UNAME_S := $(shell $(UNAME) -s | $(CUT) -f1 -d_) @@ -162,7 +162,7 @@ ZIP_UP_RESULTS = ( $(MKDIR) -p `$(DIRNAME) $(ARCHIVE_BUNDLE)` \ && $(CD) $(ABS_TEST_OUTPUT_DIR) \ && $(CHMOD) -R a+r . \ - && $(ZIP) -q -r $(ARCHIVE_BUNDLE) . ) + && $(ZIPEXE) -q -r $(ARCHIVE_BUNDLE) . ) # important results files SUMMARY_TXT = $(shell $(GETMIXEDPATH) "$(ABS_TEST_OUTPUT_DIR)/JTreport/text/summary.txt") diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/ProblemList.txt --- a/jdk/test/ProblemList.txt Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/ProblemList.txt Wed Jul 05 22:30:52 2017 +0200 @@ -135,7 +135,7 @@ java/lang/instrument/BootClassPath/BootClassPathTest.sh 8072130 macosx-all java/lang/management/MemoryMXBean/Pending.java 8158837 generic-all -java/lang/management/MemoryMXBean/PendingAllGC.sh 8158760 generic-all +java/lang/management/MemoryMXBean/PendingAllGC.sh 8158837 generic-all ############################################################################ @@ -252,10 +252,14 @@ # core_tools -tools/pack200/CommandLineTests.java 7143279,8059906 generic-all +tools/pack200/CommandLineTests.java 8059906 generic-all tools/launcher/FXLauncherTest.java 8068049 linux-all,macosx-all +tools/jimage/JImageExtractTest.java 8169713 generic-all +tools/jimage/JImageListTest.java 8169713 generic-all +tools/jimage/JImageVerifyTest.java 8169713 generic-all + ############################################################################ # jdk_jdi @@ -300,6 +304,6 @@ # jdk_other -com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java 8141370 linux-i586,macosx-all +com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java 8169942 linux-i586,macosx-all,windows-x64 ############################################################################ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/com/sun/jndi/dns/CheckAccess.java --- a/jdk/test/com/sun/jndi/dns/CheckAccess.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/com/sun/jndi/dns/CheckAccess.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2009, 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 @@ -24,11 +24,13 @@ /* * @test * @bug 6657619 + * @modules jdk.naming.dns * @summary DnsContext.debug is public static mutable (findbugs) * @author Vincent Ryan */ -import java.lang.reflect.*; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; /* * Check that the 'debug' class member is no longer publicly accessible. diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/com/sun/jndi/dns/Test6991580.java --- a/jdk/test/com/sun/jndi/dns/Test6991580.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/com/sun/jndi/dns/Test6991580.java Wed Jul 05 22:30:52 2017 +0200 @@ -30,13 +30,14 @@ import java.awt.event.ActionEvent; import java.awt.event.ActionListener; -/** +/* * @test * @bug 6991580 8080108 8133035 * @requires os.family != "windows" * @summary IPv6 Nameservers in resolv.conf throws NumberFormatException - * @modules jdk.naming.dns/com.sun.jndi.dns - * @build IPv6NameserverPlatformParsingTest + * @modules java.desktop + * jdk.naming.dns/com.sun.jndi.dns + * @compile --add-modules jdk.naming.dns IPv6NameserverPlatformParsingTest.java * @run main/manual Test6991580 */ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/com/sun/jndi/ldap/TEST.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/com/sun/jndi/ldap/TEST.properties Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,1 @@ +modules = java.naming diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java --- a/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/com/sun/jndi/rmi/registry/RegistryContext/UnbindIdempotent.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -28,6 +28,7 @@ * successfully. * @modules java.rmi/sun.rmi.registry java.rmi/sun.rmi.server * java.rmi/sun.rmi.transport java.rmi/sun.rmi.transport.tcp + * jdk.naming.rmi * @library ../../../../../../java/rmi/testlibrary * @build TestLibrary * @run main UnbindIdempotent @@ -49,8 +50,10 @@ try { rctx = (Context)ictx.lookup("rmi://localhost:" + Integer.toString(registryPort)); + System.out.println("Got context: " + rctx.getClass()); } catch (NamingException e) { // Unable to set up for test. + System.err.println("WARNING: The test skipped due to NamingException: " + e); return; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/com/sun/nio/sctp/TEST.properties --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/com/sun/nio/sctp/TEST.properties Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,2 @@ +modules = jdk.sctp + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java --- a/jdk/test/java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/awt/FileDialog/FileDialogIconTest/FileDialogIconTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -22,21 +22,28 @@ */ /* @test - * @bug 8157163 + * @bug 8157163 8159132 * @summary AWT FileDialog does not inherit icon image from parent Frame * @requires os.family=="windows" * @run main FileDialogIconTest */ -import javax.swing.*; -import java.awt.*; + +import java.awt.Color; +import java.awt.Dialog; +import java.awt.FileDialog; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Point; +import java.awt.Robot; +import java.awt.Image; import java.awt.image.BufferedImage; -import java.lang.reflect.InvocationTargetException; +import javax.swing.SwingUtilities; public class FileDialogIconTest { private static Frame frame; private static Dialog dialog; - public static void main(final String[] args) throws InterruptedException, InvocationTargetException, AWTException { + public static void main(final String[] args) throws Exception { Robot robot; Point p; try { @@ -51,9 +58,9 @@ dialog.setModal(false); dialog.setVisible(true); robot.waitForIdle(); - robot.delay(200); + robot.delay(1000); - p = new Point(10, 10); + p = new Point(20, 20); SwingUtilities.convertPointToScreen(p, dialog); Color color = robot.getPixelColor(p.x, p.y); if (!Color.RED.equals(color)) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/Focus/DisposedWindow/DisposeDialogNotActivateOwnerTest/DisposeDialogNotActivateOwnerTest.java --- a/jdk/test/java/awt/Focus/DisposedWindow/DisposeDialogNotActivateOwnerTest/DisposeDialogNotActivateOwnerTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/awt/Focus/DisposedWindow/DisposeDialogNotActivateOwnerTest/DisposeDialogNotActivateOwnerTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -22,237 +22,103 @@ */ /* - test - @bug 6386592 - @summary Tests that disposing a dialog doesn't activate its invisible owner. - @author anton.tarasov@sun.com: area=awt.focus - @run applet DisposeDialogNotActivateOwnerTest.html + @test + @key headful + @bug 6386592 8160766 + @summary Tests that disposing a dialog doesn't activate its invisible owner. */ -import java.awt.*; -import java.awt.event.*; -import java.applet.Applet; +import java.awt.AWTException; +import java.awt.Button; +import java.awt.Component; +import java.awt.Dialog; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Point; +import java.awt.Robot; +import java.awt.event.FocusAdapter; +import java.awt.event.FocusEvent; +import java.awt.event.InputEvent; -public class DisposeDialogNotActivateOwnerTest extends Applet { +public class DisposeDialogNotActivateOwnerTest { Robot robot; - - Frame frame = new Frame("Owner Frame"); - Dialog dialog = new Dialog(new Frame(), "Owned Dialog"); - Button frameButton = new Button("button"); - - static boolean passed = false; + Frame frame; + Frame dialogInvisibleOwner; + Dialog dialog; + Button frameButton; + static volatile boolean buttonReceivedFocus = false; public static void main(String[] args) { - DisposeDialogNotActivateOwnerTest app = new DisposeDialogNotActivateOwnerTest(); - app.init(); - app.start(); + DisposeDialogNotActivateOwnerTest test = + new DisposeDialogNotActivateOwnerTest(); + test.performTest(); + test.dispose(); } - public void init() { + public DisposeDialogNotActivateOwnerTest() { try { robot = new Robot(); } catch (AWTException e) { - throw new RuntimeException("Error: unable to create robot", e); + throw new RuntimeException("Error: unable to create robot"); } - // Create instructions for the user here, as well as set up - // the environment -- set the layout manager, add buttons, - // etc. - this.setLayout (new BorderLayout ()); - Sysout.createDialogWithInstructions(new String[] - {"This is automatic test. Simply wait until it is done." - }); + + dialogInvisibleOwner = new Frame("Dialog Invisible Owner Frame"); + dialog = new Dialog(dialogInvisibleOwner, "Owned Dialog"); - frame.setBounds(800, 50, 200, 100); + frame = new Frame("A Frame"); + frameButton = new Button("button"); + frameButton.addFocusListener(new FocusAdapter() { + public void focusGained(FocusEvent e) { + buttonReceivedFocus = true; + } + }); + frame.setBounds(0, 0, 400, 200); frame.add(frameButton); - dialog.setBounds(800, 300, 200, 100); + dialog.setBounds(100, 50, 200, 100); } - public void start() { - - frameButton.addFocusListener(new FocusAdapter() { - public void focusGained(FocusEvent e) { - passed = true; - } - }); - + public void performTest() { frame.setVisible(true); robot.waitForIdle(); - - // make sure the frame is focused - clickOn(frame); + clickOnTitle(frame); + robot.waitForIdle(); + robot.delay(200); if (!frame.isFocused()) { - throw new RuntimeException("Error: a frame didn't get initial focus."); + dispose(); + throw new RuntimeException("Error: frame didn't get initial focus"); } dialog.setVisible(true); robot.waitForIdle(); - - // make sure the dialog is focused + robot.delay(200); if (!dialog.isFocused()) { - throw new RuntimeException("Error: a dialog didn't get initial focus."); + dispose(); + throw new RuntimeException("Error: dialog didn't get initial focus"); } dialog.dispose(); robot.waitForIdle(); - - if (passed) { - Sysout.println("Test passed."); - } else { - throw new RuntimeException("Test failed: a dialog activates invisible owner when disposed!"); + robot.delay(200); + if (!buttonReceivedFocus) { + dispose(); + throw new RuntimeException( + "Test failed: Dialog activates invisible owner when disposed!"); } } - void clickOn(Component c) { + public void dispose() { + frame.dispose(); + dialog.dispose(); + dialogInvisibleOwner.dispose(); + } + + void clickOnTitle(Component c) { Point p = c.getLocationOnScreen(); Dimension d = c.getSize(); - - if (c instanceof Frame) { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + ((Frame)c).getInsets().top/2); - } else { - robot.mouseMove(p.x + (int)(d.getWidth()/2), p.y + (int)(d.getHeight()/2)); - } - + robot.mouseMove(p.x + (int)(d.getWidth() / 2), + p.y + ((Frame)c).getInsets().top / 2); robot.mousePress(InputEvent.BUTTON1_MASK); robot.delay(20); robot.mouseRelease(InputEvent.BUTTON1_MASK); - - robot.waitForIdle(); } } - -/**************************************************** - 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 -{ - static TestDialog dialog; - - public static void createDialogWithInstructions( String[] instructions ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - dialog.printInstructions( instructions ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - public static void createDialog( ) - { - dialog = new TestDialog( new Frame(), "Instructions" ); - String[] defInstr = { "Instructions will appear here. ", "" } ; - dialog.printInstructions( defInstr ); - dialog.setVisible(true); - println( "Any messages for the tester will display here." ); - } - - - public static void printInstructions( String[] instructions ) - { - dialog.printInstructions( instructions ); - } - - - public static void println( String messageIn ) - { - dialog.displayMessage( messageIn ); - } - -}// Sysout class - -/** - This is part of the standard test machinery. It provides a place for the - test instructions to be displayed, and a place for interactive messages - to the user to be displayed. - To have the test instructions displayed, see Sysout. - To have a message to the user be displayed, see Sysout. - Do not call anything in this dialog directly. - */ -class TestDialog extends Dialog -{ - - TextArea instructionsText; - TextArea messageText; - int maxStringLength = 80; - - //DO NOT call this directly, go through Sysout - public TestDialog( Frame frame, String name ) - { - super( frame, name ); - int scrollBoth = TextArea.SCROLLBARS_BOTH; - instructionsText = new TextArea( "", 15, maxStringLength, scrollBoth ); - add( "North", instructionsText ); - - messageText = new TextArea( "", 5, maxStringLength, scrollBoth ); - add("Center", messageText); - - pack(); - - setVisible(true); - }// TestDialog() - - //DO NOT call this directly, go through Sysout - public void printInstructions( String[] instructions ) - { - //Clear out any current instructions - instructionsText.setText( "" ); - - //Go down array of instruction strings - - String printStr, remainingStr; - for( int i=0; i < instructions.length; i++ ) - { - //chop up each into pieces maxSringLength long - remainingStr = instructions[ i ]; - while( remainingStr.length() > 0 ) - { - //if longer than max then chop off first max chars to print - if( remainingStr.length() >= maxStringLength ) - { - //Try to chop on a word boundary - int posOfSpace = remainingStr. - lastIndexOf( ' ', maxStringLength - 1 ); - - if( posOfSpace <= 0 ) posOfSpace = maxStringLength - 1; - - printStr = remainingStr.substring( 0, posOfSpace + 1 ); - remainingStr = remainingStr.substring( posOfSpace + 1 ); - } - //else just print - else - { - printStr = remainingStr; - remainingStr = ""; - } - - instructionsText.append( printStr + "\n" ); - - }// while - - }// for - - }//printInstructions() - - //DO NOT call this directly, go through Sysout - public void displayMessage( String messageIn ) - { - messageText.append( messageIn + "\n" ); - System.out.println(messageIn); - } - -}// TestDialog class diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.html Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,40 @@ + + + + + SpanishDiacriticsTest + + + + +Test run requires the following keyboard layout to be installed: +Windows OS: Spanish (United States) with 'Latin American' keyboard layout + +1. A frame with a text field should be displayed at upper left corner +2. Set focus to the text field and switch to Spanish with 'Latin American' keyboard layout +3. Type the following: ' ' o - i.e. single quote two times (using [ key on US keyboard) then o character. + +If you the text field displays ''o, (i.e. o should be without acute) then the test is passed; otherwise failed. + + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/awt/InputMethods/SpanishDiacriticsTest/SpanishDiacriticsTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8169355 + * @summary Check if Spanish diacritical signs could be typed for TextField + * @author Dmitry Markov + * @run applet/manual=yesno SpanishDiacriticsTest.html +*/ + +import javax.swing.*; +import java.applet.Applet; +import java.awt.event.KeyAdapter; +import java.awt.event.KeyEvent; +import java.util.concurrent.locks.LockSupport; + +public class SpanishDiacriticsTest extends Applet { + @Override + public void init() { + SwingUtilities.invokeLater(() -> { + JFrame frame = new JFrame(); + JTextField textField = new JTextField(20); + textField.addKeyListener(new KeyAdapter() { + @Override + public void keyTyped(KeyEvent e) { + LockSupport.parkNanos(1_000_000_000L); + } + }); + frame.add(textField); + frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.pack(); + frame.setVisible(true); + }); + } +} + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/KeyboardFocusmanager/DefaultPolicyChange/DefaultPolicyChange_Swing.java --- a/jdk/test/java/awt/KeyboardFocusmanager/DefaultPolicyChange/DefaultPolicyChange_Swing.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/awt/KeyboardFocusmanager/DefaultPolicyChange/DefaultPolicyChange_Swing.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 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 @@ -23,32 +23,25 @@ /* @test - @bug 6741526 + @bug 6741526 8004693 @summary KeyboardFocusManager.setDefaultFocusTraversalPolicy(FocusTraversalPolicy) affects created components - @library ../../regtesthelpers - @build Sysout @author Andrei Dmitriev : area=awt-focus @run main DefaultPolicyChange_Swing */ import java.awt.*; + import javax.swing.*; import javax.swing.table.DefaultTableModel; -import test.java.awt.regtesthelpers.Sysout; public class DefaultPolicyChange_Swing { - public static void main(String []s) { - EventQueue.invokeLater(new Runnable(){ - public void run (){ - DefaultPolicyChange_Swing.runTestSwing(); - } - }); + + public static void main(final String[] s) throws Exception { + EventQueue.invokeAndWait(DefaultPolicyChange_Swing::runTestSwing); } + private static void runTestSwing(){ KeyboardFocusManager currentKFM = KeyboardFocusManager.getCurrentKeyboardFocusManager(); - FocusTraversalPolicy defaultFTP = currentKFM.getDefaultFocusTraversalPolicy(); - ContainerOrderFocusTraversalPolicy newFTP = new ContainerOrderFocusTraversalPolicy(); - JFrame jf = new JFrame("Test1"); JWindow jw = new JWindow(jf); @@ -71,22 +64,35 @@ throw new RuntimeException("Failure! Swing toplevel must have LayoutFocusTraversalPolicy installed"); } + FocusTraversalPolicy[] defaultFTP = { + jf.getFocusTraversalPolicy(), jw.getFocusTraversalPolicy(), + jd.getFocusTraversalPolicy() + }; + jf.setVisible(true); System.out.println("Now will set another policy."); + ContainerOrderFocusTraversalPolicy newFTP = new ContainerOrderFocusTraversalPolicy(); currentKFM.setDefaultFocusTraversalPolicy(newFTP); - FocusTraversalPolicy resultFTP = jw.getFocusTraversalPolicy(); + FocusTraversalPolicy[] resultFTP = { + jf.getFocusTraversalPolicy(), jw.getFocusTraversalPolicy(), + jd.getFocusTraversalPolicy() + }; System.out.println("FTP current on jf= " + jf.getFocusTraversalPolicy()); System.out.println("FTP current on jw= " + jw.getFocusTraversalPolicy()); System.out.println("FTP current on jd= " + jd.getFocusTraversalPolicy()); - if (!resultFTP.equals(defaultFTP)) { - Sysout.println("Failure! FocusTraversalPolicy should not change"); - Sysout.println("Was: " + defaultFTP); - Sysout.println("Become: " + resultFTP); - throw new RuntimeException("Failure! FocusTraversalPolicy should not change"); + jf.dispose(); + + for (int i=0; i < 3; i++) { + if (!resultFTP[i].equals(defaultFTP[i])) { + System.out.println("Failure! FocusTraversalPolicy should not change"); + System.out.println("Was: " + defaultFTP[i]); + System.out.println("Become: " + resultFTP[i]); + throw new RuntimeException("Failure! FocusTraversalPolicy should not change"); + } } } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/image/OpaquePNGToGIFTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/awt/image/OpaquePNGToGIFTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,422 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + + /* + * @test + * @bug 6334602 + * @summary Test verifies that when we create GIF image from Opaque PNG images + * it should not be transparent. + * @modules java.desktop/com.sun.imageio.plugins.gif + * @run main/manual OpaquePNGToGIFTest + */ + +import java.awt.image.BufferedImage; +import com.sun.imageio.plugins.gif.GIFImageMetadata; +import java.awt.Canvas; +import java.awt.Color; +import java.awt.Dimension; +import java.awt.Frame; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Image; +import java.awt.Toolkit; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.ImageTypeSpecifier; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.metadata.IIOMetadata; +import javax.imageio.stream.ImageInputStream; +import javax.imageio.stream.ImageOutputStream; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.SwingUtilities; + +public final class OpaquePNGToGIFTest extends Frame { + + Image img = null; + private Dimension prefImgSize = new Dimension(100, 100); + private Color canvasColor = new Color(0, 255, 0); + File outputFile = null; + ImageCanvas imageCanvas = new ImageCanvas(); + FileOutputStream fos; + private static GridBagLayout layout; + private static JPanel mainControlPanel; + private static JPanel resultButtonPanel; + private static JPanel canvasPanel; + private static JLabel instructionText; + private static JButton startTestButton; + private static JButton passButton; + private static JButton failButton; + private static JDialog dialog; + private static Frame instructionFrame; + private static Frame imageFrame; + Toolkit tk; + ImageWriter writer = null; + boolean testPassed, testGeneratedInterrupt, startButtonClicked; + private static Thread mainThread; + + public OpaquePNGToGIFTest() throws Exception { + SwingUtilities.invokeAndWait(() -> { + try { + startTest(); + } catch (Exception ex) { + Logger.getLogger(OpaquePNGToGIFTest.class.getName()). + log(Level.SEVERE, null, ex); + } + }); + mainThread = Thread.currentThread(); + try { + Thread.sleep(60000); + } catch (InterruptedException e) { + if (!testPassed && testGeneratedInterrupt) { + throw new RuntimeException("Test failed or didnt run" + + " properly"); + } + } + if (!testGeneratedInterrupt) { + if (img != null) { + img.flush(); + } + instructionFrame.dispose(); + if (startButtonClicked) { + imageFrame.dispose(); + } + fos.close(); + Files.delete(outputFile.toPath()); + throw new RuntimeException("user has not executed the test"); + } + } + + public void startTest() throws Exception { + instructionFrame = new Frame(); + dialog = new JDialog(instructionFrame); + dialog.setTitle("Instruction Dialog"); + layout = new GridBagLayout(); + mainControlPanel = new JPanel(layout); + resultButtonPanel = new JPanel(layout); + canvasPanel = new JPanel(); + GridBagConstraints gbc = new GridBagConstraints(); + String instructions + = " INSTRUCTIONS:

    " + + "After clicking on Start Test button you will see Red
    " + + " circle drawn with light blue background, if the circle
    " + + " color changes from Red to Green then press button Fail,
    " + + " if it stays Red then press button Pass.

    "; + instructionText = new JLabel(); + instructionText.setText(instructions); + + gbc.gridx = 0; + gbc.gridy = 0; + gbc.fill = GridBagConstraints.HORIZONTAL; + mainControlPanel.add(instructionText, gbc); + startTestButton = new JButton("Start Test"); + startTestButton.setActionCommand("Start Test"); + startTestButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + startButtonClicked = true; + imageFrame = new Frame(); + + Iterator it = ImageIO.getImageWritersByFormatName("GIF"); + while (it.hasNext()) { + writer = (ImageWriter) it.next(); + break; + } + // read input opaque PNG image. + String fileName = "opaque_input.png"; + String sep = System.getProperty("file.separator"); + String dir = System.getProperty("test.src", "."); + System.out.println(dir + " " + sep); + String filePath = dir + sep + fileName; + File inputFile = new File(filePath); + ImageInputStream iis = ImageIO. + createImageInputStream(inputFile); + ImageReader reader = null; + Iterator readerIter = ImageIO.getImageReaders(iis); + while (readerIter.hasNext()) { + reader = (ImageReader) readerIter.next(); + break; + } + + reader.setInput(iis); + IIOMetadata imgData = reader.getImageMetadata(0); + BufferedImage bi = reader.read(0); + + //create temporary GIF imageas output + File directory = new File(dir + sep); + outputFile = File.createTempFile("output", + ".gif", directory); + createAnimatedImage(bi, imgData, + writer, outputFile); + writer.dispose(); + iis.close(); + if (outputFile == null) { + throw new RuntimeException("Unable to create output GIF" + + " file"); + } + // extract GIF image using Toolkit and show it on a Panel. + tk = Toolkit.getDefaultToolkit(); + img = tk.getImage(dir + sep + outputFile.getName()); + directory.delete(); + imageCanvas.setBackground(canvasColor); + imageCanvas.setImage(img); + imageCanvas.setPreferredSize(prefImgSize); + canvasPanel.doLayout(); + + canvasPanel.add(imageCanvas); + imageFrame.add("Center", canvasPanel); + imageFrame.setSize(200, 200); + imageFrame.setVisible(true); + imageFrame.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + try { + img.flush(); + instructionFrame.dispose(); + imageFrame.dispose(); + fail(); + } finally { + try { + fos.close(); + Files.delete(outputFile.toPath()); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class. + getName()).log(Level.SEVERE, null, + ex); + } + } + } + }); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class.getName()). + log(Level.SEVERE, null, ex); + } + } + }); + passButton = new JButton("Pass"); + passButton.setActionCommand("Pass"); + passButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + if (img != null) { + img.flush(); + } + instructionFrame.dispose(); + if (!startButtonClicked) { + fail(); + } else { + imageFrame.dispose(); + pass(); + } + } finally { + try { + fos.close(); + Files.delete(outputFile.toPath()); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class. + getName()).log(Level.SEVERE, null, ex); + } + } + } + }); + failButton = new JButton("Fail"); + failButton.setActionCommand("Fail"); + failButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + try { + if (img != null) { + img.flush(); + } + instructionFrame.dispose(); + if (!startButtonClicked) { + fail(); + } else { + imageFrame.dispose(); + fail(); + } + } finally { + try { + fos.close(); + Files.delete(outputFile.toPath()); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class. + getName()).log(Level.SEVERE, null, ex); + } + } + } + }); + gbc.gridx = 1; + gbc.gridy = 0; + resultButtonPanel.add(startTestButton, gbc); + gbc.gridx = 2; + gbc.gridy = 0; + resultButtonPanel.add(passButton, gbc); + gbc.gridx = 3; + gbc.gridy = 0; + resultButtonPanel.add(failButton, gbc); + + gbc.gridx = 0; + gbc.gridy = 1; + mainControlPanel.add(resultButtonPanel, gbc); + + dialog.add(mainControlPanel); + dialog.setSize(400, 200); + dialog.setLocationRelativeTo(null); + dialog.setVisible(true); + + dialog.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + try { + if (img != null) { + img.flush(); + } + instructionFrame.dispose(); + if (!startButtonClicked) { + fail(); + } else { + imageFrame.dispose(); + fail(); + } + } finally { + try { + fos.close(); + Files.delete(outputFile.toPath()); + } catch (IOException ex) { + Logger.getLogger(OpaquePNGToGIFTest.class. + getName()).log(Level.SEVERE, null, ex); + } + } + } + }); + } + + public synchronized void pass() { + testPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + public synchronized void fail() { + testPassed = false; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + public void createAnimatedImage(BufferedImage bi, IIOMetadata metadata, + ImageWriter writer, File outputFile) { + try { + + fos = new FileOutputStream(outputFile); + ImageOutputStream ios = ImageIO.createImageOutputStream(fos); + System.out.println(ios); + writer.setOutput(ios); + + ImageWriteParam param = writer.getDefaultWriteParam(); + IIOMetadata streamData = writer.getDefaultStreamMetadata(param); + + writer.prepareWriteSequence(streamData); + ImageTypeSpecifier specify = new ImageTypeSpecifier(bi); + IIOMetadata imgData = writer.convertImageMetadata( + (IIOMetadata) metadata, specify, param); + GIFImageMetadata gifData = setAnimationProperties(imgData); + IIOImage iim = new IIOImage(bi, null, gifData); + param.setProgressiveMode(param.MODE_DISABLED); + writer.writeToSequence(iim, param); + writer.endWriteSequence(); + ios.close(); + } catch (Exception e) { + e.printStackTrace(); + } + } + + public GIFImageMetadata setAnimationProperties(IIOMetadata data) { + ArrayList appIDs = new ArrayList(); + appIDs.add(new String("NETSCAPE").getBytes()); + ArrayList authCodes = new ArrayList(); + authCodes.add(new String("2.0").getBytes()); + ArrayList appData = new ArrayList(); + byte[] authData = {1, 0, 0}; + appData.add(authData); + + GIFImageMetadata gifData = (GIFImageMetadata) data; + gifData.delayTime = 200; + // If we set disposalMethod to 2 then only the issue is reproduced. + gifData.disposalMethod = 2; + gifData.userInputFlag = false; + + gifData.applicationIDs = appIDs; + gifData.authenticationCodes = authCodes; + gifData.applicationData = appData; + + return gifData; + } + + public static void main(String args[]) throws Exception { + OpaquePNGToGIFTest test = new OpaquePNGToGIFTest(); + } + + class ImageCanvas extends Canvas { + + Image im = null; + + public void setImage(Image img) { + im = img; + } + + public void clearImage() { + im = null; + repaint(); + } + + public void paint(Graphics g) { + Graphics2D g2d = (Graphics2D) g; + + if (im != null) { + g2d.drawImage(im, 1, 1, getWidth(), getHeight(), this); + } + } + } +} + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/image/VolatileImage/VolatileImageConfigurationTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/awt/image/VolatileImage/VolatileImageConfigurationTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,267 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 8165212 + * @summary This manual test case displays scale values of Graphics and the + * underlying device configuration. Any change to host display's DPI + * value should reflect corresponding changes in the scale values + * of both Frame and Backbuffer (VolatileImage). + * @run main/othervm/manual -Dsun.java2d.d3d=false -Dsun.java2d.opengl=false VolatileImageConfigurationTest + */ +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.GraphicsConfiguration; +import java.awt.Color; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.geom.AffineTransform; +import java.awt.image.VolatileImage; +import java.awt.HeadlessException; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.JButton; +import javax.swing.SwingUtilities; + +public class VolatileImageConfigurationTest + extends JFrame + implements ActionListener { + /* Test frame and completion status */ + private static JFrame testFrame; + private static volatile boolean testComplete = false; + private static volatile boolean testResult = false; + + /* Main frame's dimensions */ + private static final int TEST_WIDTH = 600; + private static final int TEST_HEIGHT = 600; + private static final int TEST_MIN_DURATION = 3000; + private static final int TEST_TOTAL_DURATION = 45000; + + /* + * Frame will display information text explaining how to run the manual + * test, and two buttons- Pass and Fail to determine the end-result. + */ + private JTextArea infoTextArea; + private JPanel buttonPanel; + private JPanel testPanel; + private JButton passButton; + private JButton failButton; + + public VolatileImageConfigurationTest() { + /* Default constructor. Initialize the UI components */ + super("Volatile Image Configuration Update Test"); + initComponents(); + } + + private void initComponents() { + /* Create the text area with steps to execute the test */ + String description + = "\n Volatile Image Configuration Update Test.\n" + + " 1. The test displays scale values of component and the" + + " underlying graphics device configuration.\n" + + " 2. Kindly change the display's DPI settings from OS" + + " control panel and observe the application.\n" + + " 3. Select Pass if the scale values for both component & " + + "underlying device configuration are updated as per the " + + "\ndisplay's DPI value.\n"; + infoTextArea = new JTextArea(description); + + /* Create the test panel where user will observe the drawing */ + testPanel = new DisplayPanel(); + + /* Create the buttons with event listeners */ + passButton = new JButton("Pass"); + passButton.setActionCommand("Pass"); + passButton.setEnabled(true); + passButton.addActionListener(this); + + failButton = new JButton("Fail"); + failButton.setActionCommand("Fail"); + failButton.setEnabled(true); + failButton.addActionListener(this); + + /* Add the buttons to a separate panel with flowlayout */ + buttonPanel = new JPanel(new FlowLayout()); + buttonPanel.add(passButton); + buttonPanel.add(failButton); + + /* Add all the created components to the master frame */ + setLayout(new BorderLayout(10, 10)); + add(infoTextArea, BorderLayout.NORTH); + add(buttonPanel, BorderLayout.SOUTH); + add(testPanel, BorderLayout.CENTER); + + /* Set the dimensions */ + setSize(TEST_WIDTH, TEST_HEIGHT); + } + + @Override + public void actionPerformed(ActionEvent e) { + /* Button event listener */ + String command = e.getActionCommand(); + + if (command.equals("Pass")) { + /* Test has passed. Dispose the frame with success message */ + testComplete = true; + testResult = true; + System.out.println("Test Passed."); + } else if (command.equals("Fail")) { + /* Test has failed. Dispose the frame and throw exception */ + testComplete = true; + testResult = false; + } + } + + private static void constructTestUI() { + /* Construct the test's user interface */ + testFrame = new VolatileImageConfigurationTest(); + testFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + testFrame.setLocationRelativeTo(null); + testFrame.setVisible(true); + } + + private static void destructTestUI() { + /* Destroy the test's user interface */ + testFrame.dispose(); + } + + static class DisplayPanel extends JPanel { + /* Display panel settings */ + private static final int PANEL_WIDTH = 600; + private static final int PANEL_HEIGHT = 500; + private static final int PANEL_X = 20; + private static final int PANEL_Y = 80; + private static final String MSG = "%s scale: [%2.2f, %2.2f]"; + private VolatileImage vImg; + + public DisplayPanel() throws HeadlessException { + setSize(PANEL_WIDTH, PANEL_HEIGHT); + } + + @Override + public void paint(Graphics g) { + super.paint(g); + + g.setColor(Color.WHITE); + g.fillRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT); + /* Display graphics configuration values of the component */ + drawInfo(g, PANEL_X, PANEL_Y, "Frame", Color.BLUE); + int attempts = 0; + do { + /* Display graphics configuration values of volatile image */ + drawBackingStoreImage(g); + } while (vImg.contentsLost() && ++attempts < 3); + } + + private void drawInfo(Graphics g, int x, int y, + String msg, Color color) { + g.setColor(color); + g.setFont(g.getFont().deriveFont(24f)); + Graphics2D g2d = (Graphics2D) g; + AffineTransform tx = g2d.getTransform(); + + g.drawString(msg, x, y); + String text = String.format(MSG, + "Graphics", + tx.getScaleX(), + tx.getScaleY()); + int dy = 20; + g.drawString(text, x, y + dy); + + tx = g2d.getDeviceConfiguration().getDefaultTransform(); + text = String.format(MSG, + "Device Config", + tx.getScaleX(), + tx.getScaleY()); + g.drawString(text, x, y + 2 * dy); + } + + private void drawBackingStoreImage(Graphics g) { + Graphics2D g2d = (Graphics2D) g; + GraphicsConfiguration gc = g2d.getDeviceConfiguration(); + if (vImg == null || + vImg.validate(gc) == VolatileImage.IMAGE_INCOMPATIBLE) { + /* Create a new volatile image */ + vImg = createVolatileImage(PANEL_WIDTH, PANEL_HEIGHT / 3); + } + + Graphics vImgGraphics = vImg.createGraphics(); + vImgGraphics.setColor(Color.WHITE); + vImgGraphics.fillRect(0, 0, PANEL_WIDTH, PANEL_HEIGHT / 3); + drawInfo(vImgGraphics, + PANEL_X, + PANEL_Y, + "Backbuffer", + Color.MAGENTA); + g.drawImage(vImg, 0, PANEL_Y * 2, this); + } + } + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + try { + /* Construct the test interface */ + constructTestUI(); + } catch (Exception ex) { + /* Throw an exception indicating error while creating UI */ + throw new RuntimeException("Test Failed. Error while " + + "creating the test interface."); + } + } + }); + + try { + /* Provide sufficient time for user to act upon the manual test */ + long totalWaitDuration = 0; + do { + Thread.sleep(TEST_MIN_DURATION); + totalWaitDuration += TEST_MIN_DURATION; + } while (!testComplete && totalWaitDuration < TEST_TOTAL_DURATION); + } catch(InterruptedException ite) { + /* No-op. The thread continues execution further */ + } + + SwingUtilities.invokeAndWait(new Runnable() { + @Override + public void run() { + try { + /* Destroy the test interface */ + destructTestUI(); + } catch (Exception ex) { + /* No-op */ + } + } + }); + + /* Check for the test result and throw exception if required */ + if (testResult == false) { + throw new RuntimeException("Test Failed. Incorrect scale values " + + "were seen during the test execution."); + } + } +} \ No newline at end of file diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/image/multiresolution/MultiResolutionIcon/MultiResIconTest.java --- a/jdk/test/java/awt/image/multiresolution/MultiResolutionIcon/MultiResIconTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/awt/image/multiresolution/MultiResolutionIcon/MultiResIconTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -24,9 +24,10 @@ /** * @test * @key headful - * @bug 8149371 + * @bug 8149371 8169043 * @summary multi-res. image: -Dsun.java2d.uiScale does not work for Window * icons (some ambiguity for Window.setIconImages()?) + * @requires (os.family == "windows") * @run main/othervm/manual -Dsun.java2d.uiScale=2 MultiResIconTest */ import java.awt.Color; @@ -58,6 +59,7 @@ private static JDialog f; private static CountDownLatch latch; private static TestFrame frame; + private static boolean testPassed; private static BufferedImage generateImage(int x, Color c) { @@ -70,12 +72,13 @@ return img; } - public MultiResIconTest() { - try { - latch = new CountDownLatch(1); - createUI(); - latch.await(); - } catch (Exception ex) { + public MultiResIconTest() throws Exception { + latch = new CountDownLatch(1); + createUI(); + latch.await(); + + if (!testPassed) { + throw new RuntimeException("User Pressed Failed Button"); } } @@ -89,7 +92,10 @@ resultButtonPanel = new JPanel(layout); GridBagConstraints gbc = new GridBagConstraints(); String instructions - = " INSTRUCTIONS:

    " + = " INSTRUCTIONS:
    " + + "This test is for Windows OS only.
    " + + "Make sure that 'Use Small Icons' setting is not set
    " + + "on Windows Taskbar Properties
    " + "1) Test frame title icon and frame color should be green." + "
    " + "2) Test frame task bar icon should be blue
    " @@ -106,6 +112,7 @@ passButton = new JButton("Pass"); passButton.setActionCommand("Pass"); passButton.addActionListener((ActionEvent e) -> { + testPassed = true; latch.countDown(); f.dispose(); frame.dispose(); @@ -115,6 +122,7 @@ failButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { + testPassed = false; latch.countDown(); f.dispose(); frame.dispose(); @@ -140,6 +148,7 @@ f.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { + testPassed = false; latch.countDown(); f.dispose(); frame.dispose(); @@ -191,7 +200,7 @@ } } - public static void main(String[] args) { + public static void main(String[] args) throws Exception { new MultiResIconTest(); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/image/opaque_input.png Binary file jdk/test/java/awt/image/opaque_input.png has changed diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/print/PrinterJob/Margins.java --- a/jdk/test/java/awt/print/PrinterJob/Margins.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/awt/print/PrinterJob/Margins.java Wed Jul 05 22:30:52 2017 +0200 @@ -23,12 +23,12 @@ /** * @test - * @bug 6543815 6601097 + * @bug 6543815 6601097 8160888 * @summary Image should be sent to printer, no exceptions thrown. * The 3 printouts should have a rectangle which is the minimum * possible margins ie, the margins should be hardware margins * and not java default 1 inch margins. - * @run main/manual Margins + * @run main Margins */ import java.awt.print.PrinterJob; @@ -39,16 +39,36 @@ import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Color; +import java.awt.Robot; +import java.awt.event.KeyEvent; public class Margins implements Printable { - public static void main(String args[]) { + public static void main(String args[]) throws Exception { + Robot robot = new Robot(); + Thread t = new Thread (() -> { + robot.waitForIdle(); + robot.delay(5000); + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + robot.waitForIdle(); + robot.delay(5000); + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + robot.waitForIdle(); + robot.delay(5000); + robot.keyPress(KeyEvent.VK_ENTER); + robot.keyRelease(KeyEvent.VK_ENTER); + }); + PrinterJob job = PrinterJob.getPrinterJob(); PageFormat pageFormat = job.defaultPage(); Paper paper = pageFormat.getPaper(); double wid = paper.getWidth(); double hgt = paper.getHeight(); paper.setImageableArea(0, -10, wid, hgt); + t.start(); + pageFormat = job.pageDialog(pageFormat); pageFormat.setPaper(paper); job.setPrintable(new Margins(), pageFormat); @@ -57,7 +77,7 @@ } catch (PrinterException e) { } - paper.setImageableArea(0, 0, wid, hgt+72); + paper.setImageableArea(0, 0, wid, hgt + 72); pageFormat = job.pageDialog(pageFormat); pageFormat.setPaper(paper); @@ -100,12 +120,13 @@ Paper paper = pf.getPaper(); - double wid = paper.getWidth(); - double hgt = paper.getHeight(); - - /* If imageable width/height is -ve, then print was done with 1" margin - * ie ix=72 iy=72 iw=451 ih=697 and wid=595 - * but with fix, we get print with hardware margin ie + int wid = (int)paper.getWidth(); + int hgt = (int)paper.getHeight(); + System.out.println("wid="+wid+" hgt="+hgt); + /* + * If imageable width/height is -ve, then print was done with 1" margin + * e.g. ix=72 iy=72 iw=451 ih=697 and paper wid=595 + * but with fix, we get print with hardware margin e.g. * ix=12, iy=12, iw=571, ih=817 */ if ((wid - iw > 72) || (hgt - ih > 72)) { @@ -115,6 +136,12 @@ throw new RuntimeException("Printable width or height " + "exceeds paper width or height."); } + // runtime checking to see if the margins/printable area + // correspond to the entire size of the paper, for now, make it pass + // as for linux, the hwmargin is not taken into account - bug6574279 + if (ix == 0 && iy == 0 && (ix+iw == wid) && (iy+ih == hgt)) { + return PAGE_EXISTS; + } Graphics2D g2d = (Graphics2D)g; g2d.translate(ix, iy); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/awt/print/PrinterJob/TexturePaintPrintingTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +/* + * @test + * @bug 8040635 + * @summary Verifies if TexturePaint is printed in osx + * @run main/manual TexturePaintPrintingTest + */ +import java.awt.BorderLayout; +import java.awt.Color; +import java.awt.Component; +import java.awt.Container; +import java.awt.Dimension; +import java.awt.FlowLayout; +import java.awt.Graphics; +import java.awt.Graphics2D; +import java.awt.TexturePaint; +import java.awt.event.ActionEvent; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.awt.geom.Rectangle2D; +import java.awt.image.BufferedImage; +import java.awt.print.PageFormat; +import java.awt.print.Printable; +import static java.awt.print.Printable.NO_SUCH_PAGE; +import java.awt.print.PrinterException; +import java.awt.print.PrinterJob; +import javax.swing.AbstractAction; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JTextArea; +import javax.swing.SwingUtilities; +import javax.swing.WindowConstants; + +public class TexturePaintPrintingTest extends Component implements Printable { + private static void printTexture() { + f = new JFrame("Texture Printing Test"); + f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + final TexturePaintPrintingTest gpt = new TexturePaintPrintingTest(); + Container c = f.getContentPane(); + c.add(BorderLayout.CENTER, gpt); + + final JButton print = new JButton("Print"); + print.addActionListener(new AbstractAction() { + @Override + public void actionPerformed(ActionEvent e) { + PrinterJob job = PrinterJob.getPrinterJob(); + job.setPrintable(gpt); + final boolean doPrint = job.printDialog(); + if (doPrint) { + try { + job.print(); + } catch (PrinterException ex) { + throw new RuntimeException(ex); + } + } + } + }); + c.add(print, BorderLayout.SOUTH); + + f.pack(); + f.setVisible(true); + } + + public Dimension getPreferredSize() { + return new Dimension(500,500); + } + + public void paint(Graphics g) { + doPaint((Graphics2D)g); + } + + public int print( Graphics graphics, PageFormat format, int index ) { + Graphics2D g2d = (Graphics2D)graphics; + g2d.translate(format.getImageableX(), format.getImageableY()); + doPaint(g2d); + return index == 0 ? PAGE_EXISTS : NO_SUCH_PAGE; + } + + static final float DIM = 100; + public void doPaint(Graphics2D g2d) { + BufferedImage patternImage = new BufferedImage(2,2,BufferedImage.TYPE_INT_ARGB); + Graphics gImage = patternImage.getGraphics(); + gImage.setColor(Color.WHITE); + gImage.drawLine(0,1,1,0); + gImage.setColor(Color.BLACK); + gImage.drawLine(0,0,1,1); + gImage.dispose(); + + Rectangle2D.Double shape = new Rectangle2D.Double(0,0,DIM*6/5, DIM*8/5); + g2d.setPaint(new TexturePaint(patternImage, new Rectangle2D.Double(0,0, + DIM*6/50, DIM*8/50))); + g2d.fill(shape); + g2d.setPaint(Color.BLACK); + g2d.draw(shape); + } + + public static synchronized void pass() { + testPassed = true; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + public static synchronized void fail() { + testPassed = false; + testGeneratedInterrupt = true; + mainThread.interrupt(); + } + + private static Thread mainThread; + private static boolean testPassed; + private static boolean testGeneratedInterrupt; + private static JFrame f = null; + + public static void main(String[] args) { + SwingUtilities.invokeLater(new Runnable() { + @Override + public void run() { + //createUI(); + doTest(TexturePaintPrintingTest::printTexture); + } + }); + mainThread = Thread.currentThread(); + try { + Thread.sleep(120000); + } catch (InterruptedException e) { + if (!testPassed && testGeneratedInterrupt) { + throw new RuntimeException("TexturePaint did not print"); + } + } + if (!testGeneratedInterrupt) { + throw new RuntimeException("user has not executed the test"); + } + } + + private static void doTest(Runnable action) { + String description + = " A TexturePaint graphics will be shown on console.\n" + + " The same graphics is sent to printer.\n" + + " Please verify if TexturePaint shading is printed.\n" + + " If none is printed, press FAIL else press PASS"; + + final JDialog dialog = new JDialog(); + dialog.setTitle("printSelectionTest"); + JTextArea textArea = new JTextArea(description); + textArea.setEditable(false); + final JButton testButton = new JButton("Start Test"); + final JButton passButton = new JButton("PASS"); + passButton.setEnabled(false); + passButton.addActionListener((e) -> { + f.dispose(); + dialog.dispose(); + pass(); + }); + final JButton failButton = new JButton("FAIL"); + failButton.setEnabled(false); + failButton.addActionListener((e) -> { + f.dispose(); + dialog.dispose(); + fail(); + }); + testButton.addActionListener((e) -> { + testButton.setEnabled(false); + action.run(); + passButton.setEnabled(true); + failButton.setEnabled(true); + }); + JPanel mainPanel = new JPanel(new BorderLayout()); + mainPanel.add(textArea, BorderLayout.CENTER); + JPanel buttonPanel = new JPanel(new FlowLayout()); + buttonPanel.add(testButton); + buttonPanel.add(passButton); + buttonPanel.add(failButton); + mainPanel.add(buttonPanel, BorderLayout.SOUTH); + dialog.add(mainPanel); + + dialog.pack(); + dialog.setVisible(true); + dialog.addWindowListener(new WindowAdapter() { + @Override + public void windowClosing(WindowEvent e) { + System.out.println("main dialog closing"); + testGeneratedInterrupt = false; + mainThread.interrupt(); + } + }); + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/lang/ClassLoader/GetResourceNullArg.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/lang/ClassLoader/GetResourceNullArg.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,96 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.IOException; +import java.net.MalformedURLException; +import java.net.URL; +import java.net.URLClassLoader; +import java.nio.file.Paths; +import java.util.Enumeration; +import java.util.stream.Stream; +import org.testng.annotations.*; + +/* + * @test + * @bug 8136831 + * @summary Test null argument to ClassLoader.getResourceXXXX() + * @run testng GetResourceNullArg + */ + +public class GetResourceNullArg { + private static class MyClassLoader extends ClassLoader { + public MyClassLoader() { + super(null); + } + @Override + public Class findClass(String name) throws ClassNotFoundException { + throw new ClassNotFoundException("Why are you using this?"); + } + } + + @DataProvider + public static ClassLoader[][] provider() { + try { + return new ClassLoader[][] { + { ClassLoader.getSystemClassLoader() }, + { new MyClassLoader() }, + { new URLClassLoader(new URL[]{ Paths.get(".").toUri().toURL() }, + ClassLoader.getSystemClassLoader()) } + }; + } catch (MalformedURLException e) { throw new RuntimeException(e); } + } + + @Test(expectedExceptions = NullPointerException.class) + public void classGetResource() { + this.getClass().getResource(null); + } + + @Test(expectedExceptions = NullPointerException.class) + public void classGetResourceAsStream() { + this.getClass().getResourceAsStream(null); + } + + @Test(dataProvider = "provider", + expectedExceptions = NullPointerException.class) + public void loaderGetResource(ClassLoader cl) { + cl.getResource(null); + } + + @Test(dataProvider = "provider", + expectedExceptions = NullPointerException.class) + public static void loaderGetResources(ClassLoader cl) throws IOException { + Enumeration retVal = cl.getResources(null); + } + + @Test(dataProvider = "provider", + expectedExceptions = NullPointerException.class) + public static void loaderResources(ClassLoader cl) throws IOException { + Stream retVal = cl.resources(null); + } + + @Test(dataProvider = "provider", + expectedExceptions = NullPointerException.class) + public void loaderGetResourceAsStream(ClassLoader cl) { + cl.getResourceAsStream(null); + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/lang/ClassLoader/IsParallelCapable.java --- a/jdk/test/java/lang/ClassLoader/IsParallelCapable.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/lang/ClassLoader/IsParallelCapable.java Wed Jul 05 22:30:52 2017 +0200 @@ -23,8 +23,8 @@ /* * @test - * @bug 8165793 - * @summary Test ClassLoader.isParallelCapable() method + * @bug 8165793 8169435 + * @summary Test ClassLoader.isRegisteredAsParallelCapable() method * @run main IsParallelCapable */ @@ -85,7 +85,7 @@ } public static void main(String[] args) throws Exception { - if (!ClassLoader.getSystemClassLoader().isParallelCapable()) { + if (!ClassLoader.getSystemClassLoader().isRegisteredAsParallelCapable()) { throw new RuntimeException("System classloader not parallel capable!?"); } @@ -100,10 +100,10 @@ private static void testClassLoaderClass(Class klazz) { try { TestCL cl = (TestCL)klazz.newInstance(); - if (cl.expectCapable() != cl.isParallelCapable()) { + if (cl.expectCapable() != cl.isRegisteredAsParallelCapable()) { throw new RuntimeException(klazz + " expectCapable: " + - cl.expectCapable() + ", isParallelCapable: " + - cl.isParallelCapable()); + cl.expectCapable() + ", isRegisteredAsParallelCapable: " + + cl.isRegisteredAsParallelCapable()); } else { System.out.println(klazz + " passed"); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8169909 + * @library src /lib/testlibrary + * @build test/* + * @run shell AppendToClassPathModuleTest.sh + * @run main AppendToClassPathModuleTest + */ + +import java.util.Map; +import static jdk.testlibrary.ProcessTools.*; + +/** + * Launch a modular test with no class path and no CLASSPATH set. + * The java agent appends to the "hidden" directory to the class path + * at runtime. + */ +public class AppendToClassPathModuleTest { + public static void main(String... args) throws Throwable { + String modulepath = System.getProperty("test.module.path"); + ProcessBuilder pb = + createJavaProcessBuilder("-javaagent:Agent.jar", + "--module-path", modulepath, + "-m", "test/jdk.test.Main"); + + // remove CLASSPATH environment variable + Map env = pb.environment(); + String value = env.remove("CLASSPATH"); + + int exitCode = executeCommand(pb).getExitValue(); + if (exitCode != 0) { + throw new RuntimeException("Test failed: " + exitCode); + } + } + +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.sh --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/lang/instrument/modules/AppendToClassPathModuleTest.sh Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,67 @@ +#!/bin/sh + +# +# Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. +# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. +# +# This code is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License version 2 only, as +# published by the Free Software Foundation. +# +# This code is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +# version 2 for more details (a copy is included in the LICENSE file that +# accompanied this code). +# +# You should have received a copy of the GNU General Public License version +# 2 along with this work; if not, write to the Free Software Foundation, +# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. +# +# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA +# or visit www.oracle.com if you need additional information or have any +# questions. +# + +if [ "${TESTSRC}" = "" ] +then + echo "TESTSRC not set. Test cannot execute. Failed." + exit 1 +fi +echo "TESTSRC=${TESTSRC}" + +if [ "${TESTJAVA}" = "" ] +then + echo "TESTJAVA not set. Test cannot execute. Failed." + exit 1 +fi +echo "TESTJAVA=${TESTJAVA}" + +if [ "${COMPILEJAVA}" = "" ] +then + COMPILEJAVA="${TESTJAVA}" +fi +echo "COMPILEJAVA=${COMPILEJAVA}" + +if [ "${TESTCLASSES}" = "" ] +then + echo "TESTCLASSES not set. Test cannot execute. Failed." + exit 1 +fi + +echo "TESTCLASSES=${TESTCLASSES}" + +mkdir -p hidden +${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \ + -d hidden ${TESTSRC}/../ExampleForClassPath.java + +mkdir -p classes +${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \ + -d classes ${TESTSRC}/../InstrumentationHandoff.java + +echo "Manifest-Version: 1.0" > Agent.mf +echo "Class-Path: hidden/" >> Agent.mf +echo "Premain-Class: InstrumentationHandoff" >> Agent.mf + +${TESTJAVA}/bin/jar ${TESTTOOLVMOPTS} cvfm Agent.jar \ + Agent.mf -C classes InstrumentationHandoff.class diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/lang/instrument/modules/src/test/jdk/test/Main.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/lang/instrument/modules/src/test/jdk/test/Main.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +package jdk.test; + +/** + * Launched by AppendToClassPathModuleTest. + */ +public class Main { + public static void main(String... args) throws Exception { + // "java.class.path" system property is expected to be empty. + String value = System.getProperty("java.class.path"); + if (!value.isEmpty()) { + throw new RuntimeException("Non-empty java.class.path=" + value); + } + + // load the "hidden" class that should be loaded by the system loader + Class c = Class.forName("ExampleForClassPath"); + if (c.getClassLoader() != ClassLoader.getSystemClassLoader()) { + throw new RuntimeException(c + " loaderd by " + c.getClassLoader()); + } + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/lang/instrument/modules/src/test/module-info.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/lang/instrument/modules/src/test/module-info.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +module test { +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/net/Authenticator/GetAuthenticatorTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/net/Authenticator/GetAuthenticatorTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.lang.ref.Reference; +import java.net.Authenticator; +import java.net.NetPermission; +import java.net.PasswordAuthentication; +import java.security.AccessControlException; + +/** + * @test + * @bug 8169068 + * @summary Basic test for Authenticator.getDefault() + * @run main/othervm GetAuthenticatorTest + */ +public class GetAuthenticatorTest { + + static final class MyAuthenticator extends Authenticator { + + MyAuthenticator () { + super (); + } + + @Override + public PasswordAuthentication getPasswordAuthentication () { + System.out.println ("Auth called"); + return (new PasswordAuthentication ("user", + "passwordNotCheckedAnyway".toCharArray())); + } + + } + + public static void main (String args[]) throws Exception { + Authenticator defaultAuth = Authenticator.getDefault(); + if (defaultAuth != null) { + throw new RuntimeException("Unexpected authenticator: null expected"); + } + MyAuthenticator auth = new MyAuthenticator(); + Authenticator.setDefault(auth); + defaultAuth = Authenticator.getDefault(); + if (defaultAuth != auth) { + throw new RuntimeException("Unexpected authenticator: auth expected"); + } + System.setSecurityManager(new SecurityManager()); + try { + defaultAuth = Authenticator.getDefault(); + throw new RuntimeException("Expected security exception not raised"); + } catch (AccessControlException s) { + System.out.println("Got expected exception: " + s); + if (!s.getPermission().equals(new NetPermission("requestPasswordAuthentication"))) { + throw new RuntimeException("Unexpected permission check: " + s.getPermission()); + } + } + System.out.println("Test passed with default authenticator " + + defaultAuth); + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java --- a/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/nio/channels/AsynchronousSocketChannel/Basic.java Wed Jul 05 22:30:52 2017 +0200 @@ -219,7 +219,8 @@ throw new RuntimeException("ExecutionException expected"); } catch (ExecutionException x) { if (!(x.getCause() instanceof ClosedChannelException)) - throw new RuntimeException("Cause of ClosedChannelException expected"); + throw new RuntimeException("Cause of ClosedChannelException expected", + x.getCause()); } final AtomicReference connectException = new AtomicReference<>(); ch.connect(server.address(), (Void)null, new CompletionHandler() { @@ -233,7 +234,8 @@ Thread.sleep(100); } if (!(connectException.get() instanceof ClosedChannelException)) - throw new RuntimeException("ClosedChannelException expected"); + throw new RuntimeException("ClosedChannelException expected", + connectException.get()); } // test that failure to connect closes the channel @@ -353,7 +355,8 @@ Thread.sleep(100); } if (!(writeException.get() instanceof AsynchronousCloseException)) - throw new RuntimeException("AsynchronousCloseException expected"); + throw new RuntimeException("AsynchronousCloseException expected", + writeException.get()); } } @@ -460,7 +463,8 @@ throw new RuntimeException("ExecutionException expected"); } catch (ExecutionException x) { if (!(x.getCause() instanceof ClosedChannelException)) - throw new RuntimeException("Cause of ClosedChannelException expected"); + throw new RuntimeException("Cause of ClosedChannelException expected", + x.getCause()); } } } @@ -630,7 +634,8 @@ throw new RuntimeException("ExecutionException expected"); } catch (ExecutionException x) { if (!(x.getCause() instanceof ClosedChannelException)) - throw new RuntimeException("Cause of ClosedChannelException expected"); + throw new RuntimeException("Cause of ClosedChannelException expected", + x.getCause()); } } } @@ -738,7 +743,8 @@ throw new RuntimeException("ClosedChannelException expected"); } catch (ExecutionException x) { if (!(x.getCause() instanceof ClosedChannelException)) - throw new RuntimeException("ClosedChannelException expected"); + throw new RuntimeException("ClosedChannelException expected", + x.getCause()); } } } @@ -776,7 +782,8 @@ Thread.sleep(100); } if (!(readException.get() instanceof InterruptedByTimeoutException)) - throw new RuntimeException("InterruptedByTimeoutException expected"); + throw new RuntimeException("InterruptedByTimeoutException expected", + readException.get()); // after a timeout then further reading should throw unspecified runtime exception boolean exceptionThrown = false; @@ -813,7 +820,8 @@ Thread.sleep(100); } if (!(writeException.get() instanceof InterruptedByTimeoutException)) - throw new RuntimeException("InterruptedByTimeoutException expected"); + throw new RuntimeException("InterruptedByTimeoutException expected", + writeException.get()); // after a timeout then further writing should throw unspecified runtime exception boolean exceptionThrown = false; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/checkActivateRef/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/checkActivateRef/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/checkActivateRef/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -4,4 +4,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.rmi.server.useDynamicProxies=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/checkAnnotations/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/checkAnnotations/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/checkAnnotations/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/checkImplClassLoader/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/checkRegisterInLog/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,7 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/createPrivateActivable/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/createPrivateActivable/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/downloadParameterClass/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/downloadParameterClass/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/elucidateNoSuchMethod/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -4,4 +4,6 @@ permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/forceLogSnapshot/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,7 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/inactiveGroup/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/inactiveGroup/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/inactiveGroup/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/lookupActivationSystem/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/lookupActivationSystem/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/lookupActivationSystem/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -1,4 +1,6 @@ grant { permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/nestedActivate/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/nestedActivate/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/nestedActivate/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/nonExistentActivatable/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/restartCrashedService/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,7 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/restartLatecomer/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/restartLatecomer/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/restartLatecomer/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/restartService/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,7 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/shutdownGracefully/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/shutdownGracefully/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -4,4 +4,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Ddummyname=dummyvalue"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/Activatable/unregisterInactive/rmid.security.policy --- a/jdk/test/java/rmi/activation/Activatable/unregisterInactive/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/Activatable/unregisterInactive/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/ActivateFailedException/activateFails/rmid.security.policy --- a/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/ActivateFailedException/activateFails/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,6 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission java.lang.RuntimePermission "selectorProvider"; permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java --- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/ModifyDescriptor.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -33,8 +33,9 @@ * java.rmi/sun.rmi.server * java.rmi/sun.rmi.transport * java.rmi/sun.rmi.transport.tcp + * java.base/sun.nio.ch * @build TestLibrary RMID ActivationLibrary - * ActivateMe ModifyDescriptor_Stub + * ActivateMe ModifyDescriptor_Stub RMIDSelectorProvider * @run main/othervm/policy=security.policy/timeout=240 ModifyDescriptor */ diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy --- a/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/activation/ActivationSystem/modifyDescriptor/rmid.security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -3,4 +3,9 @@ permission com.sun.rmi.rmid.ExecOptionPermission "-Djava.security.policy=*"; permission com.sun.rmi.rmid.ExecOptionPermission "-Dtest.message=hello"; permission com.sun.rmi.rmid.ExecOptionPermission "-Dtest.message=hello, again"; + permission java.lang.RuntimePermission "selectorProvider"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.nio.ch"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.port", "read"; + permission java.util.PropertyPermission "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", "read"; + permission java.net.SocketPermission "*:1024-", "listen,resolve,connect,accept"; }; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/testlibrary/RMID.java --- a/jdk/test/java/rmi/testlibrary/RMID.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/testlibrary/RMID.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2015, Oracle and/or its affiliates. All rights reserved. + * 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 @@ -25,6 +25,7 @@ import java.rmi.*; import java.rmi.activation.*; import java.rmi.registry.*; +import java.time.LocalTime; import java.util.concurrent.TimeoutException; /** @@ -44,6 +45,15 @@ private static final long STARTTIME_MS = 15_000L; private static final long POLLTIME_MS = 100L; + // when restart rmid, it may take more time than usual because of + // "port in use" by a possible interloper (check JDK-8168975), + // so need to set a longer timeout for restart. + private static long restartTimeout; + // Same reason to inheritedChannel in RMIDSelectorProvider. + // Put it here rather than in RMIDSelectorProvider to adjust + // both timeout values together. + private static long inheritedChannelTimeout; + private static final String SYSTEM_NAME = ActivationSystem.class.getName(); // "java.rmi.activation.ActivationSystem" @@ -73,7 +83,8 @@ } /** make test options and arguments */ - private static String makeOptions(int port, boolean debugExec) { + private static String makeOptions(int port, boolean debugExec, + boolean enableSelectorProvider) { String options = " -Dsun.rmi.server.activation.debugExec=" + debugExec; @@ -98,12 +109,24 @@ // to avoid spurious timeouts on slow machines. options += " -Dsun.rmi.activation.execTimeout=60000"; - if (port == 0) { + // It's important to set handshakeTimeout to small value, for example + // 5 sec (default is 60 sec) to avoid wasting too much time when + // calling lookupSystem(port) in restart(), because + // 1. If use default value of this option, it will take about 2 minutes + // to finish lookupSystem(port) in 2 loops in restart(); + // 2. If set this option as 5 sec then lookupSystem(port) will return + // very quickly. + options += " -Dsun.rmi.transport.tcp.handshakeTimeout=5000"; + + if (port == 0 || enableSelectorProvider) { // Ephemeral port, so have the rmid child process create the // server socket channel and report its port number, over stdin. options += " -classpath " + TestParams.testClassPath; options += " --add-exports=java.base/sun.nio.ch=ALL-UNNAMED"; options += " -Djava.nio.channels.spi.SelectorProvider=RMIDSelectorProvider"; + options += " -Dtest.java.rmi.testlibrary.RMIDSelectorProvider.port=" + port; + options += " -Dtest.java.rmi.testlibrary.RMIDSelectorProvider.timeout=" + + inheritedChannelTimeout; // Disable redirection of System.err to /tmp options += " -Dsun.rmi.server.activation.disableErrRedirect=true"; @@ -112,6 +135,10 @@ return options; } + private static String makeArgs() { + return makeArgs(false, 0); + } + private static String makeArgs(boolean includePortArg, int port) { String propagateManager = null; @@ -183,7 +210,7 @@ boolean debugExec, boolean includePortArg, int port) { - String options = makeOptions(port, debugExec); + String options = makeOptions(port, debugExec, false); String args = makeArgs(includePortArg, port); RMID rmid = new RMID("sun.rmi.server.Activation", options, args, out, err, port); @@ -193,14 +220,14 @@ } public static RMID createRMIDOnEphemeralPort() { - return createRMID(System.out, System.err, true, true, 0); + return createRMID(System.out, System.err, true, false, 0); } public static RMID createRMIDOnEphemeralPort(OutputStream out, OutputStream err, boolean debugExec) { - return createRMID(out, err, debugExec, true, 0); + return createRMID(out, err, debugExec, false, 0); } @@ -213,6 +240,9 @@ { super(classname, options, args, out, err); this.port = port; + long waitTime = (long)(240_000 * TestLibrary.getTimeoutFactor()); + restartTimeout = (long)(waitTime * 0.9); + inheritedChannelTimeout = (long)(waitTime * 0.8); } /** @@ -280,11 +310,11 @@ // if rmid is already running, then the test will fail with // a well recognized exception (port already in use...). - mesg("Starting rmid on port " + port + "."); + mesg("Starting rmid on port " + port + ", at " + LocalTime.now()); int p = super.startAndGetPort(); if (p != -1) port = p; - mesg("Started rmid on port " + port + "."); + mesg("Started rmid on port " + port + ", at " + LocalTime.now()); // int slopFactor = 1; // try { @@ -318,6 +348,7 @@ // The rmid process is alive; check to see whether // it responds to a remote call. + mesg("looking up activation system, at " + LocalTime.now()); if (lookupSystem(port) != null) { /* * We need to set the java.rmi.activation.port value as the @@ -328,10 +359,11 @@ */ System.setProperty("java.rmi.activation.port", Integer.toString(port)); mesg("Started successfully after " + - (System.currentTimeMillis() - startTime) + "ms."); + (System.currentTimeMillis() - startTime) + "ms, at " + LocalTime.now()); return; } + mesg("after fail to looking up activation system, at " + LocalTime.now()); if (System.currentTimeMillis() > deadline) { TestLibrary.bomb("Failed to start rmid, giving up after " + (System.currentTimeMillis() - startTime) + "ms.", null); @@ -347,9 +379,10 @@ */ public void restart() throws IOException { destroy(); - options = makeOptions(port, true); - args = makeArgs(true, port); - start(); + options = makeOptions(port, true, true); + args = makeArgs(); + + start(restartTimeout); } /** diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/testlibrary/RMIDSelectorProvider.java --- a/jdk/test/java/rmi/testlibrary/RMIDSelectorProvider.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/testlibrary/RMIDSelectorProvider.java Wed Jul 05 22:30:52 2017 +0200 @@ -22,6 +22,7 @@ */ import java.io.*; +import java.net.BindException; import java.net.InetSocketAddress; import java.net.ProtocolFamily; import java.nio.channels.Channel; @@ -31,6 +32,7 @@ import java.nio.channels.SocketChannel; import java.nio.channels.spi.AbstractSelector; import java.nio.channels.spi.SelectorProvider; +import java.time.LocalTime; import static java.net.StandardSocketOptions.SO_REUSEADDR; import static java.net.StandardSocketOptions.SO_REUSEPORT; @@ -98,7 +100,37 @@ channel.setOption(SO_REUSEPORT, true); } - channel.bind(new InetSocketAddress(0)); + // when it comes here, these properties should have been set with + // a valid value, but assign a default value anyway. + long timeout = Long.getLong( + "test.java.rmi.testlibrary.RMIDSelectorProvider.timeout", + 200_000); + long deadline = System.currentTimeMillis() + timeout; + int port = Integer.getInteger( + "test.java.rmi.testlibrary.RMIDSelectorProvider.port", 0); + while (true) { + try { + channel.bind(new InetSocketAddress(port)); + break; + } catch (BindException ex) { + System.out.format("RMIDSelectorProvider: " + + "failed to bind to port %d due to \"%s\", at %s%n", + port, ex.getMessage(), LocalTime.now()); + } + if (System.currentTimeMillis() > deadline) { + System.out.format("RMIDSelectorProvider: " + + "fail to bind to port %d after trying for " + + "%d seconds, exiting rmid process, at %s%n", + port, timeout/1000, LocalTime.now()); + channel.close(); + // can not start rmid on specific port, + // there is no need to continue run rmid. + System.exit(1); + } + try { + Thread.sleep(1000); + } catch(InterruptedException ignore) { } + } System.out.println(RMID.EPHEMERAL_MSG + channel.socket().getLocalPort()); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java --- a/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/rmi/transport/reuseDefaultPort/ReuseDefaultPort.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -53,7 +53,7 @@ public class ReuseDefaultPort implements Remote { - private static final int PORT = TestLibrary.getUnusedRandomPort(); + private static int rmiPort = 0; private ReuseDefaultPort() { } @@ -64,7 +64,7 @@ Remote stub = UnicastRemoteObject.exportObject(impl, 0); System.err.println("- exported object: " + stub); try { - Registry registry = LocateRegistry.createRegistry(PORT); + Registry registry = LocateRegistry.createRegistry(rmiPort); System.err.println("- exported registry: " + registry); System.err.println("TEST PASSED"); } finally { @@ -77,13 +77,15 @@ RMISocketFactory.getDefaultSocketFactory(); SF() { } public Socket createSocket(String host, int port) throws IOException { + System.err.format("in SF::createSocket: %s, %d%n", host, port); return defaultFactory.createSocket(host, port); } public ServerSocket createServerSocket(int port) throws IOException { - if (port == 0) { - port = PORT; - } - return defaultFactory.createServerSocket(port); + System.err.format("in SF::createServerSocket: %d%n", port); + ServerSocket server = defaultFactory.createServerSocket(port); + rmiPort = server.getLocalPort(); + System.err.println("rmiPort: " + rmiPort); + return server; } } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/security/ProtectionDomain/NullGetActions.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/security/ProtectionDomain/NullGetActions.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @bug 8043252 + * @summary Debug of access control is obfuscated - NullPointerException in + * ProtectionDomain + * @run main/othervm/java.security.policy=NullGetActions.policy NullGetActions + */ + +import java.net.*; +import java.security.*; + +public class NullGetActions { + + public static void main(String[] args) throws Exception { + Permissions permset = new Permissions(); + permset.add(new EvilPermission("java.let.me.do.stuff")); + + Policy.getPolicy(); + ProtectionDomain protDom = new ProtectionDomain( + new CodeSource(new URL("http://bar"), + (java.security.cert.Certificate[])null), permset, + null, null); + + System.out.println("Protection Domain:\n" + protDom); + } + + public static class EvilPermission extends Permission { + public EvilPermission(String name) { + super(name); + } + + @Override + public String getActions() { + return null; + } + + @Override + public boolean equals(Object obj) { + return (obj == this); + } + + @Override + public int hashCode() { + return 42; + } + + @Override + public boolean implies(Permission permission) { + return false; + } + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/security/ProtectionDomain/NullGetActions.policy --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/security/ProtectionDomain/NullGetActions.policy Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,3 @@ +grant { + permission java.security.SecurityPermission "getPolicy"; +}; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/security/SecureRandom/NoSync.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/security/SecureRandom/NoSync.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,101 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.security.Provider; +import java.security.SecureRandom; +import java.security.Security; +import java.util.Date; +import java.util.concurrent.atomic.AtomicBoolean; + +/* + * @test + * @bug 7004967 + * @run main/othervm NoSync + * @summary SecureRandom should be more explicit about threading + */ +public class NoSync { + public static void main(String[] args) throws Exception { + for (Provider p : Security.getProviders()) { + for (Provider.Service s : p.getServices()) { + if (s.getType().equals("SecureRandom") && + !s.getAlgorithm().contains("Block")) { + test(SecureRandom.getInstance(s.getAlgorithm(), p)); + } + } + } + Security.setProperty("securerandom.drbg.config", "HMAC_DRBG"); + test(SecureRandom.getInstance("DRBG")); + Security.setProperty("securerandom.drbg.config", "CTR_DRBG"); + test(SecureRandom.getInstance("DRBG")); + } + + static void test(SecureRandom sr) throws Exception { + test(sr, 20, 3000); + // All out-of-box impl should have the ThreadSafe attribute + String attr = sr.getProvider().getProperty("SecureRandom." + + sr.getAlgorithm() + " ThreadSafe"); + if (!"true".equals(attr)) { + throw new Exception("Not ThreadSafe: " + attr); + } + } + + public static void test(SecureRandom sr, int tnum, int rnum) + throws Exception { + + System.out.println(sr); + System.out.println(sr.getAlgorithm() + " " + sr.getProvider().getName()); + + System.out.println(new Date()); + boolean reseed = sr.getParameters() != null; + Thread[] threads = new Thread[tnum]; + AtomicBoolean failed = new AtomicBoolean(false); + Thread.UncaughtExceptionHandler h = (t, e) -> { + failed.set(true); + e.printStackTrace(); + }; + for (int i = 0; i < threads.length; i++) { + threads[i] = new Thread() { + @Override + public void run() { + for (int j = 0; j < rnum; j++) { + sr.nextBytes(new byte[j%100+100]); + sr.setSeed((long)j); + if (reseed) { + sr.reseed(); + } + } + } + }; + threads[i].setUncaughtExceptionHandler(h); + threads[i].start(); + } + for (int i = 0; i < threads.length; i++) { + threads[i].join(); + } + System.out.println(new Date()); + System.out.println(); + if (failed.get()) { + throw new RuntimeException("Failed"); + } + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/security/SecureRandom/ThreadSafe.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/java/security/SecureRandom/ThreadSafe.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.security.Provider; +import java.security.SecureRandom; +import java.security.SecureRandomSpi; +import java.util.Map; + +/* + * @test + * @bug 7004967 + * @summary SecureRandom should be more explicit about threading + */ +public class ThreadSafe { + public static void main(String[] args) throws Exception { + Provider p = new P(); + NoSync.test(SecureRandom.getInstance("S1", p), 5, 5); + try { + NoSync.test(SecureRandom.getInstance("S2", p), 5, 5); + throw new Exception("Failed"); + } catch (RuntimeException re) { + // Good + } + NoSync.test(SecureRandom.getInstance("S3", p), 5, 5); + try { + NoSync.test(SecureRandom.getInstance("S4", p), 5, 5); + throw new Exception("Failed"); + } catch (RuntimeException re) { + // Good + } + } + + public static class P extends Provider { + public P() { + + super("P", 1.0d, "Haha"); + + // Good. No attribute. + put("SecureRandom.S1", S.class.getName()); + + // Bad. Boasting ThreadSafe but isn't + put("SecureRandom.S2", S.class.getName()); + put("SecureRandom.S2 ThreadSafe", "true"); + + // Good. No attribute. + putService(new Service(this, "SecureRandom", "S3", + S.class.getName(), null, null)); + + // Bad. Boasting ThreadSafe but isn't + putService(new Service(this, "SecureRandom", "S4", + S.class.getName(), null, Map.of("ThreadSafe", "true"))); + } + } + + // This implementation is not itself thread safe. + public static class S extends SecureRandomSpi { + @java.lang.Override + protected void engineSetSeed(byte[] seed) { + return; + } + + private volatile boolean inCall = false; + @Override + protected void engineNextBytes(byte[] bytes) { + if (inCall) { + throw new RuntimeException("IN CALL"); + } + inCall = true; + try { + Thread.sleep(100); + } catch (Exception e) { + // OK + } + inCall = false; + } + + @Override + protected byte[] engineGenerateSeed(int numBytes) { + return new byte[numBytes]; + } + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/text/testlib/IntlTest.java --- a/jdk/test/java/text/testlib/IntlTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/text/testlib/IntlTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -89,6 +89,9 @@ case "-nothrow": nothrow = true; break; + case "-exitcode": + exitCode = true; + break; default: Method m = testMethods.get(arg); if (m == null) { @@ -138,7 +141,12 @@ } } if (nothrow) { - System.exit(errorCount); + if (exitCode) { + System.exit(errorCount); + } + if (errorCount > 0) { + throw new IllegalArgumentException("encountered " + errorCount + " errors"); + } } } @@ -243,7 +251,7 @@ */ void usage() { System.out.println(getClass().getName() + - ": [-verbose] [-nothrow] [-prompt] [test names]"); + ": [-verbose] [-nothrow] [-exitcode] [-prompt] [test names]"); System.out.println(" Available test names:"); for (String methodName : testMethods.keySet()) { @@ -254,7 +262,7 @@ private boolean prompt; private boolean nothrow; protected boolean verbose; - + private boolean exitCode; private PrintWriter log; private int indentLevel; private boolean needLineFeed; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java --- a/jdk/test/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/time/tck/java/time/format/TCKDateTimeFormatterBuilder.java Wed Jul 05 22:30:52 2017 +0200 @@ -594,7 +594,7 @@ @Test(dataProvider = "formatGenericTimeZonePatterns") public void test_appendZoneText_formatGenericTimeZonePatterns(String pattern, String input, String expected) { ZonedDateTime zdt = ZonedDateTime.of(LocalDateTime.now(), ZoneId.of(input)); - DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern); + DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern, Locale.US); assertEquals(zdt.format(df), expected); } @@ -641,7 +641,7 @@ @Test(dataProvider = "formatNonGenericTimeZonePatterns_1") public void test_appendZoneText_parseNonGenricTimeZonePatterns_1(String pattern, LocalDateTime ldt, String expected) { ZoneId zId = ZoneId.of("America/Los_Angeles"); - DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(); + DateTimeFormatter df = new DateTimeFormatterBuilder().appendPattern(pattern).toFormatter(Locale.US); ZonedDateTime zdt = ZonedDateTime.of(ldt, zId); String actual = df.format(zdt); assertEquals(actual, expected); @@ -668,7 +668,7 @@ @Test(dataProvider = "formatNonGenericTimeZonePatterns_2") public void test_appendZoneText_parseNonGenricTimeZonePatterns_2(String pattern, LocalDateTime ldt, String expected) { ZoneId zId = ZoneId.of("America/Los_Angeles"); - DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern).withZone(zId); + DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern, Locale.US).withZone(zId); String actual = df.format(ldt); assertEquals(actual, expected); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/time/tck/java/time/zone/TCKZoneRulesProvider.java --- a/jdk/test/java/time/tck/java/time/zone/TCKZoneRulesProvider.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/time/tck/java/time/zone/TCKZoneRulesProvider.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -91,10 +91,11 @@ public void test_getAvailableGroupIds() { Set zoneIds = ZoneRulesProvider.getAvailableZoneIds(); assertEquals(zoneIds.contains("Europe/London"), true); - zoneIds.clear(); - assertEquals(zoneIds.size(), 0); - Set zoneIds2 = ZoneRulesProvider.getAvailableZoneIds(); - assertEquals(zoneIds2.contains("Europe/London"), true); + } + + @Test(expectedExceptions=UnsupportedOperationException.class) + public void test_getAvailableGroupIds_modifyZoneId() { + ZoneRulesProvider.getAvailableZoneIds().clear(); } //----------------------------------------------------------------------- diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/BitSet/BitSetStreamTest.java --- a/jdk/test/java/util/BitSet/BitSetStreamTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/BitSet/BitSetStreamTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -60,25 +60,6 @@ public int getAsInt() { int s = n1; n1 = n2; n2 = s + n1; return s; } } - private static final Object[][] testcases = new Object[][] { - { "none", IntStream.empty() }, - { "index 0", IntStream.of(0) }, - { "index 255", IntStream.of(255) }, - { "every bit", IntStream.range(0, 255) }, - { "step 2", IntStream.range(0, 255).map(f -> f * 2) }, - { "step 3", IntStream.range(0, 255).map(f -> f * 3) }, - { "step 5", IntStream.range(0, 255).map(f -> f * 5) }, - { "step 7", IntStream.range(0, 255).map(f -> f * 7) }, - { "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000) }, - { "max int", IntStream.of(Integer.MAX_VALUE) }, - { "25 fibs", IntStream.generate(new Fibs()).limit(25) } - }; - - @DataProvider(name = "cases") - public static Object[][] produceCases() { - return testcases; - } - @Test public void testFibs() { Fibs f = new Fibs(); @@ -93,22 +74,46 @@ assertEquals(987, Fibs.fibs(16)); } + + @DataProvider(name = "cases") + public static Object[][] produceCases() { + return new Object[][] { + { "none", IntStream.empty() }, + { "index 0", IntStream.of(0) }, + { "index 255", IntStream.of(255) }, + { "index 0 and 255", IntStream.of(0, 255) }, + { "index Integer.MAX_VALUE", IntStream.of(Integer.MAX_VALUE) }, + { "index Integer.MAX_VALUE - 1", IntStream.of(Integer.MAX_VALUE - 1) }, + { "index 0 and Integer.MAX_VALUE", IntStream.of(0, Integer.MAX_VALUE) }, + { "every bit", IntStream.range(0, 255) }, + { "step 2", IntStream.range(0, 255).map(f -> f * 2) }, + { "step 3", IntStream.range(0, 255).map(f -> f * 3) }, + { "step 5", IntStream.range(0, 255).map(f -> f * 5) }, + { "step 7", IntStream.range(0, 255).map(f -> f * 7) }, + { "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000) }, + { "25 fibs", IntStream.generate(new Fibs()).limit(25) } + }; + } + @Test(dataProvider = "cases") public void testBitsetStream(String name, IntStream data) { - BitSet bs = new BitSet(); - long setBits = data.distinct() - .peek(i -> bs.set(i)) - .count(); + BitSet bs = data.collect(BitSet::new, BitSet::set, BitSet::or); + + assertEquals(bs.cardinality(), bs.stream().count()); - assertEquals(bs.cardinality(), setBits); - assertEquals(bs.cardinality(), bs.stream().reduce(0, (s, i) -> s+1)); + int[] indexHolder = new int[] { -1 }; + bs.stream().forEach(i -> { + int ei = indexHolder[0]; + indexHolder[0] = bs.nextSetBit(ei + 1); + assertEquals(i, indexHolder[0]); + }); PrimitiveIterator.OfInt it = bs.stream().iterator(); - for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i+1)) { + for (int i = bs.nextSetBit(0); i >= 0; i = bs.nextSetBit(i + 1)) { assertTrue(it.hasNext()); assertEquals(it.nextInt(), i); if (i == Integer.MAX_VALUE) - break; // or (i+1) would overflow + break; // or (i + 1) would overflow } assertFalse(it.hasNext()); } @@ -123,16 +128,20 @@ for (int seed : seeds) { final Random random = new Random(seed); random.nextBytes(bytes); - final BitSet bitSet = BitSet.valueOf(bytes); - final int cardinality = bitSet.cardinality(); - final IntStream stream = bitSet.stream(); - final int[] array = stream.toArray(); - assertEquals(array.length, cardinality); - int nextSetBit = -1; - for (int i=0; i < cardinality; i++) { - nextSetBit = bitSet.nextSetBit(nextSetBit + 1); - assertEquals(array[i], nextSetBit); - } + + BitSet bitSet = BitSet.valueOf(bytes); + testBitSetContents(bitSet, bitSet.stream().toArray()); + testBitSetContents(bitSet, bitSet.stream().parallel().toArray()); + } + } + + void testBitSetContents(BitSet bitSet, int[] array) { + int cardinality = bitSet.cardinality(); + assertEquals(array.length, cardinality); + int nextSetBit = -1; + for (int i = 0; i < cardinality; i++) { + nextSetBit = bitSet.nextSetBit(nextSetBit + 1); + assertEquals(array[i], nextSetBit); } } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/Bug4766302.java --- a/jdk/test/java/util/Calendar/Bug4766302.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/Bug4766302.java Wed Jul 05 22:30:52 2017 +0200 @@ -29,9 +29,11 @@ import java.util.GregorianCalendar; +@SuppressWarnings("serial") public class Bug4766302 { static class MyCalendar extends GregorianCalendar { + boolean isTimeStillSet() { return isTimeSet; } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/Bug4958050.java --- a/jdk/test/java/util/Calendar/Bug4958050.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/Bug4958050.java Wed Jul 05 22:30:52 2017 +0200 @@ -29,9 +29,11 @@ import java.util.Locale; import java.util.TimeZone; + import static java.util.Calendar.*; public class Bug4958050 { + static int errorCount = 0; public static void main(String[] args) { @@ -41,87 +43,87 @@ System.out.println("Time zone = " + cal.getTimeZone().getID()); // Test the week fields - int[] weekFields = { WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH }; + int[] weekFields = {WEEK_OF_YEAR, WEEK_OF_MONTH, DAY_OF_WEEK_IN_MONTH}; for (int i = 0; i < weekFields.length; i++) { int field = weekFields[i]; // add() cal.clear(); - cal.set(1919, DECEMBER, 14-7, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 7, 23, 50, 00); cal.add(weekFields[i], +1); if (!cal.checkDate(1919, DECEMBER, 14)) { - error("1919/12/07: add("+cal.getFieldName(weekFields[i])+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1919/12/07: add(" + Koyomi.getFieldName(weekFields[i]) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-7); + cal.set(1930, JUNE, 21 - 7); cal.add(weekFields[i], +1); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { - error("1930/6/14: add("+cal.getFieldName(weekFields[i])+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1930/6/14: add(" + Koyomi.getFieldName(weekFields[i]) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } // roll() cal.clear(); - cal.set(1919, DECEMBER, 14-7, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 7, 23, 50, 00); cal.roll(weekFields[i], +1); if (!cal.checkDate(1919, DECEMBER, 14)) { - error("1919/12/07: roll("+cal.getFieldName(weekFields[i])+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1919/12/07: roll(" + Koyomi.getFieldName(weekFields[i]) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-7); + cal.set(1930, JUNE, 21 - 7); cal.roll(weekFields[i], +1); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { - error("1930/6/14: roll("+cal.getFieldName(weekFields[i])+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1930/6/14: roll(" + Koyomi.getFieldName(weekFields[i]) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } } // Test the day fields - int[] dayFields = { DAY_OF_MONTH, DAY_OF_YEAR, DAY_OF_WEEK }; + int[] dayFields = {DAY_OF_MONTH, DAY_OF_YEAR, DAY_OF_WEEK}; for (int i = 0; i < dayFields.length; i++) { int field = dayFields[i]; // add() cal.clear(); - cal.set(1919, DECEMBER, 14-1, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 1, 23, 50, 00); cal.add(field, +1); if (!cal.checkDate(1919, DECEMBER, 14)) { - error("1919/12/13: add("+cal.getFieldName(field)+", +1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1919/12/13: add(" + Koyomi.getFieldName(field) + ", +1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1919, DECEMBER, 14, 00, 00, 00); cal.add(field, -1); if (!cal.checkDate(1919, DECEMBER, 13)) { - error("1919/12/14: add("+cal.getFieldName(field)+", -1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1919/12/14: add(" + Koyomi.getFieldName(field) + ", -1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-1); + cal.set(1930, JUNE, 21 - 1); cal.add(field, +1); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { - error("1930/6/20: add("+cal.getFieldName(field)+", +1)\n" - + cal.getMessage() + cal.toDateTimeString()); + error("1930/6/20: add(" + Koyomi.getFieldName(field) + ", +1)\n" + + cal.getMessage() + cal.toDateTimeString()); } cal.clear(); cal.set(1930, JUNE, 21, 01, 00, 00); cal.add(field, -1); if (!cal.checkDateTime(1930, JUNE, 20, 01, 00, 00, 000)) { - error("1930/6/21: add("+cal.getFieldName(field)+", -1)\n" - + cal.getMessage()+" " + cal.toDateTimeString()); + error("1930/6/21: add(" + Koyomi.getFieldName(field) + ", -1)\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } // roll() cal.clear(); - cal.set(1930, JUNE, 21-1); + cal.set(1930, JUNE, 21 - 1); int amount = +1; if (field == DAY_OF_WEEK) { amount += 700; } cal.roll(field, amount); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { - error("1930/6/20: roll("+cal.getFieldName(field)+", +"+amount+")\n" - + cal.getMessage() + " " + cal.toDateTimeString()); + error("1930/6/20: roll(" + Koyomi.getFieldName(field) + ", +" + amount + ")\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1930, JUNE, 21, 01, 00, 00); @@ -131,93 +133,93 @@ } cal.roll(field, amount); if (!cal.checkDateTime(1930, JUNE, 20, 01, 00, 00, 000)) { - error("1930/6/21: roll("+cal.getFieldName(field)+", "+amount+")\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + error("1930/6/21: roll(" + Koyomi.getFieldName(field) + ", " + amount + ")\n" + + cal.getMessage() + " " + cal.toDateTimeString()); } } // Test the AM_PM field // add() cal.clear(); - cal.set(1919, DECEMBER, 14-1, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 1, 23, 50, 00); cal.add(AM_PM, +1); if (!cal.checkDate(1919, DECEMBER, 14) - || !cal.checkFieldValue(AM_PM, AM)) { + || !cal.checkFieldValue(AM_PM, AM)) { error("1919/12/13: add(AM_PM, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-1, 12, 00, 00); + cal.set(1930, JUNE, 21 - 1, 12, 00, 00); cal.add(AM_PM, +1); if (!cal.checkDate(1930, JUNE, 21) - || !cal.checkFieldValue(AM_PM, AM)) { + || !cal.checkFieldValue(AM_PM, AM)) { error("1930/6/20: add(AM_PM, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-2, 12, 00, 00); + cal.set(1930, JUNE, 21 - 2, 12, 00, 00); cal.add(AM_PM, +3); if (!cal.checkDate(1930, JUNE, 21) - || !cal.checkFieldValue(AM_PM, AM)) { + || !cal.checkFieldValue(AM_PM, AM)) { error("1930/6/10: add(AM_PM, +3)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1919, DECEMBER, 14, 11, 50, 00); cal.add(AM_PM, -1); - if (!cal.checkDateTime(1919, DECEMBER, 14-1, 23, 50, 00, 000) - || !cal.checkFieldValue(AM_PM, PM)) { + if (!cal.checkDateTime(1919, DECEMBER, 14 - 1, 23, 50, 00, 000) + || !cal.checkFieldValue(AM_PM, PM)) { error("1919/12/14 11:50:00: add(AM_PM, -1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1930, JUNE, 21, 01, 00, 00); cal.add(AM_PM, -1); - if (!cal.checkDateTime(1930, JUNE, 21-1, 01+12, 00, 00, 000) - || !cal.checkFieldValue(AM_PM, PM)) { + if (!cal.checkDateTime(1930, JUNE, 21 - 1, 01 + 12, 00, 00, 000) + || !cal.checkFieldValue(AM_PM, PM)) { error("1930/6/20: add(AM_PM, -1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); cal.set(1930, JUNE, 21, 01, 00, 00); cal.add(AM_PM, -3); - if (!cal.checkDateTime(1930, JUNE, 21-2, 01+12, 00, 00, 000) - || !cal.checkFieldValue(AM_PM, PM)) { + if (!cal.checkDateTime(1930, JUNE, 21 - 2, 01 + 12, 00, 00, 000) + || !cal.checkFieldValue(AM_PM, PM)) { error("1930/6/10: add(AM_PM, -3)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } // roll() (should NOT change the date) cal.clear(); - cal.set(1919, DECEMBER, 14-1, 23, 50, 00); + cal.set(1919, DECEMBER, 14 - 1, 23, 50, 00); cal.roll(AM_PM, +1); - if (!cal.checkDateTime(1919, DECEMBER, 14-1, 23-12, 50, 00, 000) - || !cal.checkFieldValue(AM_PM, AM)) { + if (!cal.checkDateTime(1919, DECEMBER, 14 - 1, 23 - 12, 50, 00, 000) + || !cal.checkFieldValue(AM_PM, AM)) { error("1919/12/13: roll(AM_PM, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-1, 12, 00, 00); + cal.set(1930, JUNE, 21 - 1, 12, 00, 00); cal.roll(AM_PM, +1); - if (!cal.checkDateTime(1930, JUNE, 21-1, 12-12, 00, 00, 000) - || !cal.checkFieldValue(AM_PM, AM)) { + if (!cal.checkDateTime(1930, JUNE, 21 - 1, 12 - 12, 00, 00, 000) + || !cal.checkFieldValue(AM_PM, AM)) { error("1930/6/20: roll(AM_PM, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } cal.clear(); - cal.set(1930, JUNE, 21-2, 12, 00, 00); + cal.set(1930, JUNE, 21 - 2, 12, 00, 00); cal.roll(AM_PM, +3); - if (!cal.checkDateTime(1930, JUNE, 21-2, 12-12, 00, 00, 000) - || !cal.checkFieldValue(AM_PM, AM)) { + if (!cal.checkDateTime(1930, JUNE, 21 - 2, 12 - 12, 00, 00, 000) + || !cal.checkFieldValue(AM_PM, AM)) { error("1930/6/10: roll(AM_PM, +3)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } // Test the HOUR_OF_DAY field @@ -227,7 +229,7 @@ cal.add(HOUR_OF_DAY, +1); if (!cal.checkDateTime(1930, JUNE, 21, 01, 00, 00, 000)) { error("1930/6/20 23:00:00: add(HOUR_OF_DAY, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } // roll() (should NOT change the date) @@ -236,7 +238,7 @@ cal.roll(HOUR_OF_DAY, +1); if (!cal.checkDateTime(1930, JUNE, 20, 00, 00, 00, 000)) { error("1930/6/20 23:00:00: roll(HOUR_OF_DAY, +1)\n" - + cal.getMessage()+" "+cal.toDateTimeString()); + + cal.getMessage() + " " + cal.toDateTimeString()); } checkErrors(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/CalendarRegression.java --- a/jdk/test/java/util/Calendar/CalendarRegression.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/CalendarRegression.java Wed Jul 05 22:30:52 2017 +0200 @@ -34,11 +34,24 @@ * @library /java/text/testlib * @run main CalendarRegression */ +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.text.DateFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; +import java.util.SimpleTimeZone; +import java.util.TimeZone; -import java.lang.reflect.*; -import java.io.*; -import java.util.*; -import java.text.*; +import static java.util.Calendar.*; public class CalendarRegression extends IntlTest { @@ -47,99 +60,101 @@ } /* - Synopsis: java.sql.Timestamp constructor works wrong on Windows 95 + Synopsis: java.sql.Timestamp constructor works wrong on Windows 95 - ==== Here is the test ==== - public static void main (String args[]) { - java.sql.Timestamp t= new java.sql.Timestamp(0,15,5,5,8,13,123456700); - logln("expected=1901-04-05 05:08:13.1234567"); - logln(" result="+t); - } + ==== Here is the test ==== + public static void main (String args[]) { + java.sql.Timestamp t= new java.sql.Timestamp(0,15,5,5,8,13,123456700); + logln("expected=1901-04-05 05:08:13.1234567"); + logln(" result="+t); + } - ==== Here is the output of the test on Solaris or NT ==== - expected=1901-04-05 05:08:13.1234567 - result=1901-04-05 05:08:13.1234567 + ==== Here is the output of the test on Solaris or NT ==== + expected=1901-04-05 05:08:13.1234567 + result=1901-04-05 05:08:13.1234567 - ==== Here is the output of the test on Windows95 ==== - expected=1901-04-05 05:08:13.1234567 - result=1901-04-05 06:08:13.1234567 - */ - + ==== Here is the output of the test on Windows95 ==== + expected=1901-04-05 05:08:13.1234567 + result=1901-04-05 06:08:13.1234567 + */ public void Test4031502() { // This bug actually occurs on Windows NT as well, and doesn't // require the host zone to be set; it can be set in Java. String[] ids = TimeZone.getAvailableIDs(); boolean bad = false; - for (int i=0; i max) + } + if (dow < min || dow > max) { errln("FAIL: Day of week " + dow + " out of range"); - if (dow != Calendar.SUNDAY) + } + if (dow != SUNDAY) { errln("FAIL: Day of week should be SUNDAY Got " + dow); + } } + @SuppressWarnings("deprecation") public void Test4071385() { Calendar cal = Calendar.getInstance(); - cal.setTime(new Date(98, Calendar.JUNE, 24)); - cal.set(Calendar.MONTH, Calendar.NOVEMBER); // change a field + cal.setTime(new Date(98, JUNE, 24)); + cal.set(MONTH, NOVEMBER); // change a field logln(cal.getTime().toString()); - if (!cal.getTime().equals(new Date(98, Calendar.NOVEMBER, 24))) + if (!cal.getTime().equals(new Date(98, NOVEMBER, 24))) { errln("Fail"); + } } public void Test4073929() { GregorianCalendar foo1 = new GregorianCalendar(1997, 8, 27); - foo1.add(Calendar.DAY_OF_MONTH, +1); - int testyear = foo1.get(Calendar.YEAR); - int testmonth = foo1.get(Calendar.MONTH); - int testday = foo1.get(Calendar.DAY_OF_MONTH); - if (testyear != 1997 || - testmonth != 8 || - testday != 28) + foo1.add(DAY_OF_MONTH, +1); + int testyear = foo1.get(YEAR); + int testmonth = foo1.get(MONTH); + int testday = foo1.get(DAY_OF_MONTH); + if (testyear != 1997 + || testmonth != 8 + || testday != 28) { errln("Fail: Calendar not initialized"); + } } public void Test4083167() { @@ -322,27 +346,26 @@ Date firstDate = new Date(); Calendar cal = new GregorianCalendar(); cal.setTime(firstDate); - long firstMillisInDay = cal.get(Calendar.HOUR_OF_DAY) * 3600000L + - cal.get(Calendar.MINUTE) * 60000L + - cal.get(Calendar.SECOND) * 1000L + - cal.get(Calendar.MILLISECOND); + long firstMillisInDay = cal.get(HOUR_OF_DAY) * 3600000L + + cal.get(MINUTE) * 60000L + + cal.get(SECOND) * 1000L + + cal.get(MILLISECOND); logln("Current time: " + firstDate.toString()); - for (int validity=0; validity<30; validity++) { - Date lastDate = new Date(firstDate.getTime() + - (long)validity*1000*24*60*60); + for (int validity = 0; validity < 30; validity++) { + Date lastDate = new Date(firstDate.getTime() + + (long) validity * 1000 * 24 * 60 * 60); cal.setTime(lastDate); - long millisInDay = cal.get(Calendar.HOUR_OF_DAY) * 3600000L + - cal.get(Calendar.MINUTE) * 60000L + - cal.get(Calendar.SECOND) * 1000L + - cal.get(Calendar.MILLISECOND); + long millisInDay = cal.get(HOUR_OF_DAY) * 3600000L + + cal.get(MINUTE) * 60000L + + cal.get(SECOND) * 1000L + + cal.get(MILLISECOND); if (firstMillisInDay != millisInDay) { errln("Day has shifted " + lastDate); } } - } - finally { + } finally { TimeZone.setDefault(saveZone); } } @@ -359,61 +382,60 @@ TimeZone.setDefault(TimeZone.getTimeZone("Europe/London")); date = new SimpleDateFormat("zzzz"); - Calendar cal=Calendar.getInstance(); - cal.set(1997,Calendar.SEPTEMBER,30); - Date now=cal.getTime(); + Calendar cal = Calendar.getInstance(); + cal.set(1997, SEPTEMBER, 30); + Date now = cal.getTime(); String formattedDate = date.format(now); if (!formattedDate.equals(summerTime)) { errln("Wrong display name \"" + formattedDate - + "\" for <" + now + ">"); + + "\" for <" + now + ">"); } - int weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); + int weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 40) { errln("Wrong week-of-year " + weekOfYear - + " for <" + now + ">"); + + " for <" + now + ">"); } - cal.set(1996,Calendar.DECEMBER,31); - now=cal.getTime(); + cal.set(1996, DECEMBER, 31); + now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { errln("Wrong display name \"" + formattedDate - + "\" for <" + now + ">"); + + "\" for <" + now + ">"); } - weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); + weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 1) { errln("Wrong week-of-year " + weekOfYear - + " for <" + now + ">"); + + " for <" + now + ">"); } - cal.set(1997,Calendar.JANUARY,1); - now=cal.getTime(); + cal.set(1997, JANUARY, 1); + now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { errln("Wrong display name \"" + formattedDate - + "\" for <" + now + ">"); + + "\" for <" + now + ">"); } - weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); + weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 1) { errln("Wrong week-of-year " + weekOfYear - + " for <" + now + ">"); + + " for <" + now + ">"); } - cal.set(1997,Calendar.JANUARY,8); - now=cal.getTime(); + cal.set(1997, JANUARY, 8); + now = cal.getTime(); formattedDate = date.format(now); if (!formattedDate.equals(standardTime)) { errln("Wrong display name \"" + formattedDate - + "\" for <" + now + ">"); + + "\" for <" + now + ">"); } - weekOfYear = cal.get(Calendar.WEEK_OF_YEAR); + weekOfYear = cal.get(WEEK_OF_YEAR); if (weekOfYear != 2) { errln("Wrong week-of-year " + weekOfYear - + " for <" + now + ">"); + + " for <" + now + ">"); } - } - finally { + } finally { Locale.setDefault(saveLocale); TimeZone.setDefault(saveZone); } @@ -428,9 +450,9 @@ cal1.set( Calendar.MINUTE, 20 ); cal1.set( Calendar.SECOND, 40 ); */ - logln( " Cal1 = " + cal1.getTime().getTime() ); - logln( " Cal1 time in ms = " + cal1.get(Calendar.MILLISECOND) ); - for( int k = 0; k < 100 ; k++ ); + logln(" Cal1 = " + cal1.getTime().getTime()); + logln(" Cal1 time in ms = " + cal1.get(MILLISECOND)); + for (int k = 0; k < 100; k++); GregorianCalendar cal2 = new GregorianCalendar(1997, 10, 11, 10, 20, 40); /*cal2.set( Calendar.YEAR, 1997 ); @@ -440,17 +462,19 @@ cal2.set( Calendar.MINUTE, 20 ); cal2.set( Calendar.SECOND, 40 ); */ - logln( " Cal2 = " + cal2.getTime().getTime() ); - logln( " Cal2 time in ms = " + cal2.get(Calendar.MILLISECOND) ); - if( !cal1.equals( cal2 ) ) + logln(" Cal2 = " + cal2.getTime().getTime()); + logln(" Cal2 time in ms = " + cal2.get(MILLISECOND)); + if (!cal1.equals(cal2)) { errln("Fail: Milliseconds randomized"); + } } public void Test4095407() { - GregorianCalendar a = new GregorianCalendar(1997,Calendar.NOVEMBER, 13); - int dow = a.get(Calendar.DAY_OF_WEEK); - if (dow != Calendar.THURSDAY) + GregorianCalendar a = new GregorianCalendar(1997, NOVEMBER, 13); + int dow = a.get(DAY_OF_WEEK); + if (dow != THURSDAY) { errln("Fail: Want THURSDAY Got " + dow); + } } public void Test4096231() { @@ -461,72 +485,74 @@ Calendar cal1 = new GregorianCalendar(PST); cal1.setTime(new Date(880698639000L)); int p; - logln("PST 1 is: " + (p=cal1.get(cal1.HOUR_OF_DAY))); + logln("PST 1 is: " + (p = cal1.get(HOUR_OF_DAY))); cal1.setTimeZone(GMT); // Issue 1: Changing the timezone doesn't change the // represented time. - int h1,h2; - logln("GMT 1 is: " + (h1=cal1.get(cal1.HOUR_OF_DAY))); + int h1, h2; + logln("GMT 1 is: " + (h1 = cal1.get(HOUR_OF_DAY))); cal1.setTime(new Date(880698639000L)); - logln("GMT 2 is: " + (h2=cal1.get(cal1.HOUR_OF_DAY))); + logln("GMT 2 is: " + (h2 = cal1.get(HOUR_OF_DAY))); // Note: This test had a bug in it. It wanted h1!=h2, when // what was meant was h1!=p. Fixed this concurrent with fix // to 4177484. - if (p == h1 || h1 != h2) + if (p == h1 || h1 != h2) { errln("Fail: Hour same in different zones"); + } Calendar cal2 = new GregorianCalendar(GMT); Calendar cal3 = new GregorianCalendar(PST); - cal2.set(Calendar.MILLISECOND, 0); - cal3.set(Calendar.MILLISECOND, 0); + cal2.set(MILLISECOND, 0); + cal3.set(MILLISECOND, 0); - cal2.set(cal1.get(cal1.YEAR), - cal1.get(cal1.MONTH), - cal1.get(cal1.DAY_OF_MONTH), - cal1.get(cal1.HOUR_OF_DAY), - cal1.get(cal1.MINUTE), - cal1.get(cal1.SECOND)); + cal2.set(cal1.get(YEAR), + cal1.get(MONTH), + cal1.get(DAY_OF_MONTH), + cal1.get(HOUR_OF_DAY), + cal1.get(MINUTE), + cal1.get(SECOND)); - long t1,t2,t3,t4; - logln("RGMT 1 is: " + (t1=cal2.getTime().getTime())); + long t1, t2, t3, t4; + logln("RGMT 1 is: " + (t1 = cal2.getTime().getTime())); cal3.set(year, month, day, hr, min, sec); - logln("RPST 1 is: " + (t2=cal3.getTime().getTime())); + logln("RPST 1 is: " + (t2 = cal3.getTime().getTime())); cal3.setTimeZone(GMT); - logln("RGMT 2 is: " + (t3=cal3.getTime().getTime())); - cal3.set(cal1.get(cal1.YEAR), - cal1.get(cal1.MONTH), - cal1.get(cal1.DAY_OF_MONTH), - cal1.get(cal1.HOUR_OF_DAY), - cal1.get(cal1.MINUTE), - cal1.get(cal1.SECOND)); + logln("RGMT 2 is: " + (t3 = cal3.getTime().getTime())); + cal3.set(cal1.get(YEAR), + cal1.get(MONTH), + cal1.get(DAY_OF_MONTH), + cal1.get(HOUR_OF_DAY), + cal1.get(MINUTE), + cal1.get(SECOND)); // Issue 2: Calendar continues to use the timezone in its // constructor for set() conversions, regardless // of calls to setTimeZone() - logln("RGMT 3 is: " + (t4=cal3.getTime().getTime())); - if (t1 == t2 || - t1 != t4 || - t2 != t3) + logln("RGMT 3 is: " + (t4 = cal3.getTime().getTime())); + if (t1 == t2 + || t1 != t4 + || t2 != t3) { errln("Fail: Calendar zone behavior faulty"); + } } public void Test4096539() { - int[] y = {31,28,31,30,31,30,31,31,30,31,30,31}; + int[] y = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + + for (int x = 0; x < 12; x++) { + GregorianCalendar gc = new GregorianCalendar(1997, x, y[x]); + int m1, m2; + log((m1 = gc.get(MONTH) + 1) + "/" + + gc.get(DATE) + "/" + gc.get(YEAR) + + " + 1mo = "); - for (int x=0;x<12;x++) { - GregorianCalendar gc = new - GregorianCalendar(1997,x,y[x]); - int m1,m2; - log((m1=gc.get(Calendar.MONTH)+1)+"/"+ - gc.get(Calendar.DATE)+"/"+gc.get(Calendar.YEAR)+ - " + 1mo = "); - - gc.add(Calendar.MONTH, 1); - logln((m2=gc.get(Calendar.MONTH)+1)+"/"+ - gc.get(Calendar.DATE)+"/"+gc.get(Calendar.YEAR) - ); + gc.add(MONTH, 1); + logln((m2 = gc.get(MONTH) + 1) + "/" + + gc.get(DATE) + "/" + gc.get(YEAR) + ); int m = (m1 % 12) + 1; - if (m2 != m) + if (m2 != m) { errln("Fail: Want " + m + " Got " + m2); + } } } @@ -538,13 +564,14 @@ return; } - GregorianCalendar cal = (GregorianCalendar)Calendar.getInstance(); - cal.set(Calendar.YEAR, 1997); - cal.set(Calendar.DAY_OF_YEAR, 1); + GregorianCalendar cal = (GregorianCalendar) Calendar.getInstance(); + cal.set(YEAR, 1997); + cal.set(DAY_OF_YEAR, 1); Date d = cal.getTime(); // Should be Jan 1 logln(d.toString()); - if (cal.get(Calendar.DAY_OF_YEAR) != 1) + if (cal.get(DAY_OF_YEAR) != 1) { errln("Fail: DAY_OF_YEAR not set"); + } } public void Test4103271() { @@ -555,28 +582,28 @@ } SimpleDateFormat sdf = new SimpleDateFormat(); - int numYears=40, startYear=1997, numDays=15; + int numYears = 40, startYear = 1997, numDays = 15; String output, testDesc; - GregorianCalendar testCal = (GregorianCalendar)Calendar.getInstance(); + GregorianCalendar testCal = (GregorianCalendar) Calendar.getInstance(); testCal.clear(); sdf.setCalendar(testCal); sdf.applyPattern("d MMM yyyy"); boolean fail = false; - for (int firstDay=1; firstDay<=2; firstDay++) { - for (int minDays=1; minDays<=7; minDays++) { + for (int firstDay = 1; firstDay <= 2; firstDay++) { + for (int minDays = 1; minDays <= 7; minDays++) { testCal.setMinimalDaysInFirstWeek(minDays); testCal.setFirstDayOfWeek(firstDay); testDesc = ("Test" + String.valueOf(firstDay) + String.valueOf(minDays)); - logln(testDesc + " => 1st day of week=" + - String.valueOf(firstDay) + - ", minimum days in first week=" + - String.valueOf(minDays)); - for (int j=startYear; j<=startYear+numYears; j++) { - testCal.set(j,11,25); - for(int i=0; i 1st day of week=" + + String.valueOf(firstDay) + + ", minimum days in first week=" + + String.valueOf(minDays)); + for (int j = startYear; j <= startYear + numYears; j++) { + testCal.set(j, 11, 25); + for (int i = 0; i < numDays; i++) { + testCal.add(DATE, 1); String calWOY; - int actWOY = testCal.get(Calendar.WEEK_OF_YEAR); + int actWOY = testCal.get(WEEK_OF_YEAR); if (actWOY < 1 || actWOY > 53) { Date d = testCal.getTime(); calWOY = String.valueOf(actWOY); @@ -592,20 +619,19 @@ int[] DATA = { 3, 52, 52, 52, 52, 52, 52, 52, - 1, 1, 1, 1, 1, 1, 1, - 2, 2, 2, 2, 2, 2, 2, + 1, 1, 1, 1, 1, 1, 1, + 2, 2, 2, 2, 2, 2, 2, 4, 52, 52, 52, 52, 52, 52, 52, - 53, 53, 53, 53, 53, 53, 53, - 1, 1, 1, 1, 1, 1, 1, - }; - testCal.setFirstDayOfWeek(Calendar.SUNDAY); - for (int j=0; j " + testCal.getTime()); + if (ADDROLL[i] == ADD) { + testCal.add(WEEK_OF_YEAR, amount); + } else { + testCal.roll(WEEK_OF_YEAR, amount); + } + log((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + + amount + ")\t " + before + + "\n\t\t => " + testCal.getTime()); if (!after.equals(testCal.getTime())) { logln("\tFAIL\n\t\texp: " + after); fail = true; - } else + } else { logln(" OK"); + } testCal.setTime(after); - if (ADDROLL[i] == ADD) - testCal.add(Calendar.WEEK_OF_YEAR, -amount); - else - testCal.roll(Calendar.WEEK_OF_YEAR, -amount); - log((ADDROLL[i]==ADD ? "add(WOY," : "roll(WOY,") + - (-amount) + ") " + after + - "\n\t\t => " + testCal.getTime()); + if (ADDROLL[i] == ADD) { + testCal.add(WEEK_OF_YEAR, -amount); + } else { + testCal.roll(WEEK_OF_YEAR, -amount); + } + log((ADDROLL[i] == ADD ? "add(WOY," : "roll(WOY,") + + (-amount) + ") " + after + + "\n\t\t => " + testCal.getTime()); if (!before.equals(testCal.getTime())) { logln("\tFAIL\n\t\texp: " + before); fail = true; + } else { + logln("\tOK"); } - else logln("\tOK"); } if (fail) { @@ -719,63 +749,68 @@ public void Test4106136() { Locale saveLocale = Locale.getDefault(); try { - Locale[] locales = { Locale.CHINESE, Locale.CHINA }; - for (int i=0; i maxYear) { - errln("Failed for "+DATES[i].getTime()+" ms: year=" + - year + ", maxYear=" + maxYear); + errln("Failed for " + DATES[i].getTime() + " ms: year=" + + year + ", maxYear=" + maxYear); } } } @@ -1068,28 +1104,29 @@ "SECOND", "MILLISECOND", "ZONE_OFFSET", - "DST_OFFSET" - }; + "DST_OFFSET"}; GregorianCalendar calendar = new GregorianCalendar(); calendar.setLenient(false); - Date date = new Date(1996-1900, Calendar.JANUARY, 3); // Arbitrary date - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { + @SuppressWarnings("deprecation") + Date date = new Date(1996 - 1900, JANUARY, 3); // Arbitrary date + for (int field = 0; field < FIELD_COUNT; field++) { calendar.setTime(date); // Note: In the bug report, getActualMaximum() was called instead // of getMaximum() -- this was an error. The validation code doesn't // use getActualMaximum(), since that's too costly. int max = calendar.getMaximum(field); - int value = max+1; + int value = max + 1; calendar.set(field, value); try { calendar.getTime(); // Force time computation // We expect an exception to be thrown. If we fall through // to the next line, then we have a bug. - errln("Test failed with field " + fieldName[field] + - ", date before: " + date + - ", date after: " + calendar.getTime() + - ", value: " + value + " (max = " + max +")"); - } catch (IllegalArgumentException e) {} + errln("Test failed with field " + fieldName[field] + + ", date before: " + date + + ", date after: " + calendar.getTime() + + ", value: " + value + " (max = " + max + ")"); + } catch (IllegalArgumentException e) { + } } } @@ -1099,19 +1136,19 @@ * CANNOT REPRODUCE THIS BUG */ public void Test4149677() { - TimeZone[] zones = { TimeZone.getTimeZone("GMT"), - TimeZone.getTimeZone("PST"), - TimeZone.getTimeZone("EAT") }; - for (int i=0; i0) logln("---"); + for (int i = 0; i < 5; ++i) { + if (i > 0) { + logln("---"); + } cal.clear(); - cal.set(1998, Calendar.APRIL, 5, i, 0); + cal.set(1998, APRIL, 5, i, 0); d = cal.getTime(); String s0 = d.toString(); logln("0 " + i + ": " + s0); cal.clear(); - cal.set(1998, Calendar.APRIL, 4, i+24, 0); + cal.set(1998, APRIL, 4, i + 24, 0); d = cal.getTime(); String sPlus = d.toString(); logln("+ " + i + ": " + sPlus); cal.clear(); - cal.set(1998, Calendar.APRIL, 6, i-24, 0); + cal.set(1998, APRIL, 6, i - 24, 0); d = cal.getTime(); String sMinus = d.toString(); logln("- " + i + ": " + sMinus); @@ -1164,8 +1203,7 @@ errln("Fail: All three lines must match"); } } - } - finally { + } finally { TimeZone.setDefault(savedTz); } } @@ -1174,14 +1212,14 @@ * Adding 12 months behaves differently from adding 1 year */ public void Test4165343() { - GregorianCalendar calendar = new GregorianCalendar(1996, Calendar.FEBRUARY, 29); + GregorianCalendar calendar = new GregorianCalendar(1996, FEBRUARY, 29); Date start = calendar.getTime(); logln("init date: " + start); - calendar.add(Calendar.MONTH, 12); + calendar.add(MONTH, 12); Date date1 = calendar.getTime(); logln("after adding 12 months: " + date1); calendar.setTime(start); - calendar.add(Calendar.YEAR, 1); + calendar.add(YEAR, 1); Date date2 = calendar.getTime(); logln("after adding one year : " + date2); if (date1.equals(date2)) { @@ -1196,34 +1234,34 @@ */ public void Test4166109() { /* Test month: - * - * March 1998 - * Su Mo Tu We Th Fr Sa - * 1 2 3 4 5 6 7 - * 8 9 10 11 12 13 14 - * 15 16 17 18 19 20 21 - * 22 23 24 25 26 27 28 - * 29 30 31 + * + * March 1998 + * Su Mo Tu We Th Fr Sa + * 1 2 3 4 5 6 7 + * 8 9 10 11 12 13 14 + * 15 16 17 18 19 20 21 + * 22 23 24 25 26 27 28 + * 29 30 31 */ boolean passed = true; - int field = Calendar.WEEK_OF_MONTH; + int field = WEEK_OF_MONTH; GregorianCalendar calendar = new GregorianCalendar(Locale.US); - calendar.set(1998, Calendar.MARCH, 1); + calendar.set(1998, MARCH, 1); calendar.setMinimalDaysInFirstWeek(1); logln("Date: " + calendar.getTime()); - int firstInMonth = calendar.get(Calendar.DAY_OF_MONTH); + int firstInMonth = calendar.get(DAY_OF_MONTH); - for (int firstInWeek = Calendar.SUNDAY; firstInWeek <= Calendar.SATURDAY; firstInWeek++) { + for (int firstInWeek = SUNDAY; firstInWeek <= SATURDAY; firstInWeek++) { calendar.setFirstDayOfWeek(firstInWeek); int returned = calendar.getActualMaximum(field); - int expected = (31 + ((firstInMonth - firstInWeek + 7)% 7) + 6) / 7; + int expected = (31 + ((firstInMonth - firstInWeek + 7) % 7) + 6) / 7; - logln("First day of week = " + firstInWeek + - " getActualMaximum(WEEK_OF_MONTH) = " + returned + - " expected = " + expected + - ((returned == expected) ? " ok" : " FAIL")); + logln("First day of week = " + firstInWeek + + " getActualMaximum(WEEK_OF_MONTH) = " + returned + + " expected = " + expected + + ((returned == expected) ? " ok" : " FAIL")); if (returned != expected) { passed = false; @@ -1242,19 +1280,19 @@ * changed. See 4928615. */ public void Test4167060() { - int field = Calendar.YEAR; + int field = YEAR; DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss zzz yyyy G", - Locale.US); + Locale.US); int[][] dates = { // year, month, day of month - { 100, Calendar.NOVEMBER, 1 }, - { -99 /*100BC*/, Calendar.JANUARY, 1 }, - { 1996, Calendar.FEBRUARY, 29 }}; + {100, NOVEMBER, 1}, + {-99 /*100BC*/, JANUARY, 1}, + {1996, FEBRUARY, 29}}; - String[] id = { "Hybrid", "Gregorian", "Julian" }; + String[] id = {"Hybrid", "Gregorian", "Julian"}; - for (int k=0; k<3; ++k) { + for (int k = 0; k < 3; ++k) { logln("--- " + id[k] + " ---"); for (int j = 0; j < dates.length; ++j) { @@ -1265,7 +1303,7 @@ calendar.setGregorianChange(new Date(Long.MAX_VALUE)); } calendar.set(dates[j][0], dates[j][1], dates[j][2]); - format.setCalendar((Calendar)calendar.clone()); + format.setCalendar((Calendar) calendar.clone()); Date dateBefore = calendar.getTime(); @@ -1273,7 +1311,7 @@ logln("maxYear: " + maxYear + " for " + format.format(calendar.getTime())); logln("date before: " + format.format(dateBefore)); - int years[] = {2000, maxYear-1, maxYear, maxYear+1}; + int[] years = {2000, maxYear - 1, maxYear, maxYear + 1}; for (int i = 0; i < years.length; i++) { boolean valid = years[i] <= maxYear; @@ -1282,8 +1320,8 @@ int newYear = calendar.get(field); calendar.setTime(dateBefore); // restore calendar for next use - logln(" Year " + years[i] + (valid? " ok " : " bad") + - " => " + format.format(dateAfter)); + logln(" Year " + years[i] + (valid ? " ok " : " bad") + + " => " + format.format(dateAfter)); if (valid && newYear != years[i]) { errln(" FAIL: " + newYear + " should be valid; date, month and time shouldn't change"); } else if (!valid && newYear == years[i]) { @@ -1305,18 +1343,16 @@ return; } - int fieldsList[][] = { - { 1997, Calendar.FEBRUARY, 1, 10, 45, 15, 900 }, - { 1999, Calendar.DECEMBER, 22, 23, 59, 59, 999 }, + int[][] fieldsList = { + {1997, FEBRUARY, 1, 10, 45, 15, 900}, + {1999, DECEMBER, 22, 23, 59, 59, 999}, // test case for 4960642 with default cutover - { 1582, Calendar.OCTOBER, 4, 23, 59, 59, 999 }, - }; + {1582, OCTOBER, 4, 23, 59, 59, 999}}; String[] fieldNames = { "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH", "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", "HOUR_OF_DAY", "MINUTE", "SECOND", "MILLISECOND", - "ZONE_OFFSET", "DST_OFFSET" - }; + "ZONE_OFFSET", "DST_OFFSET"}; Locale savedLocale = Locale.getDefault(); Locale.setDefault(Locale.US); @@ -1326,25 +1362,25 @@ GregorianCalendar cal = new GregorianCalendar(); cal.setTime(new Date(0)); - cal.roll(Calendar.HOUR, 0x7F000000); - cal.roll(Calendar.HOUR, -0x7F000000); + cal.roll(HOUR, 0x7F000000); + cal.roll(HOUR, -0x7F000000); if (cal.getTime().getTime() != 0) { - errln("Hour rolling broken. expected 0, got "+cal.getTime().getTime()); + errln("Hour rolling broken. expected 0, got " + cal.getTime().getTime()); } - for (int op=0; op<2; ++op) { - logln("Testing GregorianCalendar " + (op==0 ? "add" : "roll")); + for (int op = 0; op < 2; ++op) { + logln("Testing GregorianCalendar " + (op == 0 ? "add" : "roll")); - for (int field=0; field < Calendar.FIELD_COUNT; ++field) { - if (field != Calendar.ZONE_OFFSET && - field != Calendar.DST_OFFSET) { - for (int j=0; j " + - cal.get(Calendar.YEAR) + - "/" + (cal.get(Calendar.MONTH) + 1) + - "/" + cal.get(Calendar.DATE) + - " " + cal.get(Calendar.HOUR_OF_DAY) + - ":" + cal.get(Calendar.MINUTE) + - ":" + cal.get(Calendar.SECOND) + - "." + cal.get(Calendar.MILLISECOND) + - " d=" + delta); + errln((op == 0 ? "add(" : "roll(") + + fieldNames[field] + ", " + + (i < limit ? "+" : "-") + "1) => " + + cal.get(YEAR) + + "/" + (cal.get(MONTH) + 1) + + "/" + cal.get(DATE) + + " " + cal.get(HOUR_OF_DAY) + + ":" + cal.get(MINUTE) + + ":" + cal.get(SECOND) + + "." + cal.get(MILLISECOND) + + " d=" + delta); } } } } } } - } - finally { + } finally { Locale.setDefault(savedLocale); } } @@ -1425,14 +1460,14 @@ public void Test4174361() { GregorianCalendar calendar = new GregorianCalendar(1996, 1, 29); - calendar.add(Calendar.MONTH, 10); + calendar.add(MONTH, 10); Date date1 = calendar.getTime(); - int d1 = calendar.get(Calendar.DAY_OF_MONTH); + int d1 = calendar.get(DAY_OF_MONTH); calendar = new GregorianCalendar(1996, 1, 29); - calendar.add(Calendar.MONTH, 11); + calendar.add(MONTH, 11); Date date2 = calendar.getTime(); - int d2 = calendar.get(Calendar.DAY_OF_MONTH); + int d2 = calendar.get(DAY_OF_MONTH); if (d1 != d2) { errln("adding months to Feb 29 broken"); @@ -1449,9 +1484,9 @@ Calendar cal = Calendar.getInstance(PST, Locale.US); cal.clear(); cal.set(1999, 3, 21, 15, 5, 0); // Arbitrary - int h1 = cal.get(Calendar.HOUR_OF_DAY); + int h1 = cal.get(HOUR_OF_DAY); cal.setTimeZone(EST); - int h2 = cal.get(Calendar.HOUR_OF_DAY); + int h2 = cal.get(HOUR_OF_DAY); if (h1 == h2) { errln("FAIL: Fields not updated after setTimeZone"); } @@ -1460,7 +1495,7 @@ // getTime() returns zone-independent time in ms. cal.clear(); cal.setTimeZone(PST); - cal.set(Calendar.HOUR_OF_DAY, 10); + cal.set(HOUR_OF_DAY, 10); Date pst10 = cal.getTime(); cal.setTimeZone(EST); Date est10 = cal.getTime(); @@ -1474,28 +1509,27 @@ */ public void Test4197699() { GregorianCalendar cal = new GregorianCalendar(); - cal.setFirstDayOfWeek(Calendar.MONDAY); + cal.setFirstDayOfWeek(MONDAY); cal.setMinimalDaysInFirstWeek(4); DateFormat fmt = new SimpleDateFormat("E dd MMM yyyy 'DOY='D 'WOY='w"); fmt.setCalendar(cal); int[] DATA = { - 2000, Calendar.JANUARY, 1, 52, - 2001, Calendar.DECEMBER, 31, 1, - }; + 2000, JANUARY, 1, 52, + 2001, DECEMBER, 31, 1}; - for (int i=0; i " + actual + - ", want " + DATA[i+1]); + if (!actual.equals(DATA[i + 1])) { + errln("FAIL: Sunday " + DATA[i] + + " of Jan 1997 -> " + actual + + ", want " + DATA[i + 1]); } } } - public void Test4288792() throws Exception - { + public void Test4288792() throws Exception { TimeZone savedTZ = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); GregorianCalendar cal = new GregorianCalendar(); @@ -1631,45 +1664,44 @@ for (int i = 1900; i < 2100; i++) { for (int j1 = 1; j1 <= 7; j1++) { // Loop for MinimalDaysInFirstWeek: 1..7 - for (int j = Calendar.SUNDAY; j <= Calendar.SATURDAY; j++) { + for (int j = SUNDAY; j <= SATURDAY; j++) { // Loop for FirstDayOfWeek: SUNDAY..SATURDAY cal.clear(); cal.setMinimalDaysInFirstWeek(j1); cal.setFirstDayOfWeek(j); - cal.set(Calendar.YEAR, i); - int maxWeek = cal.getActualMaximum(Calendar.WEEK_OF_YEAR); - cal.set(Calendar.WEEK_OF_YEAR, maxWeek); - cal.set(Calendar.DAY_OF_WEEK, j); + cal.set(YEAR, i); + int maxWeek = cal.getActualMaximum(WEEK_OF_YEAR); + cal.set(WEEK_OF_YEAR, maxWeek); + cal.set(DAY_OF_WEEK, j); for (int k = 1; k < 7; k++) { - cal.add(Calendar.DATE, 1); - int WOY = cal.get(Calendar.WEEK_OF_YEAR); + cal.add(DATE, 1); + int WOY = cal.get(WEEK_OF_YEAR); if (WOY != maxWeek) { errln(cal.getTime() + ",got=" + WOY - + ",expected=" + maxWeek - + ",min=" + j1 + ",first=" + j); + + ",expected=" + maxWeek + + ",min=" + j1 + ",first=" + j); } } - cal.add(Calendar.DATE, 1); - int WOY = cal.get(Calendar.WEEK_OF_YEAR); + cal.add(DATE, 1); + int WOY = cal.get(WEEK_OF_YEAR); if (WOY != 1) { errln(cal.getTime() + ",got=" + WOY - + ",expected=1,min=" + j1 + ",first" + j); + + ",expected=1,min=" + j1 + ",first" + j); } } } } - } - finally { + } finally { TimeZone.setDefault(savedTZ); } } public void Test4328747() throws Exception { - Calendar c = (Calendar)Calendar.getInstance(Locale.US); + Calendar c = Calendar.getInstance(Locale.US); c.clear(); - c.set(1966,0,1); // 1 jan 1966 + c.set(1966, 0, 1); // 1 jan 1966 // serialize ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -1679,16 +1711,16 @@ // deserialize ObjectInputStream t = new ObjectInputStream(new ByteArrayInputStream(out.toByteArray())); - Calendar result = (Calendar)t.readObject(); + Calendar result = (Calendar) t.readObject(); // let recalculate fields with the same UTC time result.setTime(result.getTime()); // Bug gives 1965 11 19 - if ((result.get(c.YEAR) != 1966) || (result.get(c.MONTH) != 0) - || (result.get(c.DATE) != 1)) { + if ((result.get(YEAR) != 1966) || (result.get(MONTH) != 0) + || (result.get(DATE) != 1)) { errln("deserialized Calendar returned wrong date field(s): " - + result.get(c.YEAR) + "/" + result.get(c.MONTH) + "/" + result.get(c.DATE) - + ", expected 1966/0/1"); + + result.get(YEAR) + "/" + result.get(MONTH) + "/" + result.get(DATE) + + ", expected 1966/0/1"); } } @@ -1700,13 +1732,13 @@ TimeZone savedTimeZone = TimeZone.getDefault(); try { boolean pass = true; - String[] IDs = new String[] {"Undefined", "PST", "US/Pacific", - "GMT+3:00", "GMT-01:30"}; + String[] IDs = new String[]{"Undefined", "PST", "US/Pacific", + "GMT+3:00", "GMT-01:30"}; for (int i = 0; i < IDs.length; i++) { TimeZone tz = TimeZone.getTimeZone(IDs[i]); TimeZone.setDefault(tz); - Calendar c = (Calendar)Calendar.getInstance(); + Calendar c = Calendar.getInstance(); // serialize ByteArrayOutputStream out = new ByteArrayOutputStream(); @@ -1719,26 +1751,20 @@ if (!c.equals(t.readObject())) { pass = false; - logln("Calendar instance which uses TimeZone <" + - IDs[i] + "> is incorrectly serialized/deserialized."); + logln("Calendar instance which uses TimeZone <" + + IDs[i] + "> is incorrectly serialized/deserialized."); } else { - logln("Calendar instance which uses TimeZone <" + - IDs[i] + "> is correctly serialized/deserialized."); + logln("Calendar instance which uses TimeZone <" + + IDs[i] + "> is correctly serialized/deserialized."); } } if (!pass) { errln("Fail: Calendar serialization/equality bug"); } - } - catch (IOException e) { + } catch (IOException | ClassNotFoundException e) { errln("Fail: " + e); e.printStackTrace(); - } - catch (ClassNotFoundException e) { - errln("Fail: " + e); - e.printStackTrace(); - } - finally { + } finally { TimeZone.setDefault(savedTimeZone); } } @@ -1747,12 +1773,12 @@ * 4546637: Incorrect WEEK_OF_MONTH after changing First Day Of Week */ public void Test4546637() { - GregorianCalendar day = new GregorianCalendar (2001, Calendar.NOVEMBER, 04); + GregorianCalendar day = new GregorianCalendar(2001, NOVEMBER, 04); day.setMinimalDaysInFirstWeek(1); - int wom = day.get(Calendar.WEEK_OF_MONTH); + int wom = day.get(WEEK_OF_MONTH); - day.setFirstDayOfWeek(Calendar.MONDAY); - if (day.get(Calendar.WEEK_OF_MONTH) != 1) { + day.setFirstDayOfWeek(MONDAY); + if (day.get(WEEK_OF_MONTH) != 1) { errln("Fail: 2001/11/4 must be the first week of the month."); } } @@ -1761,14 +1787,14 @@ * 4623997: GregorianCalendar returns bad WEEK_OF_YEAR */ public void Test4623997() { - GregorianCalendar cal = new GregorianCalendar(2000, GregorianCalendar.JANUARY, 1); + GregorianCalendar cal = new GregorianCalendar(2000, JANUARY, 1); - int dow = cal.get(GregorianCalendar.DAY_OF_WEEK); + int dow = cal.get(DAY_OF_WEEK); - cal.setFirstDayOfWeek(GregorianCalendar.MONDAY); + cal.setFirstDayOfWeek(MONDAY); cal.setMinimalDaysInFirstWeek(4); - if (cal.get(GregorianCalendar.WEEK_OF_YEAR) != 52) { + if (cal.get(WEEK_OF_YEAR) != 52) { errln("Fail: 2000/1/1 must be the 52nd week of the year."); } } @@ -1800,9 +1826,9 @@ } t = calendar.getTime(); - calendar.set(Calendar.DAY_OF_MONTH, 33); + calendar.set(DAY_OF_MONTH, 33); t = calendar.getTime(); - calendar.set(Calendar.DAY_OF_MONTH, 0); + calendar.set(DAY_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { errln("DAY_OF_MONTH w/o ZONE_OFFSET: expected: " + expected + ", got: " + s); @@ -1815,10 +1841,10 @@ throw new RuntimeException("Unexpected parse exception", e); } t = calendar.getTime(); - calendar.set(calendar.ZONE_OFFSET, calendar.get(calendar.ZONE_OFFSET)); - calendar.set(Calendar.DAY_OF_MONTH, 33); + calendar.set(ZONE_OFFSET, calendar.get(ZONE_OFFSET)); + calendar.set(DAY_OF_MONTH, 33); t = calendar.getTime(); - calendar.set(Calendar.DAY_OF_MONTH, 0); + calendar.set(DAY_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { errln("DAY_OF_MONTH: expected: " + expected + ", got: " + s); @@ -1834,11 +1860,11 @@ throw new RuntimeException("Unexpected parse exception", e); } t = calendar.getTime(); - calendar.set(calendar.ZONE_OFFSET, calendar.get(calendar.ZONE_OFFSET)); + calendar.set(ZONE_OFFSET, calendar.get(ZONE_OFFSET)); // jump to the next year - calendar.set(Calendar.WEEK_OF_YEAR, 100); + calendar.set(WEEK_OF_YEAR, 100); t = calendar.getTime(); - calendar.set(Calendar.WEEK_OF_YEAR, 0); + calendar.set(WEEK_OF_YEAR, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { errln("WEEK_OF_YEAR: expected: " + expected + ", got: " + s); @@ -1846,11 +1872,11 @@ // change the state back calendar.clear(); calendar.setTime(initialDate); - calendar.set(calendar.ZONE_OFFSET, calendar.get(calendar.ZONE_OFFSET)); + calendar.set(ZONE_OFFSET, calendar.get(ZONE_OFFSET)); // jump to next month - calendar.set(Calendar.WEEK_OF_MONTH, 7); + calendar.set(WEEK_OF_MONTH, 7); t = calendar.getTime(); - calendar.set(Calendar.WEEK_OF_MONTH, 0); + calendar.set(WEEK_OF_MONTH, 0); s = df.format(calendar.getTime()); if (!expected.equals(s)) { errln("WEEK_OF_MONTH: expected: " + expected + ", got: " + s); @@ -1870,10 +1896,10 @@ } t = calendar.getTime(); // time should be 22:59:59. - calendar.set(Calendar.MINUTE, 61); + calendar.set(MINUTE, 61); // time should be 23:01:59. t = calendar.getTime(); - calendar.set(Calendar.MINUTE, -1); + calendar.set(MINUTE, -1); // time should be back to 22:59:59. s = df.format(calendar.getTime()); if (!expected.equals(s)) { @@ -1896,15 +1922,15 @@ Calendar cal = Calendar.getInstance(); cal.setTime(new Date(1029814211523L)); - cal.set(Calendar.YEAR, 2001); + cal.set(YEAR, 2001); Date t = cal.getTime(); - cal.set(Calendar.MONTH, Calendar.JANUARY); + cal.set(MONTH, JANUARY); t = cal.getTime(); - cal.set(Calendar.DAY_OF_MONTH, 8); + cal.set(DAY_OF_MONTH, 8); t = cal.getTime(); - cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); + cal.set(DAY_OF_WEEK, MONDAY); DateFormat df = new SimpleDateFormat("yyyy/MM/dd", Locale.US); String expected = "2001/01/08"; String s = df.format(cal.getTime()); @@ -1923,9 +1949,9 @@ */ public void Test4683492() { Calendar cal = new GregorianCalendar(2002, 3, 29, 10, 0, 0); - cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY); - cal.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1); - cal.set(Calendar.MONTH, 12); + cal.set(DAY_OF_WEEK, FRIDAY); + cal.set(DAY_OF_WEEK_IN_MONTH, -1); + cal.set(MONTH, 12); DateFormat df = new SimpleDateFormat("yyyy/MM/dd", Locale.US); String expected = "2003/01/31"; String s = df.format(cal.getTime()); @@ -1940,31 +1966,31 @@ public void Test4080631() { Calendar cal = Calendar.getInstance(); int h1 = cal.hashCode(); - cal.add(cal.SECOND, +1); + cal.add(SECOND, +1); int h2 = cal.hashCode(); Calendar cal2 = (Calendar) cal.clone(); - cal.add(cal.MILLISECOND, +1); + cal.add(MILLISECOND, +1); int h3 = cal.hashCode(); - logln("hash code: h1="+h1+", h2="+h2+", h3="+h3); + logln("hash code: h1=" + h1 + ", h2=" + h2 + ", h3=" + h3); if (h1 == h2 || h1 == h3 || h2 == h3) { - errln("hash code is poor: hashCode="+h1); + errln("hash code is poor: hashCode=" + h1); } h2 = cal2.hashCode(); - cal.add(cal.MILLISECOND, -1); + cal.add(MILLISECOND, -1); int h4 = cal.hashCode(); - logln("hash code: h2="+h2+", h4="+h4); + logln("hash code: h2=" + h2 + ", h4=" + h4); if (cal.equals(cal2) && h2 != h4) { - errln("broken hash code: h2="+h2+", h4="+h4); + errln("broken hash code: h2=" + h2 + ", h4=" + h4); } int x = cal.getFirstDayOfWeek() + 3; - if (x > cal.SATURDAY) { + if (x > SATURDAY) { x -= 7; } cal.setFirstDayOfWeek(x); int h5 = cal.hashCode(); - logln("hash code: h4="+h4+", h5="+h5); + logln("hash code: h4=" + h4 + ", h5=" + h5); if (h4 == h5) { - errln("has code is poor with first day of week param: hashCode="+h4); + errln("has code is poor with first day of week param: hashCode=" + h4); } } @@ -1991,8 +2017,7 @@ errln("Wrong BCE and/or CE values"); } } - */ - + */ /** * 4167995: GregorianCalendar.setGregorianChange() not to spec */ @@ -2000,42 +2025,42 @@ Koyomi gc = new Koyomi(TimeZone.getTimeZone("GMT")); logln("Hybrid: min date"); gc.setTime(new Date(Long.MIN_VALUE)); - if (!gc.checkDate(292269055, gc.DECEMBER, 2, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.BC)) { + if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { errln(gc.getMessage()); } logln("Hybrid: max date"); gc.setTime(new Date(Long.MAX_VALUE)); - if (!gc.checkDate(292278994, gc.AUGUST, 17, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.AD)) { + if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { errln(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MIN_VALUE)); logln("Gregorian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); - if (!gc.checkDate(292275056, gc.MAY, 16, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.BC)) { + if (!gc.checkDate(292275056, MAY, 16, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { errln(gc.getMessage()); } logln("Gregorian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); - if (!gc.checkDate(292278994, gc.AUGUST, 17, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.AD)) { + if (!gc.checkDate(292278994, AUGUST, 17, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { errln(gc.getMessage()); } gc.setGregorianChange(new Date(Long.MAX_VALUE)); logln("Julian: min date"); gc.setTime(new Date(Long.MIN_VALUE)); - if (!gc.checkDate(292269055, gc.DECEMBER, 2, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.BC)) { + if (!gc.checkDate(292269055, DECEMBER, 2, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.BC)) { errln(gc.getMessage()); } logln("Julian: max date"); gc.setTime(new Date(Long.MAX_VALUE)); - if (!gc.checkDate(292272993, gc.JANUARY, 4, gc.SUNDAY) - || !gc.checkFieldValue(gc.ERA, gc.AD)) { + if (!gc.checkDate(292272993, JANUARY, 4, SUNDAY) + || !gc.checkFieldValue(ERA, GregorianCalendar.AD)) { errln(gc.getMessage()); } } @@ -2046,13 +2071,13 @@ public void Test4340146() { Koyomi cal = new Koyomi(); cal.clear(); - cal.set(2003, cal.OCTOBER, 32); + cal.set(2003, OCTOBER, 32); cal.equals(new Koyomi()); - if (!cal.checkInternalDate(2003, cal.OCTOBER, 32)) { + if (!cal.checkInternalDate(2003, OCTOBER, 32)) { errln(cal.getMessage()); } new Koyomi().equals(cal); - if (!cal.checkInternalDate(2003, cal.OCTOBER, 32)) { + if (!cal.checkInternalDate(2003, OCTOBER, 32)) { errln(cal.getMessage()); } } @@ -2065,10 +2090,10 @@ // throw IllegalArgumentException. Koyomi cal = new Koyomi(TimeZone.getTimeZone("Pacific/Kiritimati")); cal.setLenient(false); - cal.set(2003, cal.OCTOBER, 10); + cal.set(2003, OCTOBER, 10); cal.getTime(); cal.setTimeZone(TimeZone.getTimeZone("Pacific/Tongatapu")); - cal.set(2003, cal.OCTOBER, 10); + cal.set(2003, OCTOBER, 10); cal.getTime(); } @@ -2077,10 +2102,10 @@ */ public void Test4652815() { Koyomi cal = new Koyomi(Locale.US); - testRoll(cal, 2003, cal.SEPTEMBER, 29); - testRoll(cal, 2003, cal.DECEMBER, 24); - testRoll(cal, 1582, cal.DECEMBER, 19); - testRoll(cal, 1582, cal.DECEMBER, 20); + testRoll(cal, 2003, SEPTEMBER, 29); + testRoll(cal, 2003, DECEMBER, 24); + testRoll(cal, 1582, DECEMBER, 19); + testRoll(cal, 1582, DECEMBER, 20); } private void testRoll(Koyomi cal, int year, int month, int dayOfMonth) { @@ -2089,15 +2114,15 @@ cal.getTime(); // normalize fields logln("Roll backwards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { - cal.roll(cal.WEEK_OF_YEAR, -i); - if (!cal.checkFieldValue(cal.YEAR, year)) { + cal.roll(WEEK_OF_YEAR, -i); + if (!cal.checkFieldValue(YEAR, year)) { errln(cal.getMessage()); } } logln("Roll forewards from " + cal.toDateString()); for (int i = 0; i < 1000; i++) { - cal.roll(cal.WEEK_OF_YEAR, +i); - if (!cal.checkFieldValue(cal.YEAR, year)) { + cal.roll(WEEK_OF_YEAR, +i); + if (!cal.checkFieldValue(YEAR, year)) { errln(cal.getMessage()); } } @@ -2110,20 +2135,20 @@ Koyomi cal = new Koyomi(Locale.US); cal.clear(); logln("BCE 9-2-28 (leap year) roll DAY_OF_MONTH++ twice"); - cal.set(cal.ERA, cal.BC); - cal.set(9, cal.FEBRUARY, 28); - if (cal.getActualMaximum(cal.DAY_OF_YEAR) != 366) { + cal.set(ERA, GregorianCalendar.BC); + cal.set(9, FEBRUARY, 28); + if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { errln(" wrong actual max of DAY_OF_YEAR: got " - + cal.getActualMaximum(cal.DAY_OF_YEAR) + " expected " + 366); + + cal.getActualMaximum(DAY_OF_YEAR) + " expected " + 366); } - cal.roll(cal.DAY_OF_MONTH, +1); - if (!cal.checkFieldValue(cal.ERA, cal.BC) - || !cal.checkDate(9, cal.FEBRUARY, 29)) { + cal.roll(DAY_OF_MONTH, +1); + if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) + || !cal.checkDate(9, FEBRUARY, 29)) { errln(cal.getMessage()); } - cal.roll(cal.DAY_OF_MONTH, +1); - if (!cal.checkFieldValue(cal.ERA, cal.BC) - || !cal.checkDate(9, cal.FEBRUARY, 1)) { + cal.roll(DAY_OF_MONTH, +1); + if (!cal.checkFieldValue(ERA, GregorianCalendar.BC) + || !cal.checkDate(9, FEBRUARY, 1)) { errln(cal.getMessage()); } } @@ -2135,11 +2160,11 @@ logln("1999/(Feb+12)/1 should be normalized to 2000/Feb/1 for getActualMaximum"); Koyomi cal = new Koyomi(Locale.US); cal.clear(); - cal.set(1999, cal.FEBRUARY + 12, 1); - if (!cal.checkActualMaximum(cal.DAY_OF_YEAR, 366)) { + cal.set(1999, FEBRUARY + 12, 1); + if (!cal.checkActualMaximum(DAY_OF_YEAR, 366)) { errln(cal.getMessage()); } - if (!cal.checkActualMaximum(cal.DAY_OF_MONTH, 29)) { + if (!cal.checkActualMaximum(DAY_OF_MONTH, 29)) { errln(cal.getMessage()); } } @@ -2150,36 +2175,36 @@ public void Test4936355() { Koyomi cal = new Koyomi(TimeZone.getTimeZone("GMT")); cal.clear(); - cal.set(1970, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.HOUR_OF_DAY, Integer.MAX_VALUE, - (long)Integer.MAX_VALUE * 60 * 60 * 1000); + cal.set(1970, JANUARY, 1); + checkTimeCalculation(cal, HOUR_OF_DAY, Integer.MAX_VALUE, + (long) Integer.MAX_VALUE * 60 * 60 * 1000); cal.clear(); - cal.set(1970, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.HOUR, Integer.MAX_VALUE, - (long)Integer.MAX_VALUE * 60 * 60 * 1000); + cal.set(1970, JANUARY, 1); + checkTimeCalculation(cal, HOUR, Integer.MAX_VALUE, + (long) Integer.MAX_VALUE * 60 * 60 * 1000); cal.clear(); - cal.set(1970, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.MINUTE, Integer.MAX_VALUE, - (long)Integer.MAX_VALUE * 60 * 1000); + cal.set(1970, JANUARY, 1); + checkTimeCalculation(cal, MINUTE, Integer.MAX_VALUE, + (long) Integer.MAX_VALUE * 60 * 1000); cal.clear(); // Make sure to use Gregorian dates (before and after the // set() call) for testing - cal.set(250000, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.HOUR_OF_DAY, Integer.MIN_VALUE, - (long)Integer.MIN_VALUE * 60 * 60 * 1000); + cal.set(250000, JANUARY, 1); + checkTimeCalculation(cal, HOUR_OF_DAY, Integer.MIN_VALUE, + (long) Integer.MIN_VALUE * 60 * 60 * 1000); cal.clear(); - cal.set(250000, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.HOUR, Integer.MIN_VALUE, - (long)Integer.MIN_VALUE * 60 * 60 * 1000); + cal.set(250000, JANUARY, 1); + checkTimeCalculation(cal, HOUR, Integer.MIN_VALUE, + (long) Integer.MIN_VALUE * 60 * 60 * 1000); cal.clear(); - cal.set(250000, cal.JANUARY, 1); - checkTimeCalculation(cal, cal.MINUTE, Integer.MIN_VALUE, - (long)Integer.MIN_VALUE * 60 * 1000); + cal.set(250000, JANUARY, 1); + checkTimeCalculation(cal, MINUTE, Integer.MIN_VALUE, + (long) Integer.MIN_VALUE * 60 * 1000); } private void checkTimeCalculation(Koyomi cal, int field, int value, long expectedDelta) { @@ -2189,7 +2214,7 @@ if ((time + expectedDelta) != time2) { String s = value == Integer.MAX_VALUE ? "Integer.MAX_VALUE" : "Integer.MIN_VALUE"; errln("set(" + Koyomi.getFieldName(field) + ", " + s + ") failed." + " got " + time2 - + ", expected " + (time+expectedDelta)); + + ", expected " + (time + expectedDelta)); } } @@ -2204,8 +2229,8 @@ cal2.clear(); cal2.setLenient(false); - cal1.set(2003, Calendar.OCTOBER, 31); - cal2.set(2003, Calendar.OCTOBER, 31); + cal1.set(2003, OCTOBER, 31); + cal2.set(2003, OCTOBER, 31); try { if (cal1.equals(cal2)) { errln("lenient and non-lenient shouldn't be equal. (2003/10/31)"); @@ -2217,8 +2242,8 @@ errln("equals threw IllegalArugumentException with non-lenient"); } - cal1.set(2003, Calendar.OCTOBER, 32); - cal2.set(2003, Calendar.OCTOBER, 32); + cal1.set(2003, OCTOBER, 32); + cal2.set(2003, OCTOBER, 32); try { if (cal1.equals(cal2)) { errln("lenient and non-lenient shouldn't be equal. (2003/10/32)"); @@ -2246,17 +2271,17 @@ * 4738710: API: Calendar comparison methods should be improved */ public void Test4738710() { - Calendar cal0 = new GregorianCalendar(2003, Calendar.SEPTEMBER, 30); - Comparable cal1 = new GregorianCalendar(2003, Calendar.OCTOBER, 1); - Calendar cal2 = new GregorianCalendar(2003, Calendar.OCTOBER, 2); + Calendar cal0 = new GregorianCalendar(2003, SEPTEMBER, 30); + Comparable cal1 = new GregorianCalendar(2003, OCTOBER, 1); + Calendar cal2 = new GregorianCalendar(2003, OCTOBER, 2); if (!(cal1.compareTo(cal0) > 0)) { errln("!(cal1 > cal0)"); } if (!(cal1.compareTo(cal2) < 0)) { errln("!(cal1 < cal2)"); } - if (cal1.compareTo(new GregorianCalendar(2003, Calendar.OCTOBER, 1)) != 0) { - errln("cal1 != new GregorianCalendar(2003, Calendar.OCTOBER, 1)"); + if (cal1.compareTo(new GregorianCalendar(2003, OCTOBER, 1)) != 0) { + errln("cal1 != new GregorianCalendar(2003, OCTOBER, 1)"); } if (cal0.after(cal2)) { @@ -2266,10 +2291,10 @@ errln("cal2 shouldn't be before cal0"); } - if (cal0.after(new Integer(0))) { + if (cal0.after(0)) { errln("cal0.after() returned true with an Integer."); } - if (cal0.before(new Integer(0))) { + if (cal0.before(0)) { errln("cal0.before() returned true with an Integer."); } if (cal0.after(null)) { @@ -2283,34 +2308,35 @@ /** * 4633646: Setting WEEK_OF_MONTH to 1 results in incorrect date */ + @SuppressWarnings("deprecation") public void Test4633646() { Koyomi cal = new Koyomi(Locale.US); - cal.setTime(new Date(2002-1900, 1-1, 28)); + cal.setTime(new Date(2002 - 1900, 1 - 1, 28)); sub4633646(cal); cal.setLenient(false); - cal.setTime(new Date(2002-1900, 1-1, 28)); + cal.setTime(new Date(2002 - 1900, 1 - 1, 28)); sub4633646(cal); cal = new Koyomi(Locale.US); cal.clear(); - cal.set(2002, cal.JANUARY, 28); + cal.set(2002, JANUARY, 28); sub4633646(cal); cal.clear(); cal.setLenient(false); - cal.set(2002, cal.JANUARY, 28); + cal.set(2002, JANUARY, 28); sub4633646(cal); } void sub4633646(Koyomi cal) { cal.getTime(); - cal.set(cal.WEEK_OF_MONTH, 1); + cal.set(WEEK_OF_MONTH, 1); if (cal.isLenient()) { - if (!cal.checkDate(2001, cal.DECEMBER, 31)) { + if (!cal.checkDate(2001, DECEMBER, 31)) { errln(cal.getMessage()); } - if (!cal.checkFieldValue(cal.WEEK_OF_MONTH, 6)) { + if (!cal.checkFieldValue(WEEK_OF_MONTH, 6)) { errln(cal.getMessage()); } } else { @@ -2329,29 +2355,29 @@ public void Test4846659() { Koyomi cal = new Koyomi(); cal.clear(); - cal.set(2003, cal.OCTOBER, 31, 10, 30, 30); + cal.set(2003, OCTOBER, 31, 10, 30, 30); cal.getTime(); // Test roll() - cal.roll(cal.AM_PM, +1); // should turn to PM - if (!cal.checkFieldValue(cal.HOUR_OF_DAY, 10+12)) { + cal.roll(AM_PM, +1); // should turn to PM + if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { errln("roll: AM_PM didn't change to PM"); } cal.clear(); - cal.set(2003, cal.OCTOBER, 31, 10, 30, 30); + cal.set(2003, OCTOBER, 31, 10, 30, 30); cal.getTime(); // Test set() - cal.set(cal.AM_PM, cal.PM); // should turn to PM - if (!cal.checkFieldValue(cal.HOUR_OF_DAY, 10+12)) { + cal.set(AM_PM, PM); // should turn to PM + if (!cal.checkFieldValue(HOUR_OF_DAY, 10 + 12)) { errln("set: AM_PM didn't change to PM"); } cal.clear(); - cal.set(2003, cal.OCTOBER, 31, 10, 30, 30); + cal.set(2003, OCTOBER, 31, 10, 30, 30); cal.getTime(); - cal.set(cal.AM_PM, cal.PM); - cal.set(cal.HOUR, 9); - if (!cal.checkFieldValue(cal.HOUR_OF_DAY, 9+12)) { + cal.set(AM_PM, PM); + cal.set(HOUR, 9); + if (!cal.checkFieldValue(HOUR_OF_DAY, 9 + 12)) { errln("set: both AM_PM and HOUT didn't change to PM"); } } @@ -2370,15 +2396,15 @@ // 29 30 cal.clear(); // 6/1 to 6/7 should be the 1st week of June. - cal.set(2003, cal.JUNE, 2); + cal.set(2003, JUNE, 2); cal.getTime(); // Let cal calculate time. - cal.setFirstDayOfWeek(cal.MONDAY); + cal.setFirstDayOfWeek(MONDAY); // Now 6/2 to 6/8 should be the 2nd week of June. Sunday of // that week is 6/8. - logln("1: " +cal.get(cal.WEEK_OF_MONTH)+", "+cal.get(cal.DAY_OF_MONTH)); - cal.set(cal.DAY_OF_WEEK, cal.SUNDAY); + logln("1: " + cal.get(WEEK_OF_MONTH) + ", " + cal.get(DAY_OF_MONTH)); + cal.set(DAY_OF_WEEK, SUNDAY); logln("1st Sunday of June 2003 with FirstDayOfWeek=MONDAY"); - if (!cal.checkDate(2003, cal.JUNE, 8)) { + if (!cal.checkDate(2003, JUNE, 8)) { errln(cal.getMessage()); } } @@ -2387,7 +2413,7 @@ * 4973919: Inconsistent GregorianCalendar hashCode before and after serialization */ public void Test4966499() throws Exception { - GregorianCalendar date1 = new GregorianCalendar(2004, Calendar.JANUARY, 7); + GregorianCalendar date1 = new GregorianCalendar(2004, JANUARY, 7); // Serialize date1 ByteArrayOutputStream baos = new ByteArrayOutputStream(); @@ -2399,15 +2425,15 @@ // Deserialize it ByteArrayInputStream bais = new ByteArrayInputStream(buffer); ObjectInputStream ois = new ObjectInputStream(bais); - GregorianCalendar date2 = (GregorianCalendar)ois.readObject(); + GregorianCalendar date2 = (GregorianCalendar) ois.readObject(); if (!date1.equals(date2)) { errln("date1.equals(date2) != true"); } if (date1.hashCode() != date2.hashCode()) { errln("inconsistent hashCode() value (before=0x" - +Integer.toHexString(date1.hashCode())+ - ", after=0x"+Integer.toHexString(date2.hashCode())+")"); + + Integer.toHexString(date1.hashCode()) + + ", after=0x" + Integer.toHexString(date2.hashCode()) + ")"); } } @@ -2468,29 +2494,26 @@ TimeZone savedZone = TimeZone.getDefault(); TimeZone.setDefault(TimeZone.getTimeZone("GMT")); try { - Map data = new HashMap(); - data.put(getGregorianDate(999, Calendar.OCTOBER, 1), Boolean.FALSE); - data.put(getGregorianDate(1000, Calendar.JANUARY, 1), Boolean.FALSE); - data.put(getGregorianDate(1000, Calendar.FEBRUARY, 1), Boolean.FALSE); - data.put(getGregorianDate(1000, Calendar.FEBRUARY, 28), Boolean.FALSE); - data.put(getGregorianDate(1000, Calendar.MARCH, 1), Boolean.TRUE); - data.put(getGregorianDate(1001, Calendar.JANUARY, 1), Boolean.TRUE); - data.put(getGregorianDate(1001, Calendar.JANUARY, 6), Boolean.TRUE); - data.put(getGregorianDate(1001, Calendar.MARCH, 1), Boolean.TRUE); + Map data = new HashMap<>(); + data.put(getGregorianDate(999, OCTOBER, 1), Boolean.FALSE); + data.put(getGregorianDate(1000, JANUARY, 1), Boolean.FALSE); + data.put(getGregorianDate(1000, FEBRUARY, 1), Boolean.FALSE); + data.put(getGregorianDate(1000, FEBRUARY, 28), Boolean.FALSE); + data.put(getGregorianDate(1000, MARCH, 1), Boolean.TRUE); + data.put(getGregorianDate(1001, JANUARY, 1), Boolean.TRUE); + data.put(getGregorianDate(1001, JANUARY, 6), Boolean.TRUE); + data.put(getGregorianDate(1001, MARCH, 1), Boolean.TRUE); - Iterator itr = data.keySet().iterator(); - while (itr.hasNext()) { - Date d = itr.next(); - boolean expected = data.get(d).booleanValue(); + data.keySet().forEach(d -> { + boolean expected = data.get(d); GregorianCalendar cal = new GregorianCalendar(); cal.setGregorianChange(d); if (cal.isLeapYear(1000) != expected) { - errln("isLeapYear(1000) returned " + cal.isLeapYear(1000) + - " with cutover date (Julian) " + d); + errln("isLeapYear(1000) returned " + cal.isLeapYear(1000) + + " with cutover date (Julian) " + d); } - } - } - finally { + }); + } finally { TimeZone.setDefault(savedZone); } } @@ -2511,15 +2534,15 @@ */ public void Test5006864() { GregorianCalendar cal = new GregorianCalendar(); - int min = cal.getMinimum(cal.DAY_OF_WEEK_IN_MONTH); + int min = cal.getMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { errln("GregorianCalendar.getMinimum(DAY_OF_WEEK_IN_MONTH) returned " - + min + ", expected 1."); + + min + ", expected 1."); } - min = cal.getGreatestMinimum(cal.DAY_OF_WEEK_IN_MONTH); + min = cal.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH); if (min != 1) { errln("GregorianCalendar.getGreatestMinimum(DAY_OF_WEEK_IN_MONTH) returned " - + min + ", expected 1."); + + min + ", expected 1."); } } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/CalendarTest.java --- a/jdk/test/java/util/Calendar/CalendarTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/CalendarTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -30,12 +30,25 @@ * @key randomness */ -import java.util.*; -import java.text.*; -import java.io.*; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutput; +import java.io.ObjectOutputStream; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.SimpleTimeZone; +import java.util.TimeZone; + +import static java.util.Calendar.*; public class CalendarTest extends IntlTest { - static final int ONE_DAY = 24*60*60*1000; + + static final int ONE_DAY = 24 * 60 * 60 * 1000; static final int EPOCH_JULIAN = 2440588; public static void main(String argv[]) throws Exception { @@ -64,32 +77,31 @@ Changeover +6 days: 1582/10/21 dow=5 Changeover +7 days: 1582/10/22 dow=6 */ - int MON[] = { 9, 9, 9,10,10,10,10, 10, 10, 10, 10, 10, 10, 10, 10 }; - int DOM[] = { 28, 29, 30, 1, 2, 3, 4, 15, 16, 17, 18, 19, 20, 21, 22 }; - int DOW[] = { 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6 }; + int[] MON = { 9, 9, 9,10,10,10,10, 10, 10, 10, 10, 10, 10, 10, 10 }; + int[] DOM = { 28, 29, 30, 1, 2, 3, 4, 15, 16, 17, 18, 19, 20, 21, 22 }; + int[] DOW = { 6, 7, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6 }; // ^ <-Changeover Fri Oct 15 1582 - try { TimeZone.setDefault(TimeZone.getTimeZone("GMT")); - Date co = new Date(1582-1900, Calendar.OCTOBER, 15); + @SuppressWarnings("deprecation") + Date co = new Date(1582 - 1900, OCTOBER, 15); GregorianCalendar cal = new GregorianCalendar(); int j = 0; for (int i = -7; i <= 7; ++i, ++j) { - Date d = new Date(co.getTime() + i*ONE_DAY); + Date d = new Date(co.getTime() + i * ONE_DAY); cal.setTime(d); - int y = cal.get(Calendar.YEAR); - int mon = cal.get(Calendar.MONTH)+1-Calendar.JANUARY; - int dom = cal.get(Calendar.DATE); - int dow = cal.get(Calendar.DAY_OF_WEEK); + int y = cal.get(YEAR); + int mon = cal.get(MONTH) + 1 - JANUARY; + int dom = cal.get(DATE); + int dow = cal.get(DAY_OF_WEEK); - logln("Changeover " + (i>=0?"+":"") + i + - " days: " + y + "/" + mon + "/" + dom + " dow=" + dow); + logln("Changeover " + (i >= 0 ? "+" : "") + i + + " days: " + y + "/" + mon + "/" + dom + " dow=" + dow); if (y != 1582 || mon != MON[j] || dom != DOM[j] || dow != DOW[j]) { errln(" Fail: Above line is wrong"); } } - } - finally { + } finally { TimeZone.setDefault(savedZone); } } @@ -99,22 +111,22 @@ * of this test, we don't care about timezones and week data * (first day of week, minimal days in first week). */ + @SuppressWarnings("deprecation") public void TestMapping() { TimeZone saveZone = TimeZone.getDefault(); int[] DATA = { - // Julian# Year Month DOM JULIAN:Year, Month, DOM - 2440588, 1970, Calendar.JANUARY, 1, 1969, Calendar.DECEMBER, 19, - 2415080, 1900, Calendar.MARCH, 1, 1900, Calendar.FEBRUARY, 17, - 2451604, 2000, Calendar.FEBRUARY, 29, 2000, Calendar.FEBRUARY, 16, - 2452269, 2001, Calendar.DECEMBER, 25, 2001, Calendar.DECEMBER, 12, - 2416526, 1904, Calendar.FEBRUARY, 15, 1904, Calendar.FEBRUARY, 2, - 2416656, 1904, Calendar.JUNE, 24, 1904, Calendar.JUNE, 11, - 1721426, 1, Calendar.JANUARY, 1, 1, Calendar.JANUARY, 3, - 2000000, 763, Calendar.SEPTEMBER, 18, 763, Calendar.SEPTEMBER, 14, - 4000000, 6239, Calendar.JULY, 12, 6239, Calendar.MAY, 28, - 8000000, 17191, Calendar.FEBRUARY, 26, 17190, Calendar.OCTOBER, 22, - 10000000, 22666, Calendar.DECEMBER, 20, 22666, Calendar.JULY, 5, - }; + // Julian# Year Month DOM JULIAN:Year Month, DOM + 2440588, 1970, JANUARY, 1, 1969, DECEMBER, 19, + 2415080, 1900, MARCH, 1, 1900, FEBRUARY, 17, + 2451604, 2000, FEBRUARY, 29, 2000, FEBRUARY, 16, + 2452269, 2001, DECEMBER, 25, 2001, DECEMBER, 12, + 2416526, 1904, FEBRUARY, 15, 1904, FEBRUARY, 2, + 2416656, 1904, JUNE, 24, 1904, JUNE, 11, + 1721426, 1, JANUARY, 1, 1, JANUARY, 3, + 2000000, 763, SEPTEMBER, 18, 763, SEPTEMBER, 14, + 4000000, 6239, JULY, 12, 6239, MAY, 28, + 8000000, 17191, FEBRUARY, 26, 17190, OCTOBER, 22, + 10000000, 22666, DECEMBER, 20, 22666, JULY, 5}; try { TimeZone.setDefault(TimeZone.getTimeZone("UTC")); @@ -123,11 +135,11 @@ GregorianCalendar cal = new GregorianCalendar(); for (int i = 0; i < DATA.length; i += 7) { int julian = DATA[i]; - int year = DATA[i+1]; - int month = DATA[i+2]; - int dom = DATA[i+3]; + int year = DATA[i + 1]; + int month = DATA[i + 2]; + int dom = DATA[i + 3]; int year2, month2, dom2; - long millis = ((long)julian - EPOCH_JULIAN) * ONE_DAY; + long millis = ((long) julian - EPOCH_JULIAN) * ONE_DAY; String s; // Test Gregorian computation @@ -137,56 +149,55 @@ long calMillis = cal.getTime().getTime(); long delta = calMillis - millis; cal.setTime(new Date(millis)); - year2 = cal.get(Calendar.YEAR); - month2 = cal.get(Calendar.MONTH); - dom2 = cal.get(Calendar.DAY_OF_MONTH); - s = "G " + year + "-" + (month+1-Calendar.JANUARY) + "-" + dom + - " => " + calMillis + - " (" + ((float)delta/ONE_DAY) + " day delta) => " + - year2 + "-" + (month2+1-Calendar.JANUARY) + "-" + dom2; - if (delta != 0 || year != year2 || month != month2 || - dom != dom2) { + year2 = cal.get(YEAR); + month2 = cal.get(MONTH); + dom2 = cal.get(DAY_OF_MONTH); + s = "G " + year + "-" + (month + 1 - JANUARY) + "-" + dom + + " => " + calMillis + + " (" + ((float) delta / ONE_DAY) + " day delta) => " + + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; + if (delta != 0 || year != year2 || month != month2 + || dom != dom2) { errln(s + " FAIL"); } else { logln(s); } // Test Julian computation - year = DATA[i+4]; - month = DATA[i+5]; - dom = DATA[i+6]; + year = DATA[i + 4]; + month = DATA[i + 5]; + dom = DATA[i + 6]; cal.setGregorianChange(PURE_JULIAN); cal.clear(); cal.set(year, month, dom); calMillis = cal.getTime().getTime(); delta = calMillis - millis; cal.setTime(new Date(millis)); - year2 = cal.get(Calendar.YEAR); - month2 = cal.get(Calendar.MONTH); - dom2 = cal.get(Calendar.DAY_OF_MONTH); - s = "J " + year + "-" + (month+1-Calendar.JANUARY) + "-" + dom + - " => " + calMillis + - " (" + ((float)delta/ONE_DAY) + " day delta) => " + - year2 + "-" + (month2+1-Calendar.JANUARY) + "-" + dom2; - if (delta != 0 || year != year2 || month != month2 || - dom != dom2) { + year2 = cal.get(YEAR); + month2 = cal.get(MONTH); + dom2 = cal.get(DAY_OF_MONTH); + s = "J " + year + "-" + (month + 1 - JANUARY) + "-" + dom + + " => " + calMillis + + " (" + ((float) delta / ONE_DAY) + " day delta) => " + + year2 + "-" + (month2 + 1 - JANUARY) + "-" + dom2; + if (delta != 0 || year != year2 || month != month2 + || dom != dom2) { errln(s + " FAIL"); } else { logln(s); } } - cal.setGregorianChange(new Date(1582-1900, Calendar.OCTOBER, 15)); - auxMapping(cal, 1582, Calendar.OCTOBER, 4); - auxMapping(cal, 1582, Calendar.OCTOBER, 15); - auxMapping(cal, 1582, Calendar.OCTOBER, 16); - for (int y = 800; y < 3000; y += 1+(int)100*Math.random()) { - for (int m = Calendar.JANUARY; m <= Calendar.DECEMBER; ++m) { + cal.setGregorianChange(new Date(1582 - 1900, OCTOBER, 15)); + auxMapping(cal, 1582, OCTOBER, 4); + auxMapping(cal, 1582, OCTOBER, 15); + auxMapping(cal, 1582, OCTOBER, 16); + for (int y = 800; y < 3000; y += 1 + 100 * Math.random()) { + for (int m = JANUARY; m <= DECEMBER; ++m) { auxMapping(cal, y, m, 15); } } - } - finally { + } finally { TimeZone.setDefault(saveZone); } } @@ -195,14 +206,16 @@ cal.set(y, m, d); long millis = cal.getTime().getTime(); cal.setTime(new Date(millis)); - int year2 = cal.get(Calendar.YEAR); - int month2 = cal.get(Calendar.MONTH); - int dom2 = cal.get(Calendar.DAY_OF_MONTH); - if (y != year2 || m != month2 || dom2 != d) - errln("Round-trip failure: " + y + "-" + (m+1) + "-"+d+" =>ms=> " + - year2 + "-" + (month2+1) + "-" + dom2); + int year2 = cal.get(YEAR); + int month2 = cal.get(MONTH); + int dom2 = cal.get(DAY_OF_MONTH); + if (y != year2 || m != month2 || dom2 != d) { + errln("Round-trip failure: " + y + "-" + (m + 1) + "-" + d + " =>ms=> " + + year2 + "-" + (month2 + 1) + "-" + dom2); + } } + @SuppressWarnings("deprecation") public void TestGenericAPI() { Locale locale = Locale.getDefault(); if (!TestUtils.usesGregorianCalendar(locale)) { @@ -211,76 +224,95 @@ } String str; - - Date when = new Date(90, Calendar.APRIL, 15); + Date when = new Date(90, APRIL, 15); String tzid = "TestZone"; int tzoffset = 123400; SimpleTimeZone zone = new SimpleTimeZone(tzoffset, tzid); - Calendar cal = (Calendar)Calendar.getInstance((SimpleTimeZone)zone.clone()); + Calendar cal = Calendar.getInstance((SimpleTimeZone) zone.clone()); - if (!zone.equals(cal.getTimeZone())) errln("FAIL: Calendar.getTimeZone failed"); + if (!zone.equals(cal.getTimeZone())) { + errln("FAIL: Calendar.getTimeZone failed"); + } Calendar cal2 = Calendar.getInstance(cal.getTimeZone()); cal.setTime(when); cal2.setTime(when); - if (!(cal.equals(cal2))) errln("FAIL: Calendar.operator== failed"); + if (!(cal.equals(cal2))) { + errln("FAIL: Calendar.operator== failed"); + } // if ((*cal != *cal2)) errln("FAIL: Calendar.operator!= failed"); - if (!cal.equals(cal2) || - cal.before(cal2) || - cal.after(cal2)) errln("FAIL: equals/before/after failed"); + if (!cal.equals(cal2) + || cal.before(cal2) + || cal.after(cal2)) { + errln("FAIL: equals/before/after failed"); + } cal2.setTime(new Date(when.getTime() + 1000)); - if (cal.equals(cal2) || - cal2.before(cal) || - cal.after(cal2)) errln("FAIL: equals/before/after failed"); + if (cal.equals(cal2) + || cal2.before(cal) + || cal.after(cal2)) { + errln("FAIL: equals/before/after failed"); + } - cal.roll(Calendar.SECOND, true); - if (!cal.equals(cal2) || - cal.before(cal2) || - cal.after(cal2)) errln("FAIL: equals/before/after failed"); + cal.roll(SECOND, true); + if (!cal.equals(cal2) + || cal.before(cal2) + || cal.after(cal2)) { + errln("FAIL: equals/before/after failed"); + } // Roll back to January - cal.roll(Calendar.MONTH, (int)(1 + Calendar.DECEMBER - cal.get(Calendar.MONTH))); - if (cal.equals(cal2) || - cal2.before(cal) || - cal.after(cal2)) errln("FAIL: equals/before/after failed"); + cal.roll(MONTH, 1 + DECEMBER - cal.get(MONTH)); + if (cal.equals(cal2) + || cal2.before(cal) + || cal.after(cal2)) { + errln("FAIL: equals/before/after failed"); + } // C++ only /* TimeZone z = cal.orphanTimeZone(); - if (z.getID(str) != tzid || - z.getRawOffset() != tzoffset) - errln("FAIL: orphanTimeZone failed"); - */ - + if (z.getID(str) != tzid || + z.getRawOffset() != tzoffset) + errln("FAIL: orphanTimeZone failed"); + */ for (int i = 0; i < 2; ++i) { - boolean lenient = ( i > 0 ); + boolean lenient = (i > 0); cal.setLenient(lenient); - if (lenient != cal.isLenient()) errln("FAIL: setLenient/isLenient failed"); + if (lenient != cal.isLenient()) { + errln("FAIL: setLenient/isLenient failed"); + } // Later: Check for lenient behavior } int i; - for (i = Calendar.SUNDAY; i <= Calendar.SATURDAY; ++i) { + for (i = SUNDAY; i <= SATURDAY; ++i) { cal.setFirstDayOfWeek(i); - if (cal.getFirstDayOfWeek() != i) errln("FAIL: set/getFirstDayOfWeek failed"); + if (cal.getFirstDayOfWeek() != i) { + errln("FAIL: set/getFirstDayOfWeek failed"); + } } for (i = 0; i <= 7; ++i) { cal.setMinimalDaysInFirstWeek(i); - if (cal.getMinimalDaysInFirstWeek() != i) errln("FAIL: set/getFirstDayOfWeek failed"); + if (cal.getMinimalDaysInFirstWeek() != i) { + errln("FAIL: set/getFirstDayOfWeek failed"); + } } - for (i = 0; i < Calendar.FIELD_COUNT; ++i) { - if (cal.getMinimum(i) != cal.getGreatestMinimum(i)) + for (i = 0; i < FIELD_COUNT; ++i) { + if (cal.getMinimum(i) != cal.getGreatestMinimum(i)) { errln("FAIL: getMinimum doesn't match getGreatestMinimum for field " + i); - if (cal.getLeastMaximum(i) > cal.getMaximum(i)) + } + if (cal.getLeastMaximum(i) > cal.getMaximum(i)) { errln("FAIL: getLeastMaximum larger than getMaximum for field " + i); - if (cal.getMinimum(i) >= cal.getMaximum(i)) + } + if (cal.getMinimum(i) >= cal.getMaximum(i)) { errln("FAIL: getMinimum not less than getMaximum for field " + i); + } } cal.setTimeZone(TimeZone.getDefault()); @@ -306,30 +338,36 @@ } cal.getTime(); - for (i = 0; i < Calendar.FIELD_COUNT; ++i) { - switch(i) { - case Calendar.YEAR: case Calendar.MONTH: case Calendar.DATE: - case Calendar.HOUR_OF_DAY: case Calendar.MINUTE: case Calendar.SECOND: - if (!cal.isSet(i)) - errln("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); - break; - default: - if (cal.isSet(i)) - errln("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); + for (i = 0; i < FIELD_COUNT; ++i) { + switch (i) { + case YEAR: + case MONTH: + case DATE: + case HOUR_OF_DAY: + case MINUTE: + case SECOND: + if (!cal.isSet(i)) { + errln("FAIL: !Calendar.isSet test failed: " + calendarFieldNames[i]); + } + break; + default: + if (cal.isSet(i)) { + errln("FAIL: Calendar.isSet test failed: " + calendarFieldNames[i]); + } } cal.clear(i); - if (cal.isSet(i)) errln("FAIL: Calendar.clear/isSet failed"); + if (cal.isSet(i)) { + errln("FAIL: Calendar.clear/isSet failed"); + } } // delete cal; // delete cal2; - Locale[] loc = Calendar.getAvailableLocales(); long count = loc.length; if (count < 1 || loc == null) { errln("FAIL: getAvailableLocales failed"); - } - else { + } else { for (i = 0; i < count; ++i) { cal = Calendar.getInstance(loc[i]); // delete cal; @@ -358,13 +396,15 @@ // delete gc; gc = new GregorianCalendar(1998, 10, 14, 21, 43); - if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43).getTime()) + if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43).getTime()) { errln("FAIL: new GregorianCalendar(ymdhm) failed"); + } // delete gc; gc = new GregorianCalendar(1998, 10, 14, 21, 43, 55); - if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43, 55).getTime()) + if (gc.getTime().getTime() != new Date(98, 10, 14, 21, 43, 55).getTime()) { errln("FAIL: new GregorianCalendar(ymdhms) failed"); + } // C++ only: // GregorianCalendar gc2 = new GregorianCalendar(Locale.ENGLISH); @@ -378,19 +418,20 @@ public void TestRog() { GregorianCalendar gc = new GregorianCalendar(); - int year = 1997, month = Calendar.APRIL, date = 1; + int year = 1997, month = APRIL, date = 1; gc.set(year, month, date); // April 1, 1997 - gc.set(Calendar.HOUR_OF_DAY, 23); - gc.set(Calendar.MINUTE, 0); - gc.set(Calendar.SECOND, 0); - gc.set(Calendar.MILLISECOND, 0); + gc.set(HOUR_OF_DAY, 23); + gc.set(MINUTE, 0); + gc.set(SECOND, 0); + gc.set(MILLISECOND, 0); - for (int i = 0; i < 9; i++, gc.add(Calendar.DATE, 1)) { - if (gc.get(Calendar.YEAR) != year || - gc.get(Calendar.MONTH) != month || - gc.get(Calendar.DATE) != (date + i)) + for (int i = 0; i < 9; i++, gc.add(DATE, 1)) { + if (gc.get(YEAR) != year + || gc.get(MONTH) != month + || gc.get(DATE) != (date + i)) { errln("FAIL: Date " + gc.getTime() + " wrong"); + } } } @@ -402,162 +443,172 @@ void dowTest(boolean lenient) { GregorianCalendar cal = new GregorianCalendar(); - cal.set(1997, Calendar.AUGUST, 12); // Wednesday + cal.set(1997, AUGUST, 12); // Wednesday cal.getTime(); // Force update cal.setLenient(lenient); - cal.set(1996, Calendar.DECEMBER, 1); // Set the date to be December 1, 1996 - int dow = cal.get(Calendar.DAY_OF_WEEK); - int min = cal.getMinimum(Calendar.DAY_OF_WEEK); - int max = cal.getMaximum(Calendar.DAY_OF_WEEK); - if (dow < min || dow > max) errln("FAIL: Day of week " + dow + " out of range"); - if (dow != Calendar.SUNDAY) { + cal.set(1996, DECEMBER, 1); // Set the date to be December 1, 1996 + int dow = cal.get(DAY_OF_WEEK); + int min = cal.getMinimum(DAY_OF_WEEK); + int max = cal.getMaximum(DAY_OF_WEEK); + if (dow < min || dow > max) { + errln("FAIL: Day of week " + dow + " out of range"); + } + if (dow != SUNDAY) { errln("FAIL2: Day of week should be SUNDAY; is " + dow + ": " + cal.getTime()); } - if (min != Calendar.SUNDAY || max != Calendar.SATURDAY) errln("FAIL: Min/max bad"); + if (min != SUNDAY || max != SATURDAY) { + errln("FAIL: Min/max bad"); + } } // Verify that the clone method produces distinct objects with no // unintentionally shared fields. public void TestClonesUnique908() { Calendar c = Calendar.getInstance(); - Calendar d = (Calendar)c.clone(); - c.set(Calendar.MILLISECOND, 123); - d.set(Calendar.MILLISECOND, 456); - if (c.get(Calendar.MILLISECOND) != 123 || - d.get(Calendar.MILLISECOND) != 456) { + Calendar d = (Calendar) c.clone(); + c.set(MILLISECOND, 123); + d.set(MILLISECOND, 456); + if (c.get(MILLISECOND) != 123 + || d.get(MILLISECOND) != 456) { errln("FAIL: Clones share fields"); } } // Verify effect of Gregorian cutoff value + @SuppressWarnings("deprecation") public void TestGregorianChange768() { boolean b; GregorianCalendar c = new GregorianCalendar(); logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b=c.isLeapYear(1800))); + logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); logln(" (should be FALSE)"); - if (b != false) errln("FAIL"); + if (b != false) { + errln("FAIL"); + } c.setGregorianChange(new Date(0, 0, 1)); // Jan 1 1900 logln("With cutoff " + c.getGregorianChange()); - logln(" isLeapYear(1800) = " + (b=c.isLeapYear(1800))); + logln(" isLeapYear(1800) = " + (b = c.isLeapYear(1800))); logln(" (should be TRUE)"); - if (b != true) errln("FAIL"); + if (b != true) { + errln("FAIL"); + } } // Test the correct behavior of the disambiguation algorithm. public void TestDisambiguation765() throws Exception { - Locale savedLocale = Locale.getDefault(); - try { - Locale.setDefault(Locale.US); - Calendar c = Calendar.getInstance(); - c.setLenient(false); + Locale savedLocale = Locale.getDefault(); + try { + Locale.setDefault(Locale.US); + Calendar c = Calendar.getInstance(); + c.setLenient(false); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.DATE, 3); + c.clear(); + c.set(YEAR, 1997); + c.set(MONTH, JUNE); + c.set(DATE, 3); - verify765("1997 third day of June = ", c, 1997, Calendar.JUNE, 3); + verify765("1997 third day of June = ", c, 1997, JUNE, 3); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); - verify765("1997 first Tuesday in June = ", c, 1997, Calendar.JUNE, 3); + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(DAY_OF_WEEK_IN_MONTH, 1); + verify765("1997 first Tuesday in June = ", c, 1997, JUNE, 3); - c.setLenient(true); // for 4944795 - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.DAY_OF_WEEK_IN_MONTH, -1); - verify765("1997 last Tuesday in June = ", c, 1997, Calendar.JUNE, 24); - - c.setLenient(false); - IllegalArgumentException e = null; - try { + c.setLenient(true); // for 4944795 c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.DAY_OF_WEEK_IN_MONTH, 0); - c.getTime(); - } - catch (IllegalArgumentException ex) { - e = ex; - } - verify765("1997 zero-th Tuesday in June = ", e); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(DAY_OF_WEEK_IN_MONTH, -1); + verify765("1997 last Tuesday in June = ", c, 1997, JUNE, 24); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.WEEK_OF_MONTH, 1); - verify765("1997 Tuesday in week 1 of June = ", c, 1997, Calendar.JUNE, 3); + c.setLenient(false); + IllegalArgumentException e = null; + try { + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(DAY_OF_WEEK_IN_MONTH, 0); + c.getTime(); + } catch (IllegalArgumentException ex) { + e = ex; + } + verify765("1997 zero-th Tuesday in June = ", e); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.WEEK_OF_MONTH, 4); - verify765("1997 Tuesday in week 4 of June = ", c, 1997, Calendar.JUNE, 24); - - try { c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.MONTH, Calendar.JUNE); - c.set(Calendar.WEEK_OF_MONTH, 1); - verify765("1997 Tuesday in week 0 of June = ", c, 1997, Calendar.JUNE, 3); - } - catch (IllegalArgumentException ex) { - errln("FAIL: Exception seen: " + ex.getMessage()); - // ex.printStackTrace(log); - } + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(WEEK_OF_MONTH, 1); + verify765("1997 Tuesday in week 1 of June = ", c, 1997, JUNE, 3); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.WEEK_OF_YEAR, 2); - verify765("1997 Tuesday in week 2 of year = ", c, 1997, Calendar.JANUARY, 7); + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(WEEK_OF_MONTH, 4); + verify765("1997 Tuesday in week 4 of June = ", c, 1997, JUNE, 24); - c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.WEEK_OF_YEAR, 10); - verify765("1997 Tuesday in week 10 of year = ", c, 1997, Calendar.MARCH, 4); + try { + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(MONTH, JUNE); + c.set(WEEK_OF_MONTH, 1); + verify765("1997 Tuesday in week 0 of June = ", c, 1997, JUNE, 3); + } catch (IllegalArgumentException ex) { + errln("FAIL: Exception seen: " + ex.getMessage()); + // ex.printStackTrace(log); + } - try { c.clear(); - c.set(Calendar.YEAR, 1997); - c.set(Calendar.DAY_OF_WEEK, Calendar.TUESDAY); - c.set(Calendar.WEEK_OF_YEAR, 0); - verify765("1997 Tuesday in week 0 of year = ", c, 1996, Calendar.DECEMBER, 24); - throw new Exception("Fail: WEEK_OF_YEAR 0 should be illegal"); - } - catch (IllegalArgumentException ex) {} - } - finally { - Locale.setDefault(savedLocale); - } - } - void verify765(String msg, Calendar c, int year, int month, int day) { - if (c.get(Calendar.YEAR) == year && - c.get(Calendar.MONTH) == month && - c.get(Calendar.DATE) == day) { - logln("PASS: " + msg + c.getTime()); - } - else { - errln("FAIL: " + msg + c.getTime() + - "; expected " + - year + "/" + (month+1) + "/" + day); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(WEEK_OF_YEAR, 2); + verify765("1997 Tuesday in week 2 of year = ", c, 1997, JANUARY, 7); + + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(WEEK_OF_YEAR, 10); + verify765("1997 Tuesday in week 10 of year = ", c, 1997, MARCH, 4); + + try { + c.clear(); + c.set(YEAR, 1997); + c.set(DAY_OF_WEEK, TUESDAY); + c.set(WEEK_OF_YEAR, 0); + verify765("1997 Tuesday in week 0 of year = ", c, 1996, DECEMBER, 24); + throw new Exception("Fail: WEEK_OF_YEAR 0 should be illegal"); + } catch (IllegalArgumentException ex) { + } + } finally { + Locale.setDefault(savedLocale); } } + + void verify765(String msg, Calendar c, int year, int month, int day) { + if (c.get(YEAR) == year + && c.get(MONTH) == month + && c.get(DATE) == day) { + logln("PASS: " + msg + c.getTime()); + } else { + errln("FAIL: " + msg + c.getTime() + + "; expected " + + year + "/" + (month + 1) + "/" + day); + } + } + // Called when e expected to be non-null void verify765(String msg, IllegalArgumentException e) { - if (e == null) errln("FAIL: No IllegalArgumentException for " + msg); - else logln("PASS: " + msg + "IllegalArgument as expected"); + if (e == null) { + errln("FAIL: No IllegalArgumentException for " + msg); + } else { + logln("PASS: " + msg + "IllegalArgument as expected"); + } } // Test the behavior of GMT vs. local time @@ -588,106 +639,112 @@ Date date; Calendar gmtcal = Calendar.getInstance(); gmtcal.setTimeZone(TimeZone.getTimeZone("Africa/Casablanca")); - gmtcal.set(yr, mo-1, dt, hr, mn, sc); - gmtcal.set(Calendar.MILLISECOND, 0); + gmtcal.set(yr, mo - 1, dt, hr, mn, sc); + gmtcal.set(MILLISECOND, 0); date = gmtcal.getTime(); - logln("date = "+date); + logln("date = " + date); Calendar cal = Calendar.getInstance(); cal.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles")); cal.setTime(date); - int offset = cal.getTimeZone().getOffset(cal.get(Calendar.ERA), - cal.get(Calendar.YEAR), - cal.get(Calendar.MONTH), - cal.get(Calendar.DATE), - cal.get(Calendar.DAY_OF_WEEK), - cal.get(Calendar.MILLISECOND)); + int offset = cal.getTimeZone().getOffset(cal.get(ERA), + cal.get(YEAR), + cal.get(MONTH), + cal.get(DATE), + cal.get(DAY_OF_WEEK), + cal.get(MILLISECOND)); - logln("offset for "+date+"= "+(offset/1000/60/60.0) + "hr"); + logln("offset for " + date + "= " + (offset / 1000 / 60 / 60.0) + "hr"); - int utc = ((cal.get(Calendar.HOUR_OF_DAY) * 60 + - cal.get(Calendar.MINUTE)) * 60 + - cal.get(Calendar.SECOND)) * 1000 + - cal.get(Calendar.MILLISECOND) - offset; + int utc = ((cal.get(HOUR_OF_DAY) * 60 + + cal.get(MINUTE)) * 60 + + cal.get(SECOND)) * 1000 + + cal.get(MILLISECOND) - offset; int expected = ((hr * 60 + mn) * 60 + sc) * 1000; - if (utc != expected) - errln("FAIL: Discrepancy of " + - (utc - expected) + " millis = " + - ((utc-expected)/1000/60/60.0) + " hr"); + if (utc != expected) { + errln("FAIL: Discrepancy of " + + (utc - expected) + " millis = " + + ((utc - expected) / 1000 / 60 / 60.0) + " hr"); + } } // Verify that add and set work regardless of the order in which // they are called. public void TestAddSetOrder621() { + @SuppressWarnings("deprecation") Date d = new Date(97, 4, 14, 13, 23, 45); - Calendar cal = Calendar.getInstance (); - cal.setTime (d); - cal.add (Calendar.DATE, -5); - cal.set (Calendar.HOUR_OF_DAY, 0); - cal.set (Calendar.MINUTE, 0); - cal.set (Calendar.SECOND, 0); + Calendar cal = Calendar.getInstance(); + cal.setTime(d); + cal.add(DATE, -5); + cal.set(HOUR_OF_DAY, 0); + cal.set(MINUTE, 0); + cal.set(SECOND, 0); // ma feb 03 00:00:00 GMT+00:00 1997 - String s = cal.getTime ().toString (); + String s = cal.getTime().toString(); - cal = Calendar.getInstance (); - cal.setTime (d); - cal.set (Calendar.HOUR_OF_DAY, 0); - cal.set (Calendar.MINUTE, 0); - cal.set (Calendar.SECOND, 0); - cal.add (Calendar.DATE, -5); + cal = Calendar.getInstance(); + cal.setTime(d); + cal.set(HOUR_OF_DAY, 0); + cal.set(MINUTE, 0); + cal.set(SECOND, 0); + cal.add(DATE, -5); // ma feb 03 13:11:06 GMT+00:00 1997 - String s2 = cal.getTime ().toString (); + String s2 = cal.getTime().toString(); - if (s.equals(s2)) + if (s.equals(s2)) { logln("Pass: " + s + " == " + s2); - else + } else { errln("FAIL: " + s + " != " + s2); + } } // Verify that add works. public void TestAdd520() { - int y = 1997, m = Calendar.FEBRUARY, d = 1; - GregorianCalendar temp = new GregorianCalendar( y, m, d ); + int y = 1997, m = FEBRUARY, d = 1; + GregorianCalendar temp = new GregorianCalendar(y, m, d); check520(temp, y, m, d); - temp.add( temp.YEAR, 1 ); + temp.add(YEAR, 1); y++; check520(temp, y, m, d); - temp.add( temp.MONTH, 1 ); + temp.add(MONTH, 1); m++; check520(temp, y, m, d); - temp.add( temp.DATE, 1 ); + temp.add(DATE, 1); d++; check520(temp, y, m, d); - temp.add( temp.DATE, 2 ); + temp.add(DATE, 2); d += 2; check520(temp, y, m, d); - temp.add( temp.DATE, 28 ); - d = 1; ++m; + temp.add(DATE, 28); + d = 1; + ++m; check520(temp, y, m, d); } + void check520(Calendar c, int y, int m, int d) { - if (c.get(Calendar.YEAR) != y || - c.get(Calendar.MONTH) != m || - c.get(Calendar.DATE) != d) { - errln("FAILURE: Expected YEAR/MONTH/DATE of " + - y + "/" + (m+1) + "/" + d + - "; got " + - c.get(Calendar.YEAR) + "/" + - (c.get(Calendar.MONTH)+1) + "/" + - c.get(Calendar.DATE)); + if (c.get(YEAR) != y + || c.get(MONTH) != m + || c.get(DATE) != d) { + errln("FAILURE: Expected YEAR/MONTH/DATE of " + + y + "/" + (m + 1) + "/" + d + + "; got " + + c.get(YEAR) + "/" + + (c.get(MONTH) + 1) + "/" + + c.get(DATE)); + } else { + logln("Confirmed: " + + y + "/" + (m + 1) + "/" + d); } - else logln("Confirmed: " + - y + "/" + (m+1) + "/" + d); } // Verify that setting fields works. This test fails when an exception is thrown. @@ -697,18 +754,18 @@ GregorianCalendar g2 = new GregorianCalendar(); // At this point UTC value is set, various fields are not. // Now set to noon. - g2.set(Calendar.HOUR, 12); - g2.set(Calendar.MINUTE, 0); - g2.set(Calendar.SECOND, 0); + g2.set(HOUR, 12); + g2.set(MINUTE, 0); + g2.set(SECOND, 0); // At this point the object thinks UTC is NOT set, but fields are set. // The following line will result in IllegalArgumentException because // it thinks the YEAR is set and it is NOT. - if (g2.equals(g)) + if (g2.equals(g)) { logln("Same"); - else + } else { logln("Different"); - } - catch (IllegalArgumentException e) { + } + } catch (IllegalArgumentException e) { errln("Unexpected exception seen: " + e); } } @@ -729,28 +786,28 @@ FileInputStream in = new FileInputStream(FILENAME); ObjectInputStream t = new ObjectInputStream(in); - String pre = (String)t.readObject(); - Calendar c = (Calendar)t.readObject(); - String post = (String)t.readObject(); + String pre = (String) t.readObject(); + Calendar c = (Calendar) t.readObject(); + String post = (String) t.readObject(); in.close(); - ok = pre.equals(PREFIX) && - post.equals(POSTFIX) && - cal.equals(c); + ok = pre.equals(PREFIX) + && post.equals(POSTFIX) + && cal.equals(c); File fl = new File(FILENAME); fl.delete(); - } - catch (IOException e) { + } catch (IOException e) { errln("FAIL: Exception received:"); // e.printStackTrace(log); - } - catch (ClassNotFoundException e) { + } catch (ClassNotFoundException e) { errln("FAIL: Exception received:"); // e.printStackTrace(log); } - if (!ok) errln("Serialization of Calendar object failed."); + if (!ok) { + errln("Serialization of Calendar object failed."); + } } static final String PREFIX = "abc"; static final String POSTFIX = "def"; @@ -758,14 +815,16 @@ // Try to zero out the seconds field public void TestSecondsZero121() { - Calendar cal = new GregorianCalendar(); + Calendar cal = new GregorianCalendar(); // Initialize with current date/time cal.setTime(new Date()); // Round down to minute - cal.set(Calendar.SECOND, 0); - Date d = cal.getTime(); + cal.set(SECOND, 0); + Date d = cal.getTime(); String s = d.toString(); - if (s.indexOf(":00 ") < 0) errln("Expected to see :00 in " + s); + if (s.indexOf(":00 ") < 0) { + errln("Expected to see :00 in " + s); + } } // Try various sequences of add, set, and get method calls. @@ -777,15 +836,17 @@ // - Addition uses millis which are still *now* // { - Calendar calendar = new GregorianCalendar( ) ; - calendar.set( 1993, Calendar.JANUARY, 4 ) ; - logln( "1A) " + value( calendar ) ) ; - calendar.add( Calendar.DATE, 1 ) ; + Calendar calendar = new GregorianCalendar(); + calendar.set(1993, JANUARY, 4); + logln("1A) " + value(calendar)); + calendar.add(DATE, 1); String v = value(calendar); - logln( "1B) " + v ); - logln( "--) 1993/0/5" ) ; - if (!v.equals(EXPECTED_0610)) errln("Expected " + EXPECTED_0610 + - "; saw " + v); + logln("1B) " + v); + logln("--) 1993/0/5"); + if (!v.equals(EXPECTED_0610)) { + errln("Expected " + EXPECTED_0610 + + "; saw " + v); + } } // @@ -793,16 +854,17 @@ // - Upon initialization calendar fields set, millis = 0 // - Addition uses millis which are still 1970, 0, 1 // - { - Calendar calendar = new GregorianCalendar( 1993, Calendar.JANUARY, 4 ) ; - logln( "2A) " + value( calendar ) ) ; - calendar.add( Calendar.DATE, 1 ) ; + Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); + logln("2A) " + value(calendar)); + calendar.add(DATE, 1); String v = value(calendar); - logln( "2B) " + v ); - logln( "--) 1993/0/5" ) ; - if (!v.equals(EXPECTED_0610)) errln("Expected " + EXPECTED_0610 + - "; saw " + v); + logln("2B) " + v); + logln("--) 1993/0/5"); + if (!v.equals(EXPECTED_0610)) { + errln("Expected " + EXPECTED_0610 + + "; saw " + v); + } } // @@ -811,102 +873,99 @@ // - getTime( ) is called which forces the millis to be set // - Addition uses millis which are correct // - { - Calendar calendar = new GregorianCalendar( 1993, Calendar.JANUARY, 4 ) ; - logln( "3A) " + value( calendar ) ) ; - calendar.getTime( ) ; - calendar.add( Calendar.DATE, 1 ) ; + Calendar calendar = new GregorianCalendar(1993, JANUARY, 4); + logln("3A) " + value(calendar)); + calendar.getTime(); + calendar.add(DATE, 1); String v = value(calendar); - logln( "3B) " + v ) ; - logln( "--) 1993/0/5" ) ; - if (!v.equals(EXPECTED_0610)) errln("Expected " + EXPECTED_0610 + - "; saw " + v); + logln("3B) " + v); + logln("--) 1993/0/5"); + if (!v.equals(EXPECTED_0610)) { + errln("Expected " + EXPECTED_0610 + + "; saw " + v); + } } } - static String value( Calendar calendar ) { - return( calendar.get( Calendar.YEAR ) + "/" + - calendar.get( Calendar.MONTH ) + "/" + - calendar.get( Calendar.DATE ) ) ; + static String value(Calendar calendar) { + return (calendar.get(YEAR) + "/" + + calendar.get(MONTH) + "/" + + calendar.get(DATE)); } static String EXPECTED_0610 = "1993/0/5"; // Test that certain fields on a certain date are as expected. public void TestFields060() { int year = 1997; - int month = java.util.Calendar.OCTOBER; //october + int month = OCTOBER; //october int dDate = 22; //DAYOFWEEK should return 3 for Wednesday GregorianCalendar calendar = null; - calendar = new GregorianCalendar( year, month, dDate); - for (int i = 0; i < EXPECTED_FIELDS.length; ) { + calendar = new GregorianCalendar(year, month, dDate); + for (int i = 0; i < EXPECTED_FIELDS.length;) { int field = EXPECTED_FIELDS[i++]; int expected = EXPECTED_FIELDS[i++]; if (calendar.get(field) != expected) { - errln("Expected field " + field + " to have value " + expected + - "; received " + calendar.get(field) + " instead"); + errln("Expected field " + field + " to have value " + expected + + "; received " + calendar.get(field) + " instead"); } } } - static int EXPECTED_FIELDS[] = { - Calendar.YEAR, 1997, - Calendar.MONTH, Calendar.OCTOBER, - Calendar.DAY_OF_MONTH, 22, - Calendar.DAY_OF_WEEK, Calendar.WEDNESDAY, - Calendar.DAY_OF_WEEK_IN_MONTH, 4, - Calendar.DAY_OF_YEAR, 295 - }; + static int[] EXPECTED_FIELDS = { + YEAR, 1997, + MONTH, OCTOBER, + DAY_OF_MONTH, 22, + DAY_OF_WEEK, WEDNESDAY, + DAY_OF_WEEK_IN_MONTH, 4, + DAY_OF_YEAR, 295}; static final String[] calendarFieldNames = { - /* 0 */ "ERA", - /* 1 */ "YEAR", - /* 2 */ "MONTH", - /* 3 */ "WEEK_OF_YEAR", - /* 4 */ "WEEK_OF_MONTH", - /* 5 */ "DAY_OF_MONTH", - /* 6 */ "DAY_OF_YEAR", - /* 7 */ "DAY_OF_WEEK", - /* 8 */ "DAY_OF_WEEK_IN_MONTH", - /* 9 */ "AM_PM", - /* 10 */ "HOUR", - /* 11 */ "HOUR_OF_DAY", - /* 12 */ "MINUTE", - /* 13 */ "SECOND", - /* 14 */ "MILLISECOND", - /* 15 */ "ZONE_OFFSET", - /* 16 */ "DST_OFFSET" - }; + /* 0 */ "ERA", + /* 1 */ "YEAR", + /* 2 */ "MONTH", + /* 3 */ "WEEK_OF_YEAR", + /* 4 */ "WEEK_OF_MONTH", + /* 5 */ "DAY_OF_MONTH", + /* 6 */ "DAY_OF_YEAR", + /* 7 */ "DAY_OF_WEEK", + /* 8 */ "DAY_OF_WEEK_IN_MONTH", + /* 9 */ "AM_PM", + /* 10 */ "HOUR", + /* 11 */ "HOUR_OF_DAY", + /* 12 */ "MINUTE", + /* 13 */ "SECOND", + /* 14 */ "MILLISECOND", + /* 15 */ "ZONE_OFFSET", + /* 16 */ "DST_OFFSET"}; // Verify that the fields are as expected (mostly zero) at the epoch start. // Note that we adjust for the default timezone to get most things to zero. public void TestEpochStartFields() { String[][] lt = { - {"en", "US", "US/Pacific"}, /* First day = 1, Minimum day = 1 */ - {"en", "US", "America/Anchorage"}, /* First day = 1, Minimum day = 1 */ - {"en", "TO", "Pacific/Tongatapu"}, /* First day = 1, Minimum day = 1 */ - {"en", "MH", "Pacific/Majuro"}, /* First day = 1, Minimum day = 1 */ - {"ja", "JP", "Asia/Tokyo"}, /* First day = 1, Minimum day = 1 */ - {"iw", "IL", "Asia/Jerusalem"}, /* First day = 1, Minimum day = 1 */ - {"hi", "IN", "Asia/Jakarta"}, /* First day = 1, Minimum day = 1 */ - {"en", "GB", "Europe/London"}, /* First day = 2, Minimum day = 1 */ - {"en", "GB", "GMT"}, /* First day = 2, Minimum day = 1 */ - {"de", "DE", "Europe/Berlin"}, /* First day = 2, Minimum day = 4 */ - {"ar", "EG", "Africa/Cairo"}, /* First day = 7, Minimum day = 1 */ - }; + {"en", "US", "US/Pacific"}, /* First day = 1, Minimum day = 1 */ + {"en", "US", "America/Anchorage"}, /* First day = 1, Minimum day = 1 */ + {"en", "TO", "Pacific/Tongatapu"}, /* First day = 1, Minimum day = 1 */ + {"en", "MH", "Pacific/Majuro"}, /* First day = 1, Minimum day = 1 */ + {"ja", "JP", "Asia/Tokyo"}, /* First day = 1, Minimum day = 1 */ + {"iw", "IL", "Asia/Jerusalem"}, /* First day = 1, Minimum day = 1 */ + {"hi", "IN", "Asia/Jakarta"}, /* First day = 1, Minimum day = 1 */ + {"en", "GB", "Europe/London"}, /* First day = 2, Minimum day = 1 */ + {"en", "GB", "GMT"}, /* First day = 2, Minimum day = 1 */ + {"de", "DE", "Europe/Berlin"}, /* First day = 2, Minimum day = 4 */ + {"ar", "EG", "Africa/Cairo"}}; /* First day = 7, Minimum day = 1 */ int[][] goldenData = { - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, -28800000, 0}, - {1, 1969, 11, 1, 5, 31, 365, 4, 5, 1, 11, 23, 0, 0, 0, -36000000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 46800000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 43200000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 32400000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 7200000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 25200000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 1, 1, 0, 0, 0, 3600000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 3600000, 0}, - {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 7200000, 0}, - }; + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, -28800000, 0}, + {1, 1969, 11, 1, 5, 31, 365, 4, 5, 1, 11, 23, 0, 0, 0, -36000000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 46800000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 43200000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 32400000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 7200000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 25200000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 1, 1, 0, 0, 0, 3600000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 0, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 3600000, 0}, + {1, 1970, 0, 1, 1, 1, 1, 5, 1, 0, 0, 0, 0, 0, 0, 7200000, 0}}; Locale savedLocale = Locale.getDefault(); TimeZone savedTimeZone = TimeZone.getDefault(); @@ -927,19 +986,18 @@ boolean err = false; for (int i = 0; i < calendarFieldNames.length; ++i) { if ((val = c.get(i)) != EPOCH_FIELDS[i]) { - errln("Wrong value: " + val + - " for field(" + calendarFieldNames[i] + - "), expected: " + EPOCH_FIELDS[i]); + errln("Wrong value: " + val + + " for field(" + calendarFieldNames[i] + + "), expected: " + EPOCH_FIELDS[i]); err = true; } } if (err) { - errln("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + - "\n\tLocale=" + l + "\n\tCalendar=" + c); + errln("Failed: \n\tDate=" + d + "\n\tTimeZone=" + z + + "\n\tLocale=" + l + "\n\tCalendar=" + c); } } - } - finally { + } finally { Locale.setDefault(savedLocale); TimeZone.setDefault(savedTimeZone); } @@ -948,125 +1006,146 @@ // Verify that as you add days to the calendar (e.g., 24 day periods), // the day of the week shifts in the expected pattern. public void TestDOWProgression() { - Calendar cal = - new GregorianCalendar(1972, Calendar.OCTOBER, 26); + Calendar cal + = new GregorianCalendar(1972, OCTOBER, 26); marchByDelta(cal, 24); // Last parameter must be != 0 modulo 7 } // Supply a delta which is not a multiple of 7. void marchByDelta(Calendar cal, int delta) { - Calendar cur = (Calendar)cal.clone(); - int initialDOW = cur.get(Calendar.DAY_OF_WEEK); + Calendar cur = (Calendar) cal.clone(); + int initialDOW = cur.get(DAY_OF_WEEK); int DOW, newDOW = initialDOW; do { DOW = newDOW; logln("DOW = " + DOW + " " + cur.getTime()); - cur.add(Calendar.DAY_OF_WEEK, delta); - newDOW = cur.get(Calendar.DAY_OF_WEEK); + cur.add(DAY_OF_WEEK, delta); + newDOW = cur.get(DAY_OF_WEEK); int expectedDOW = 1 + (DOW + delta - 1) % 7; if (newDOW != expectedDOW) { - errln("Day of week should be " + expectedDOW + - " instead of " + newDOW + " on " + cur.getTime()); + errln("Day of week should be " + expectedDOW + + " instead of " + newDOW + " on " + cur.getTime()); return; } - } - while (newDOW != initialDOW); + } while (newDOW != initialDOW); } public void TestActualMinMax() { - Calendar cal = new GregorianCalendar(1967, Calendar.MARCH, 10); - cal.setFirstDayOfWeek(Calendar.SUNDAY); + Calendar cal = new GregorianCalendar(1967, MARCH, 10); + cal.setFirstDayOfWeek(SUNDAY); cal.setMinimalDaysInFirstWeek(3); - if (cal.getActualMinimum(Calendar.DAY_OF_MONTH) != 1) - errln("Actual minimum date for 3/10/1967 should have been 1; got " + - cal.getActualMinimum(Calendar.DAY_OF_MONTH)); - if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) != 31) - errln("Actual maximum date for 3/10/1967 should have been 31; got " + - cal.getActualMaximum(Calendar.DAY_OF_MONTH)); + if (cal.getActualMinimum(DAY_OF_MONTH) != 1) { + errln("Actual minimum date for 3/10/1967 should have been 1; got " + + cal.getActualMinimum(DAY_OF_MONTH)); + } + if (cal.getActualMaximum(DAY_OF_MONTH) != 31) { + errln("Actual maximum date for 3/10/1967 should have been 31; got " + + cal.getActualMaximum(DAY_OF_MONTH)); + } - cal.set(Calendar.MONTH, Calendar.FEBRUARY); - if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) != 28) - errln("Actual maximum date for 2/10/1967 should have been 28; got " + - cal.getActualMaximum(Calendar.DAY_OF_MONTH)); - if (cal.getActualMaximum(Calendar.DAY_OF_YEAR) != 365) - errln("Number of days in 1967 should have been 365; got " + - cal.getActualMaximum(Calendar.DAY_OF_YEAR)); + cal.set(MONTH, FEBRUARY); + if (cal.getActualMaximum(DAY_OF_MONTH) != 28) { + errln("Actual maximum date for 2/10/1967 should have been 28; got " + + cal.getActualMaximum(DAY_OF_MONTH)); + } + if (cal.getActualMaximum(DAY_OF_YEAR) != 365) { + errln("Number of days in 1967 should have been 365; got " + + cal.getActualMaximum(DAY_OF_YEAR)); + } - cal.set(Calendar.YEAR, 1968); - if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) != 29) - errln("Actual maximum date for 2/10/1968 should have been 29; got " + - cal.getActualMaximum(Calendar.DAY_OF_MONTH)); - if (cal.getActualMaximum(Calendar.DAY_OF_YEAR) != 366) - errln("Number of days in 1968 should have been 366; got " + - cal.getActualMaximum(Calendar.DAY_OF_YEAR)); + cal.set(YEAR, 1968); + if (cal.getActualMaximum(DAY_OF_MONTH) != 29) { + errln("Actual maximum date for 2/10/1968 should have been 29; got " + + cal.getActualMaximum(DAY_OF_MONTH)); + } + if (cal.getActualMaximum(DAY_OF_YEAR) != 366) { + errln("Number of days in 1968 should have been 366; got " + + cal.getActualMaximum(DAY_OF_YEAR)); + } // Using week settings of SUNDAY/3 (see above) - if (cal.getActualMaximum(Calendar.WEEK_OF_YEAR) != 52) - errln("Number of weeks in 1968 should have been 52; got " + - cal.getActualMaximum(Calendar.WEEK_OF_YEAR)); + if (cal.getActualMaximum(WEEK_OF_YEAR) != 52) { + errln("Number of weeks in 1968 should have been 52; got " + + cal.getActualMaximum(WEEK_OF_YEAR)); + } - cal.set(Calendar.YEAR, 1976); + cal.set(YEAR, 1976); // Using week settings of SUNDAY/3 (see above) - if (cal.getActualMaximum(Calendar.WEEK_OF_YEAR) != 53) - errln("Number of weeks in 1976 should have been 53; got " + - cal.getActualMaximum(Calendar.WEEK_OF_YEAR)); + if (cal.getActualMaximum(WEEK_OF_YEAR) != 53) { + errln("Number of weeks in 1976 should have been 53; got " + + cal.getActualMaximum(WEEK_OF_YEAR)); + } } public void TestRoll() { - Calendar cal = new GregorianCalendar(1997, Calendar.JANUARY, 31); + Calendar cal = new GregorianCalendar(1997, JANUARY, 31); - int[] dayValues = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31 }; + int[] dayValues = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31}; for (int i = 0; i < dayValues.length; i++) { - Calendar cal2 = (Calendar)cal.clone(); - cal2.roll(Calendar.MONTH, i); - if (cal2.get(Calendar.DAY_OF_MONTH) != dayValues[i]) + Calendar cal2 = (Calendar) cal.clone(); + cal2.roll(MONTH, i); + if (cal2.get(DAY_OF_MONTH) != dayValues[i]) { errln("Rolling the month in 1/31/1997 up by " + i + " should have yielded " - + ((i + 1) % 12) + "/" + dayValues[i] + "/1997, but actually yielded " - + ((i + 1) % 12) + "/" + cal2.get(Calendar.DAY_OF_MONTH) + "/1997."); + + ((i + 1) % 12) + "/" + dayValues[i] + "/1997, but actually yielded " + + ((i + 1) % 12) + "/" + cal2.get(DAY_OF_MONTH) + "/1997."); + } } - cal.set(1996, Calendar.FEBRUARY, 29); + cal.set(1996, FEBRUARY, 29); - int[] monthValues = { 1, 2, 2, 2, 1, 2, 2, 2, 1, 2 }; - int[] dayValues2 = { 29, 1, 1, 1, 29, 1, 1, 1, 29, 1 }; + int[] monthValues = {1, 2, 2, 2, 1, 2, 2, 2, 1, 2}; + int[] dayValues2 = {29, 1, 1, 1, 29, 1, 1, 1, 29, 1}; for (int i = 0; i < dayValues2.length; i++) { - Calendar cal2 = (Calendar)cal.clone(); - cal2.roll(Calendar.YEAR, i); - if (cal2.get(Calendar.DAY_OF_MONTH) != dayValues2[i] || cal2.get(Calendar.MONTH) - != monthValues[i]) + Calendar cal2 = (Calendar) cal.clone(); + cal2.roll(YEAR, i); + if (cal2.get(DAY_OF_MONTH) != dayValues2[i] || cal2.get(MONTH) + != monthValues[i]) { errln("Rolling the year in 2/29/1996 up by " + i + " should have yielded " - + (monthValues[i] + 1) + "/" + dayValues2[i] + "/" - + (1996 + i) + ", but actually yielded " - + (cal2.get(Calendar.MONTH) + 1) + "/" + - cal2.get(Calendar.DAY_OF_MONTH) + "/" + (1996 + i) + "."); + + (monthValues[i] + 1) + "/" + dayValues2[i] + "/" + + (1996 + i) + ", but actually yielded " + + (cal2.get(MONTH) + 1) + "/" + + cal2.get(DAY_OF_MONTH) + "/" + (1996 + i) + "."); + } } // Test rolling hour of day - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.roll(Calendar.HOUR_OF_DAY, -2); - int f = cal.get(Calendar.HOUR_OF_DAY); - if (f != 22) errln("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); - cal.roll(Calendar.HOUR_OF_DAY, 5); - f = cal.get(Calendar.HOUR_OF_DAY); - if (f != 3) errln("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); - cal.roll(Calendar.HOUR_OF_DAY, 21); - f = cal.get(Calendar.HOUR_OF_DAY); - if (f != 0) errln("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); + cal.set(HOUR_OF_DAY, 0); + cal.roll(HOUR_OF_DAY, -2); + int f = cal.get(HOUR_OF_DAY); + if (f != 22) { + errln("Rolling HOUR_OF_DAY=0 delta=-2 gave " + f + " Wanted 22"); + } + cal.roll(HOUR_OF_DAY, 5); + f = cal.get(HOUR_OF_DAY); + if (f != 3) { + errln("Rolling HOUR_OF_DAY=22 delta=5 gave " + f + " Wanted 3"); + } + cal.roll(HOUR_OF_DAY, 21); + f = cal.get(HOUR_OF_DAY); + if (f != 0) { + errln("Rolling HOUR_OF_DAY=3 delta=21 gave " + f + " Wanted 0"); + } // Test rolling hour - cal.set(Calendar.HOUR_OF_DAY, 0); - cal.roll(Calendar.HOUR, -2); - f = cal.get(Calendar.HOUR); - if (f != 10) errln("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); - cal.roll(Calendar.HOUR, 5); - f = cal.get(Calendar.HOUR); - if (f != 3) errln("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); - cal.roll(Calendar.HOUR, 9); - f = cal.get(Calendar.HOUR); - if (f != 0) errln("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); + cal.set(HOUR_OF_DAY, 0); + cal.roll(HOUR, -2); + f = cal.get(HOUR); + if (f != 10) { + errln("Rolling HOUR=0 delta=-2 gave " + f + " Wanted 10"); + } + cal.roll(HOUR, 5); + f = cal.get(HOUR); + if (f != 3) { + errln("Rolling HOUR=10 delta=5 gave " + f + " Wanted 3"); + } + cal.roll(HOUR, 9); + f = cal.get(HOUR); + if (f != 0) { + errln("Rolling HOUR=3 delta=9 gave " + f + " Wanted 0"); + } } /* @@ -1081,19 +1160,18 @@ TimeZone.setDefault(TimeZone.getTimeZone("PST")); Calendar cal = Calendar.getInstance(); - cal.set(Calendar.YEAR, 2001); - cal.set(Calendar.MONTH, Calendar.OCTOBER); - cal.set(Calendar.WEEK_OF_YEAR, 4); - cal.set(Calendar.DAY_OF_WEEK, 2); + cal.set(YEAR, 2001); + cal.set(MONTH, OCTOBER); + cal.set(WEEK_OF_YEAR, 4); + cal.set(DAY_OF_WEEK, 2); - if (cal.get(Calendar.YEAR) != 2001 || - cal.get(Calendar.MONTH) != Calendar.JANUARY || - cal.get(Calendar.DATE) != 22 || - cal.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { + if (cal.get(YEAR) != 2001 + || cal.get(MONTH) != JANUARY + || cal.get(DATE) != 22 + || cal.get(DAY_OF_WEEK) != MONDAY) { errln("Failed : got " + cal.getTime() + ", expected Mon Jan 22, 2001"); } - } - finally { + } finally { Locale.setDefault(savedLocale); TimeZone.setDefault(savedTimeZone); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/CalendarTypeTest.java --- a/jdk/test/java/util/Calendar/CalendarTypeTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/CalendarTypeTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -27,9 +27,13 @@ * @summary Unit test for calendar types */ -import java.util.*; +import java.util.Calendar; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.Set; public class CalendarTypeTest { + // Calendar types supported in JRE static Locale[] locales = new Locale[] { Locale.US, @@ -37,23 +41,20 @@ new Locale("th", "TH"), Locale.forLanguageTag("en-US-u-ca-buddhist"), new Locale("ja", "JP", "JP"), - Locale.forLanguageTag("en-US-u-ca-japanese"), - }; + Locale.forLanguageTag("en-US-u-ca-japanese")}; static final String[] TYPES = new String[] { "gregory", "buddhist", - "japanese", - }; + "japanese"}; static final String[] ALIASES = new String[] { "gregorian", - "iso8601", - }; + "iso8601"}; public static void main(String[] args) { for (int i = 0; i < locales.length; i++) { Calendar cal = Calendar.getInstance(locales[i]); String type = cal.getCalendarType(); - checkValue("bad calendar type", type, TYPES[i/2]); + checkValue("bad calendar type", type, TYPES[i / 2]); } GregorianCalendar gcal = new GregorianCalendar(); @@ -88,10 +89,13 @@ } } + @SuppressWarnings("serial") private static class Gregorian extends GregorianCalendar { } + @SuppressWarnings("serial") private static class Koyomi extends Calendar { + @Override protected void computeTime() { throw new UnsupportedOperationException("Not supported yet."); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/FieldStateTest.java --- a/jdk/test/java/util/Calendar/FieldStateTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/FieldStateTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -144,8 +144,11 @@ } logln("Set day of week to SUNDAY and date to 2003/10/31. " - + "Then, getTime and set week of year to 43."); - cal.setTime(new Date(2003-1990, OCTOBER, 31)); + + "Then, getTime and set week of year to 43."); + + @SuppressWarnings("deprecation") + Date d = new Date(2003 - 1990, OCTOBER, 31); + cal.setTime(d); cal.set(DAY_OF_WEEK, SUNDAY); cal.set(2003, OCTOBER, 31); // 2003/10/31 is Friday. cal.set(ZONE_OFFSET, 0); @@ -166,8 +169,8 @@ * 4916815: REGRESSION: Problem with java.util.Calendar VM 1.4.2-b28 */ public void Test4916815() { - logln("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. "+ - "Set dayofweek to Sunday which should be 2003/9/21."); + logln("Set date to 2003/9/26 (Fri). Roll to Aug and back to Sep. " + + "Set dayofweek to Sunday which should be 2003/9/21."); Koyomi cal = new Koyomi(); cal.clear(); // 2003/9/26 (Fri) @@ -192,17 +195,17 @@ cal.clear(); cal.set(YEAR, 2004); cal.set(WEEK_OF_YEAR, 1); - checkDate(cal, SUNDAY, 2003, DECEMBER, 28); - checkDate(cal, MONDAY, 2003, DECEMBER, 29); - checkDate(cal, TUESDAY, 2003, DECEMBER, 30); + checkDate(cal, SUNDAY, 2003, DECEMBER, 28); + checkDate(cal, MONDAY, 2003, DECEMBER, 29); + checkDate(cal, TUESDAY, 2003, DECEMBER, 30); checkDate(cal, WEDNESDAY, 2003, DECEMBER, 31); - checkDate(cal, THURSDAY, 2004, JANUARY, 1); - checkDate(cal, FRIDAY, 2004, JANUARY, 2); - checkDate(cal, SATURDAY, 2004, JANUARY, 3); + checkDate(cal, THURSDAY, 2004, JANUARY, 1); + checkDate(cal, FRIDAY, 2004, JANUARY, 2); + checkDate(cal, SATURDAY, 2004, JANUARY, 3); } private void checkDate(Koyomi cal, int dayOfWeek, - int expectedYear, int expectedMonth, int expectedDayOfMonth) { + int expectedYear, int expectedMonth, int expectedDayOfMonth) { cal.set(DAY_OF_WEEK, dayOfWeek); cal.getTime(); if (!cal.checkInternalDate(expectedYear, expectedMonth, expectedDayOfMonth, dayOfWeek)) { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/GregorianCutoverTest.java --- a/jdk/test/java/util/Calendar/GregorianCutoverTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/GregorianCutoverTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -76,7 +76,9 @@ checkContinuity(cal, WEEK_OF_YEAR); // Use large date (year >= 50000) - cal.setGregorianChange(new Date(50000-1900, JANUARY, 20)); + @SuppressWarnings("deprecation") + Date d = new Date(50000 - 1900, JANUARY, 20); + cal.setGregorianChange(d); cal.set(49998, JANUARY, 1); checkContinuity(cal, DAY_OF_YEAR); checkContinuity(cal, WEEK_OF_YEAR); @@ -124,7 +126,9 @@ // should handle the gap between 1969/12/22 (Julian) to 1970/1/5 (Gregorian) logln("Cutover date is 1970/1/5"); - cal.setGregorianChange(new Date(1970-1900, JANUARY, 5)); + @SuppressWarnings("deprecation") + Date d1 = new Date(1970 - 1900, JANUARY, 5); + cal.setGregorianChange(d1); cal.set(ERA, AD); cal.set(YEAR, 1970); logln(" Set DAY_OF_YEAR to the 28th day of 1970"); @@ -203,16 +207,17 @@ public void Test4928615() { Koyomi cal = new Koyomi(); logln("Today is 2003/10/1 Gregorian."); - Date x = new Date(2003-1900, 10-1, 1); + @SuppressWarnings("deprecation") + Date x = new Date(2003 - 1900, 10 - 1, 1); cal.setTime(x); logln(" Changing the cutover date to yesterday..."); - cal.setGregorianChange(new Date(x.getTime() - (24*3600*1000))); + cal.setGregorianChange(new Date(x.getTime() - (24 * 3600 * 1000))); if (!cal.checkDate(2003, OCTOBER, 1)) { errln(" " + cal.getMessage()); } logln(" Changing the cutover date to tomorrow..."); - cal.setGregorianChange(new Date(x.getTime() + (24*3600*1000))); + cal.setGregorianChange(new Date(x.getTime() + (24 * 3600 * 1000))); if (!cal.checkDate(2003, SEPTEMBER, 18)) { errln(" " + cal.getMessage()); } @@ -225,11 +230,11 @@ Koyomi cal = new Koyomi(); Koyomi cal2 = (Koyomi) cal.clone(); logln("getLeastMaximum should handle cutover year.\n" - +" default cutover date"); - if (!cal.checkLeastMaximum(DAY_OF_YEAR, 365-10)) { + + " default cutover date"); + if (!cal.checkLeastMaximum(DAY_OF_YEAR, 365 - 10)) { errln(" " + cal.getMessage()); } - if (!cal.checkLeastMaximum(WEEK_OF_YEAR, 52-((10+6)/7))) { + if (!cal.checkLeastMaximum(WEEK_OF_YEAR, 52 - ((10 + 6) / 7))) { errln(" " + cal.getMessage()); } // Corrected for 4956232 @@ -261,7 +266,9 @@ cal = new Koyomi(); logln("Change the cutover date to 1970/1/5."); - cal.setGregorianChange(new Date(1970-1900, 0, 5)); + @SuppressWarnings("deprecation") + Date d = new Date(1970 - 1900, 0, 5); + cal.setGregorianChange(d); if (!cal.checkLeastMaximum(DAY_OF_YEAR, 356)) { errln(" " + cal.getMessage()); } @@ -287,15 +294,15 @@ int hour = 13865672; Koyomi gc1 = new Koyomi(); gc1.clear(); - gc1.set(1, gc1.JANUARY, 1, 0, 0, 0); - gc1.set(gc1.HOUR_OF_DAY, hour); - if (!gc1.checkDate(1582, gc1.OCTOBER, 4)) { + gc1.set(1, JANUARY, 1, 0, 0, 0); + gc1.set(HOUR_OF_DAY, hour); + if (!gc1.checkDate(1582, OCTOBER, 4)) { errln("test case 1: " + gc1.getMessage()); } gc1.clear(); - gc1.set(1, gc1.JANUARY, 1, 0, 0, 0); - gc1.set(gc1.HOUR_OF_DAY, hour + 24); - if (!gc1.checkDate(1582, gc1.OCTOBER, 15)) { + gc1.set(1, JANUARY, 1, 0, 0, 0); + gc1.set(HOUR_OF_DAY, hour + 24); + if (!gc1.checkDate(1582, OCTOBER, 15)) { errln("test case 2: " + gc1.getMessage()); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/JavatimeTest.java --- a/jdk/test/java/util/Calendar/JavatimeTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/JavatimeTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, 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 @@ -28,16 +28,16 @@ * @key randomness */ +import java.time.Instant; +import java.time.LocalDateTime; +import java.time.ZonedDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Random; import java.util.TimeZone; -import java.time.Instant; -import java.time.LocalDateTime; -import java.time.ZonedDateTime; -import java.time.ZoneId; -import java.time.ZoneOffset; public class JavatimeTest { @@ -46,10 +46,11 @@ public static void main(String[] args) throws Throwable { int N = 10000; + @SuppressWarnings("deprecation") long t1970 = new java.util.Date(70, 0, 01).getTime(); Random r = new Random(); for (int i = 0; i < N; i++) { - int days = r.nextInt(50) * 365 + r.nextInt(365); + int days = r.nextInt(50) * 365 + r.nextInt(365); long secs = t1970 + days * 86400 + r.nextInt(86400); int nanos = r.nextInt(NANOS_PER_SECOND); int nanos_ms = nanos / 1000000 * 1000000; // millis precision @@ -61,15 +62,15 @@ ///////////// java.util.Date ///////////////////////// Date jud = new java.util.Date(millis); Instant inst0 = jud.toInstant(); - if (jud.getTime() != inst0.toEpochMilli() || - !jud.equals(Date.from(inst0))) { + if (jud.getTime() != inst0.toEpochMilli() + || !jud.equals(Date.from(inst0))) { System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt); throw new RuntimeException("FAILED: j.u.d -> instant -> j.u.d"); } // roundtrip only with millis precision Date jud0 = Date.from(inst_ms); - if (jud0.getTime() != inst_ms.toEpochMilli() || - !inst_ms.equals(jud0.toInstant())) { + if (jud0.getTime() != inst_ms.toEpochMilli() + || !inst_ms.equals(jud0.toInstant())) { System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt); throw new RuntimeException("FAILED: instant -> j.u.d -> instant"); } @@ -82,8 +83,8 @@ cal.setMinimalDaysInFirstWeek(4); cal.setTimeInMillis(millis); ZonedDateTime zdt0 = cal.toZonedDateTime(); - if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() || - !cal.equals(GregorianCalendar.from(zdt0))) { + if (cal.getTimeInMillis() != zdt0.toInstant().toEpochMilli() + || !cal.equals(GregorianCalendar.from(zdt0))) { System.out.println("cal:" + cal); System.out.println("zdt:" + zdt0); System.out.println("calNew:" + GregorianCalendar.from(zdt0)); @@ -97,8 +98,8 @@ } ZonedDateTime zdt = ZonedDateTime.of(ldt_ms, ZoneId.systemDefault()); GregorianCalendar cal0 = GregorianCalendar.from(zdt); - if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() || - !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) { + if (zdt.toInstant().toEpochMilli() != cal0.getTimeInMillis() + || !zdt.equals(GregorianCalendar.from(zdt).toZonedDateTime())) { System.out.printf("ms: %16d ns: %10d ldt:[%s]%n", millis, nanos, ldt); throw new RuntimeException("FAILED: zdt -> gcal -> zdt"); } @@ -107,12 +108,12 @@ ///////////// java.util.TimeZone ///////////////////////// for (String zidStr : TimeZone.getAvailableIDs()) { // TBD: tzdt intergration - if (zidStr.startsWith("SystemV") || - zidStr.contains("Riyadh8") || - zidStr.equals("US/Pacific-New") || - zidStr.equals("EST") || - zidStr.equals("HST") || - zidStr.equals("MST")) { + if (zidStr.startsWith("SystemV") + || zidStr.contains("Riyadh8") + || zidStr.equals("US/Pacific-New") + || zidStr.equals("EST") + || zidStr.equals("HST") + || zidStr.equals("MST")) { continue; } ZoneId zid = ZoneId.of(zidStr, ZoneId.SHORT_IDS); @@ -121,9 +122,9 @@ } TimeZone tz = TimeZone.getTimeZone(zidStr); // no round-trip for alias and "GMT" - if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) && - !ZoneId.SHORT_IDS.containsKey(zidStr) && - !zidStr.startsWith("GMT")) { + if (!tz.equals(TimeZone.getTimeZone(tz.toZoneId())) + && !ZoneId.SHORT_IDS.containsKey(zidStr) + && !zidStr.startsWith("GMT")) { throw new RuntimeException("FAILED: tz -> zid -> tz :" + zidStr); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/Koyomi.java --- a/jdk/test/java/util/Calendar/Koyomi.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/Koyomi.java Wed Jul 05 22:30:52 2017 +0200 @@ -21,8 +21,6 @@ * questions. */ -import static java.util.Calendar.*; - import java.util.GregorianCalendar; import java.util.Locale; import java.util.TimeZone; @@ -30,7 +28,9 @@ /** * GregorianCalendar subclass for testing. */ +@SuppressWarnings("serial") public class Koyomi extends GregorianCalendar { + static final String[] FIELD_NAMES = { "ERA", "YEAR", "MONTH", "WEEK_OF_YEAR", "WEEK_OF_MONTH", "DAY_OF_MONTH", "DAY_OF_YEAR", "DAY_OF_WEEK", "DAY_OF_WEEK_IN_MONTH", "AM_PM", "HOUR", @@ -78,7 +78,7 @@ StringBuilder sb = new StringBuilder(); sb.append(internalGet(ERA) == 0 ? "BCE " : ""); sb.append(internalGet(YEAR)).append('-'); - sb.append(internalGet(MONTH)+1).append('-'); + sb.append(internalGet(MONTH) + 1).append('-'); sb.append(internalGet(DAY_OF_MONTH)); return sb.toString(); } @@ -98,7 +98,7 @@ sb.append(ms); int offset = internalGet(ZONE_OFFSET) + internalGet(DST_OFFSET); offset /= 60000; - offset = (offset/60) * 100 + (offset%60); + offset = (offset / 60) * 100 + (offset % 60); if (offset >= 0) { sb.append('+'); } else { @@ -187,8 +187,8 @@ boolean checkActualMaximum(int field, int expectedValue) { int val; if ((val = getActualMaximum(field)) != expectedValue) { - appendMessage("getActualMaximum("+FIELD_NAMES[field]+"): got " + val - + " expected " + expectedValue); + appendMessage("getActualMaximum(" + FIELD_NAMES[field] + "): got " + val + + " expected " + expectedValue); } return getStatus(); } @@ -196,8 +196,8 @@ boolean checkLeastMaximum(int field, int expectedValue) { int val; if ((val = getLeastMaximum(field)) != expectedValue) { - appendMessage("getLeastMaximum("+FIELD_NAMES[field]+"): got " + val - + " expected " + expectedValue); + appendMessage("getLeastMaximum(" + FIELD_NAMES[field] + "): got " + val + + " expected " + expectedValue); } return getStatus(); } @@ -205,8 +205,8 @@ boolean checkActualMinimum(int field, int expectedValue) { int val; if ((val = getActualMinimum(field)) != expectedValue) { - appendMessage("getActualMinimum("+FIELD_NAMES[field]+"): got " + val - + " expected " + expectedValue); + appendMessage("getActualMinimum(" + FIELD_NAMES[field] + "): got " + val + + " expected " + expectedValue); } return getStatus(); } @@ -214,8 +214,8 @@ boolean checkGreatestMinimum(int field, int expectedValue) { int val; if ((val = getGreatestMinimum(field)) != expectedValue) { - appendMessage("getGreatestMinimum("+FIELD_NAMES[field]+"): got " + val - + " expected " + expectedValue); + appendMessage("getGreatestMinimum(" + FIELD_NAMES[field] + "): got " + val + + " expected " + expectedValue); } return getStatus(); } @@ -238,7 +238,7 @@ } boolean checkDateTime(int year, int month, int dayOfMonth, - int hourOfDay, int minute, int second, int ms) { + int hourOfDay, int minute, int second, int ms) { initTest(); checkFieldValue(YEAR, year); checkFieldValue(MONTH, month); @@ -270,8 +270,8 @@ boolean checkFieldValue(int field, int expectedValue) { int val; if ((val = get(field)) != expectedValue) { - appendMessage("get(" + FIELD_NAMES[field] + "): got " + val + - ", expected " + expectedValue + "; "); + appendMessage("get(" + FIELD_NAMES[field] + "): got " + val + + ", expected " + expectedValue + "; "); return false; } return true; @@ -280,8 +280,8 @@ boolean checkInternalFieldValue(int field, int expectedValue) { int val; if ((val = internalGet(field)) != expectedValue) { - appendMessage("internalGet(" + FIELD_NAMES[field] + "): got " + val + - ", expected " + expectedValue + "; "); + appendMessage("internalGet(" + FIELD_NAMES[field] + "): got " + val + + ", expected " + expectedValue + "; "); return false; } return true; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/NonLenientTest.java --- a/jdk/test/java/util/Calendar/NonLenientTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/NonLenientTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -28,7 +28,10 @@ * @library /java/text/testlib */ -import java.util.*; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; import static java.util.Calendar.*; @@ -129,7 +132,6 @@ validate(cal, "6th Sunday in Jan 2003"); } - /** * 4726030: GregorianCalendar doesn't check invalid dates in non-lenient */ @@ -146,34 +148,34 @@ */ public void Test4147269() { Koyomi calendar = getNonLenient(); - Date date = (new GregorianCalendar(1996,0,3)).getTime(); + Date date = (new GregorianCalendar(1996, 0, 3)).getTime(); - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { + for (int field = 0; field < FIELD_COUNT; field++) { calendar.setTime(date); int max = calendar.getActualMaximum(field); - int value = max+1; + int value = max + 1; calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + calendar.getFieldName(field) - + "\n\tdate before: " + date - + "\n\tdate after: " + calendar.getTime() - + "\n\tvalue: " + value + " (max = " + max +")"); + errln("Test failed with field " + Koyomi.getFieldName(field) + + "\n\tdate before: " + date + + "\n\tdate after: " + calendar.getTime() + + "\n\tvalue: " + value + " (max = " + max + ")"); } catch (IllegalArgumentException e) { } } - for (int field = 0; field < Calendar.FIELD_COUNT; field++) { + for (int field = 0; field < FIELD_COUNT; field++) { calendar.setTime(date); int min = calendar.getActualMinimum(field); - int value = min-1; + int value = min - 1; calendar.set(field, value); try { calendar.computeTime(); // call method under test - errln("Test failed with field " + calendar.getFieldName(field) - + "\n\tdate before: " + date - + "\n\tdate after: " + calendar.getTime() - + "\n\tvalue: " + value + " (min = " + min +")"); + errln("Test failed with field " + Koyomi.getFieldName(field) + + "\n\tdate before: " + date + + "\n\tdate after: " + calendar.getTime() + + "\n\tvalue: " + value + " (min = " + min + ")"); } catch (IllegalArgumentException e) { } } @@ -194,17 +196,17 @@ // In non-lenient, calendar field values that have beeb set by // user shouldn't be modified. int[] afterFields = cal.getFields(); - for (int i = 0; i < Calendar.FIELD_COUNT; i++) { + for (int i = 0; i < FIELD_COUNT; i++) { if (cal.isSet(i) && originalFields[i] != afterFields[i]) { - errln(" complete() modified fields[" + cal.getFieldName(i) + "] got " - + afterFields[i] + ", expected " + originalFields[i]); + errln(" complete() modified fields[" + Koyomi.getFieldName(i) + "] got " + + afterFields[i] + ", expected " + originalFields[i]); } } // In non-lenient, set state of fields shouldn't be modified. int afterSetFields = cal.getSetStateFields(); if (setFields != afterSetFields) { errln(" complate() modified set states: before 0x" + toHex(setFields) - + ", after 0x"+ toHex(afterSetFields)); + + ", after 0x" + toHex(afterSetFields)); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/ZoneOffsets.java --- a/jdk/test/java/util/Calendar/ZoneOffsets.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/ZoneOffsets.java Wed Jul 05 22:30:52 2017 +0200 @@ -28,12 +28,20 @@ * taken into account for time calculations. */ -import java.util.*; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + import static java.util.GregorianCalendar.*; public class ZoneOffsets { + // This TimeZone always returns the dstOffset value. + @SuppressWarnings("serial") private static class TestTimeZone extends TimeZone { + private int gmtOffset; private int dstOffset; @@ -44,7 +52,7 @@ } public int getOffset(int era, int year, int month, int day, - int dayOfWeek, int milliseconds) { + int dayOfWeek, int milliseconds) { return gmtOffset + dstOffset; } @@ -80,22 +88,20 @@ private static Locale[] locales = { Locale.getDefault(), new Locale("th", "TH"), - new Locale("ja", "JP", "JP"), - }; + new Locale("ja", "JP", "JP")}; private static final int HOUR = 60 * 60 * 1000; private static int[][] offsets = { - { 0, 0 }, - { 0, HOUR }, - { 0, 2 * HOUR }, - { -8 * HOUR, 0 }, - { -8 * HOUR, HOUR }, - { -8 * HOUR, 2 * HOUR }, - { 9 * HOUR, 0 }, - { 9 * HOUR, HOUR }, - { 9 * HOUR, 2 * HOUR }, - }; + {0, 0}, + {0, HOUR}, + {0, 2 * HOUR}, + {-8 * HOUR, 0}, + {-8 * HOUR, HOUR}, + {-8 * HOUR, 2 * HOUR}, + {9 * HOUR, 0}, + {9 * HOUR, HOUR}, + {9 * HOUR, 2 * HOUR}}; public static void main(String[] args) { for (int l = 0; l < locales.length; l++) { @@ -121,17 +127,17 @@ private static void test(Locale loc, int gmtOffset, int dstOffset) { TimeZone tz1 = new TestTimeZone(gmtOffset, - "GMT" + (gmtOffset/HOUR) + "." + (dstOffset/HOUR), - dstOffset); + "GMT" + (gmtOffset / HOUR) + "." + (dstOffset / HOUR), + dstOffset); int someDifferentOffset = gmtOffset + 2 * HOUR; TimeZone tz2 = new TestTimeZone(someDifferentOffset, - "GMT"+ (someDifferentOffset/HOUR) + "." + (dstOffset/HOUR), - dstOffset); + "GMT" + (someDifferentOffset / HOUR) + "." + (dstOffset / HOUR), + dstOffset); int someDifferentDSTOffset = dstOffset == 2 * HOUR ? HOUR : dstOffset + HOUR; TimeZone tz3 = new TestTimeZone(gmtOffset, - "GMT"+ (gmtOffset/HOUR) + "." + (someDifferentDSTOffset/HOUR), - someDifferentDSTOffset); + "GMT" + (gmtOffset / HOUR) + "." + (someDifferentDSTOffset / HOUR), + someDifferentDSTOffset); // cal1 is the base line. Calendar cal1 = Calendar.getInstance(tz1, loc); @@ -225,7 +231,7 @@ private static void error(String msg, Locale loc, Calendar cal2, int gmtOffset, int dstOffset, long t1) { System.err.println(cal2); throw new RuntimeException(msg + ": Locale=" + loc - + ", gmtOffset=" + gmtOffset + ", dstOffset=" + dstOffset - + ", cal1 time=" + t1 + ", cal2 time=" + cal2.getTime().getTime()); + + ", gmtOffset=" + gmtOffset + ", dstOffset=" + dstOffset + + ", cal1 time=" + t1 + ", cal2 time=" + cal2.getTime().getTime()); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/bug4372743.java --- a/jdk/test/java/util/Calendar/bug4372743.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/bug4372743.java Wed Jul 05 22:30:52 2017 +0200 @@ -28,9 +28,8 @@ * @library /java/text/testlib */ -import java.io.*; -import java.util.*; -import java.text.*; +import java.util.GregorianCalendar; +import java.util.TimeZone; import static java.util.GregorianCalendar.*; @@ -41,51 +40,50 @@ } private int[][] data = { - {AD, 2, MARCH}, - {AD, 2, FEBRUARY}, - {AD, 2, JANUARY}, - {AD, 1, DECEMBER}, - {AD, 1, NOVEMBER}, - {AD, 1, OCTOBER}, - {AD, 1, SEPTEMBER}, - {AD, 1, AUGUST}, - {AD, 1, JULY}, - {AD, 1, JUNE}, - {AD, 1, MAY}, - {AD, 1, APRIL}, - {AD, 1, MARCH}, - {AD, 1, FEBRUARY}, - {AD, 1, JANUARY}, - {BC, 1, DECEMBER}, - {BC, 1, NOVEMBER}, - {BC, 1, OCTOBER}, - {BC, 1, SEPTEMBER}, - {BC, 1, AUGUST}, - {BC, 1, JULY}, - {BC, 1, JUNE}, - {BC, 1, MAY}, - {BC, 1, APRIL}, - {BC, 1, MARCH}, - {BC, 1, FEBRUARY}, - {BC, 1, JANUARY}, - {BC, 2, DECEMBER}, - {BC, 2, NOVEMBER}, - {BC, 2, OCTOBER}, - }; + {AD, 2, MARCH}, + {AD, 2, FEBRUARY}, + {AD, 2, JANUARY}, + {AD, 1, DECEMBER}, + {AD, 1, NOVEMBER}, + {AD, 1, OCTOBER}, + {AD, 1, SEPTEMBER}, + {AD, 1, AUGUST}, + {AD, 1, JULY}, + {AD, 1, JUNE}, + {AD, 1, MAY}, + {AD, 1, APRIL}, + {AD, 1, MARCH}, + {AD, 1, FEBRUARY}, + {AD, 1, JANUARY}, + {BC, 1, DECEMBER}, + {BC, 1, NOVEMBER}, + {BC, 1, OCTOBER}, + {BC, 1, SEPTEMBER}, + {BC, 1, AUGUST}, + {BC, 1, JULY}, + {BC, 1, JUNE}, + {BC, 1, MAY}, + {BC, 1, APRIL}, + {BC, 1, MARCH}, + {BC, 1, FEBRUARY}, + {BC, 1, JANUARY}, + {BC, 2, DECEMBER}, + {BC, 2, NOVEMBER}, + {BC, 2, OCTOBER}}; private int tablesize = data.length; private void check(GregorianCalendar gc, int index) { if (gc.get(ERA) != data[index][ERA]) { - errln("Invalid era :" + gc.get(ERA) + - ", expected :" + data[index][ERA]); + errln("Invalid era :" + gc.get(ERA) + + ", expected :" + data[index][ERA]); } if (gc.get(YEAR) != data[index][YEAR]) { - errln("Invalid year :" + gc.get(YEAR) + - ", expected :" + data[index][YEAR]); + errln("Invalid year :" + gc.get(YEAR) + + ", expected :" + data[index][YEAR]); } if (gc.get(MONTH) != data[index][MONTH]) { - errln("Invalid month :" + gc.get(MONTH) + - ", expected :" + data[index][MONTH]); + errln("Invalid month :" + gc.get(MONTH) + + ", expected :" + data[index][MONTH]); } } @@ -97,36 +95,35 @@ TimeZone.setDefault(TimeZone.getTimeZone("PST")); /* Set March 3, A.D. 2 */ - gc = new GregorianCalendar(2, MARCH, 3); + gc = new GregorianCalendar(2, MARCH, 3); for (int i = 0; i < tablesize; i++) { check(gc, i); - gc.add(gc.MONTH, -1); + gc.add(MONTH, -1); } /* Again, Set March 3, A.D. 2 */ - gc = new GregorianCalendar(2, MARCH, 3); - for (int i = 0; i < tablesize; i+=7) { + gc = new GregorianCalendar(2, MARCH, 3); + for (int i = 0; i < tablesize; i += 7) { check(gc, i); - gc.add(gc.MONTH, -7); + gc.add(MONTH, -7); } /* Set March 10, 2 B.C. */ - gc = new GregorianCalendar(2, OCTOBER, 10); - gc.add(gc.YEAR, -3); - for (int i = tablesize -1; i >= 0; i--) { + gc = new GregorianCalendar(2, OCTOBER, 10); + gc.add(YEAR, -3); + for (int i = tablesize - 1; i >= 0; i--) { check(gc, i); - gc.add(gc.MONTH, 1); + gc.add(MONTH, 1); } /* Again, Set March 10, 2 B.C. */ - gc = new GregorianCalendar(2, OCTOBER, 10); - gc.add(gc.YEAR, -3); - for (int i = tablesize -1; i >= 0; i-=8) { + gc = new GregorianCalendar(2, OCTOBER, 10); + gc.add(YEAR, -3); + for (int i = tablesize - 1; i >= 0; i -= 8) { check(gc, i); - gc.add(gc.MONTH, 8); + gc.add(MONTH, 8); } - } - finally { + } finally { TimeZone.setDefault(saveZone); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/bug4401223.java --- a/jdk/test/java/util/Calendar/bug4401223.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/bug4401223.java Wed Jul 05 22:30:52 2017 +0200 @@ -28,7 +28,10 @@ * @library /java/text/testlib */ -import java.util.*; +import java.util.Date; +import java.util.GregorianCalendar; + +import static java.util.GregorianCalendar.*; public class bug4401223 extends IntlTest { @@ -37,11 +40,12 @@ String s = null; try { - Date date = new Date(2000-1900, Calendar.FEBRUARY, 29); + @SuppressWarnings("deprecation") + Date date = new Date(2000 - 1900, FEBRUARY, 29); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); gc.setLenient(false); - gc.set(Calendar.YEAR, 2001); + gc.set(YEAR, 2001); s = "02/29/00 & set(YEAR,2001) = " + gc.getTime().toString(); } catch (Exception ex) { status++; @@ -59,16 +63,17 @@ String s = null; try { - Date date = new Date(2000-1900, Calendar.DECEMBER, 31); + @SuppressWarnings("deprecation") + Date date = new Date(2000 - 1900, DECEMBER, 31); GregorianCalendar gc = new GregorianCalendar(); gc.setTime(date); gc.setLenient(false); - gc.set(Calendar.YEAR, 2001); + gc.set(YEAR, 2001); - if (gc.get(Calendar.YEAR) != 2001 || - gc.get(Calendar.MONTH) != Calendar.DECEMBER || - gc.get(Calendar.DATE) != 31 || - gc.get(Calendar.DAY_OF_YEAR) != 365) { + if (gc.get(YEAR) != 2001 + || gc.get(MONTH) != DECEMBER + || gc.get(DATE) != 31 + || gc.get(DAY_OF_YEAR) != 365) { status++; s = "Wrong Date : 12/31/00 & set(YEAR,2001) ---> " + gc.getTime().toString(); } else { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Calendar/bug4514831.java --- a/jdk/test/java/util/Calendar/bug4514831.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Calendar/bug4514831.java Wed Jul 05 22:30:52 2017 +0200 @@ -27,7 +27,12 @@ * @summary Confirm that GregorianCalendar.roll() works properly during transition from Daylight Saving Time to Standard Time. */ -import java.util.*; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import static java.util.GregorianCalendar.*; + public class bug4514831 { @@ -36,52 +41,52 @@ TimeZone savedTimeZone = TimeZone.getDefault(); boolean err = false; - String golden_data1 ="27-28 28-29 29-30 30-31 31-1 1-2 2-3 "; - String golden_data2 ="27-28 28-29 29-30 30-31 31-25 25-26 26-27 "; - String golden_data3 ="1-8 8-15 15-22 22-29 29-1 1-8 8-15 "; + String golden_data1 = "27-28 28-29 29-30 30-31 31-1 1-2 2-3 "; + String golden_data2 = "27-28 28-29 29-30 30-31 31-25 25-26 26-27 "; + String golden_data3 = "1-8 8-15 15-22 22-29 29-1 1-8 8-15 "; try { Locale.setDefault(Locale.US); TimeZone.setDefault(TimeZone.getTimeZone("US/Pacific")); String test_roll = ""; - GregorianCalendar c_roll = new GregorianCalendar(2001, Calendar.OCTOBER, 27); - for (int i=0; i < 7; i++) { - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + "-"; - c_roll.roll(c_roll.DAY_OF_YEAR, true); - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + " "; + GregorianCalendar c_roll = new GregorianCalendar(2001, OCTOBER, 27); + for (int i = 0; i < 7; i++) { + test_roll += c_roll.get(DAY_OF_MONTH) + "-"; + c_roll.roll(DAY_OF_YEAR, true); + test_roll += c_roll.get(DAY_OF_MONTH) + " "; } if (!test_roll.equals(golden_data1)) { err = true; - System.err.println("Wrong roll(DAY_OF_YEAR) transition: got "+ - test_roll + "expected " + golden_data1); + System.err.println("Wrong roll(DAY_OF_YEAR) transition: got " + + test_roll + "expected " + golden_data1); } test_roll = ""; - c_roll = new GregorianCalendar(2001, Calendar.OCTOBER, 27); - c_roll.setFirstDayOfWeek(Calendar.THURSDAY); - for (int i=0; i < 7; i++) { - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + "-"; - c_roll.roll(c_roll.DAY_OF_WEEK, true); - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + " "; + c_roll = new GregorianCalendar(2001, OCTOBER, 27); + c_roll.setFirstDayOfWeek(THURSDAY); + for (int i = 0; i < 7; i++) { + test_roll += c_roll.get(DAY_OF_MONTH) + "-"; + c_roll.roll(DAY_OF_WEEK, true); + test_roll += c_roll.get(DAY_OF_MONTH) + " "; } if (!test_roll.equals(golden_data2)) { err = true; - System.err.println("Wrong roll(DAY_OF_WEEK) transition: got "+ - test_roll + "expected " + golden_data2); + System.err.println("Wrong roll(DAY_OF_WEEK) transition: got " + + test_roll + "expected " + golden_data2); } test_roll = ""; - c_roll = new GregorianCalendar(2001, Calendar.OCTOBER, 1); - for (int i=0; i < 7; i++) { - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + "-"; - c_roll.roll(c_roll.DAY_OF_WEEK_IN_MONTH, true); - test_roll += c_roll.get(c_roll.DAY_OF_MONTH) + " "; + c_roll = new GregorianCalendar(2001, OCTOBER, 1); + for (int i = 0; i < 7; i++) { + test_roll += c_roll.get(DAY_OF_MONTH) + "-"; + c_roll.roll(DAY_OF_WEEK_IN_MONTH, true); + test_roll += c_roll.get(DAY_OF_MONTH) + " "; } if (!test_roll.equals(golden_data3)) { err = true; - System.err.println("Wrong roll(DAY_OF_WEEK_IN_MONTH) transition: got "+ - test_roll + "expected " + golden_data3); + System.err.println("Wrong roll(DAY_OF_WEEK_IN_MONTH) transition: got " + + test_roll + "expected " + golden_data3); } } finally { Locale.setDefault(savedLocale); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Date/Bug4955000.java --- a/jdk/test/java/util/Date/Bug4955000.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Date/Bug4955000.java Wed Jul 05 22:30:52 2017 +0200 @@ -28,11 +28,15 @@ * same date/time. Both are new implementations in 1.5. */ -import java.util.*; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.TimeZone; + import static java.util.GregorianCalendar.*; @SuppressWarnings("deprecation") public class Bug4955000 { + // Tests for Date.UTC(), derived from JCK // Date.miscTests.Date1025 and Date2015 public static void main(String[] args) { @@ -51,17 +55,17 @@ }; for (int i = 0; i < years1.length; i++) { gc.clear(); - gc.set(years1[i], gc.JANUARY, 1); + gc.set(years1[i], JANUARY, 1); long t = gc.getTimeInMillis(); - long utc = Date.UTC(years1[i] - 1900, 1-1, 1, - 0, 0, 0); // Jan 1 00:00:00 + long utc = Date.UTC(years1[i] - 1900, 1 - 1, 1, + 0, 0, 0); // Jan 1 00:00:00 if (t != utc) { - throw new RuntimeException("t (" + t + ") != utc (" + utc +")"); + throw new RuntimeException("t (" + t + ") != utc (" + utc + ")"); } } // Date2015 - int years[] = { + int[] years = { gc.getGreatestMinimum(YEAR), gc.getGreatestMinimum(YEAR) + 1, -1, @@ -71,47 +75,47 @@ gc.getLeastMaximum(YEAR) }; - int months[] = { + int[] months = { gc.getMinimum(MONTH), gc.getMinimum(MONTH) + 1, gc.getMaximum(MONTH) - 1, gc.getMaximum(MONTH) }; - int dates[] = { + int[] dates = { gc.getMinimum(DAY_OF_MONTH), gc.getMinimum(DAY_OF_MONTH) + 1, gc.getMaximum(DAY_OF_MONTH) - 1, gc.getMaximum(DAY_OF_MONTH) }; - int hs[] = { + int[] hs = { gc.getMinimum(HOUR), gc.getMinimum(HOUR) + 1, gc.getMaximum(HOUR) - 1, gc.getMaximum(HOUR) }; - int ms[] = { + int[] ms = { gc.getMinimum(MINUTE), gc.getMinimum(MINUTE) + 1, gc.getMaximum(MINUTE) - 1, gc.getMaximum(MINUTE) }; - int ss[] = { + int[] ss = { gc.getMinimum(SECOND), gc.getMinimum(SECOND) + 1, gc.getMaximum(SECOND) - 1, gc.getMaximum(SECOND) }; - for(int i = 0; i < years.length; i++) { - for(int j = 0; j < months.length; j++) { - for(int k = 0; k < dates.length; k++) { - for(int m = 0; m < hs.length; m++) { - for(int n = 0; n < ms.length; n++) { - for(int p = 0; p < ss.length; p++) { + for (int i = 0; i < years.length; i++) { + for (int j = 0; j < months.length; j++) { + for (int k = 0; k < dates.length; k++) { + for (int m = 0; m < hs.length; m++) { + for (int n = 0; n < ms.length; n++) { + for (int p = 0; p < ss.length; p++) { int year = years[i] - 1900; int month = months[j]; int date = dates[k]; @@ -120,7 +124,7 @@ int seconds = ss[p]; long result = Date.UTC(year, month, date, - hours, minutes, seconds); + hours, minutes, seconds); gc.clear(); gc.set(year + 1900, month, date, hours, minutes, seconds); @@ -129,7 +133,7 @@ if (expected != result) { throw new RuntimeException("expected (" + expected - + ") != result (" + result +")"); + + ") != result (" + result + ")"); } } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Locale/Bug4175998Test.java --- a/jdk/test/java/util/Locale/Bug4175998Test.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Locale/Bug4175998Test.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -24,6 +24,7 @@ /* * @test * @summary test ISO639-2 language codes + * @library /java/text/testlib * @compile -encoding ascii Bug4175998Test.java * @run main Bug4175998Test * @bug 4175998 @@ -43,14 +44,13 @@ */ import java.util.*; -import java.io.*; /** * Bug4175998Test verifies that the following bug has been fixed: * Bug 4175998 - The java.util.Locale.getISO3Language() returns wrong result for a locale with * language code 'ta'(Tamil). */ -public class Bug4175998Test extends LocaleTestFmwk { +public class Bug4175998Test extends IntlTest { public static void main(String[] args) throws Exception { new Bug4175998Test().run(args); //generateTables(); //uncomment this to regenerate data tables diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Locale/Bug4184873Test.java --- a/jdk/test/java/util/Locale/Bug4184873Test.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Locale/Bug4184873Test.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it @@ -23,6 +23,7 @@ /* @test @summary test that locale invariants are preserved across serialization + @library /java/text/testlib @run main Bug4184873Test @bug 4184873 */ @@ -63,7 +64,7 @@ /** * A Locale can never contain the following language codes: he, yi or id. */ -public class Bug4184873Test extends LocaleTestFmwk { +public class Bug4184873Test extends IntlTest { public static void main(String[] args) throws Exception { if (args.length == 1 && args[0].equals("prepTest")) { prepTest(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Locale/Bug8001562.java --- a/jdk/test/java/util/Locale/Bug8001562.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Locale/Bug8001562.java Wed Jul 05 22:30:52 2017 +0200 @@ -30,37 +30,46 @@ * @run main Bug8001562 */ -import java.text.*; -import java.util.*; +import java.text.BreakIterator; +import java.text.Collator; +import java.text.DateFormat; +import java.text.DateFormatSymbols; +import java.text.DecimalFormatSymbols; +import java.text.NumberFormat; +import java.util.Arrays; +import java.util.List; +import java.util.Locale; +import java.util.stream.Collectors; public class Bug8001562 { - static final String[] jdk7availTags = { - "ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", - "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SD", "ar-SY", - "ar-TN", "ar-YE", "be", "be-BY", "bg", "bg-BG", "ca", "ca-ES", "cs", - "cs-CZ", "da", "da-DK", "de", "de-AT", "de-CH", "de-DE", "de-LU", "el", - "el-CY", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", - "en-MT", "en-NZ", "en-PH", "en-SG", "en-US", "en-ZA", "es", "es-AR", - "es-BO", "es-CL", "es-CO", "es-CR", "es-DO", "es-EC", "es-ES", "es-GT", - "es-HN", "es-MX", "es-NI", "es-PA", "es-PE", "es-PR", "es-PY", "es-SV", - "es-US", "es-UY", "es-VE", "et", "et-EE", "fi", "fi-FI", "fr", "fr-BE", - "fr-CA", "fr-CH", "fr-FR", "fr-LU", "ga", "ga-IE", "he", "he-IL", - "hi-IN", "hr", "hr-HR", "hu", "hu-HU", "id", "id-ID", "is", "is-IS", - "it", "it-CH", "it-IT", "ja", "ja-JP", - "ja-JP-u-ca-japanese-x-lvariant-JP", "ko", "ko-KR", "lt", "lt-LT", "lv", - "lv-LV", "mk", "mk-MK", "ms", "ms-MY", "mt", "mt-MT", "nl", "nl-BE", - "nl-NL", "no", "no-NO", "no-NO-x-lvariant-NY", "pl", "pl-PL", "pt", - "pt-BR", "pt-PT", "ro", "ro-RO", "ru", "ru-RU", "sk", "sk-SK", "sl", - "sl-SI", "sq", "sq-AL", "sr", "sr-BA", "sr-CS", "sr-Latn", "sr-Latn-BA", - "sr-Latn-ME", "sr-Latn-RS", "sr-ME", "sr-RS", "sv", "sv-SE", "th", - "th-TH", "th-TH-u-nu-thai-x-lvariant-TH", "tr", "tr-TR", "uk", "uk-UA", - "vi", "vi-VN", "zh", "zh-CN", "zh-HK", "zh-SG", "zh-TW", }; - static List jdk7availLocs = new ArrayList<>(); + static final List jdk7availTags = List.of( + "ar", "ar-AE", "ar-BH", "ar-DZ", "ar-EG", "ar-IQ", "ar-JO", "ar-KW", + "ar-LB", "ar-LY", "ar-MA", "ar-OM", "ar-QA", "ar-SA", "ar-SD", "ar-SY", + "ar-TN", "ar-YE", "be", "be-BY", "bg", "bg-BG", "ca", "ca-ES", "cs", + "cs-CZ", "da", "da-DK", "de", "de-AT", "de-CH", "de-DE", "de-LU", "el", + "el-CY", "el-GR", "en", "en-AU", "en-CA", "en-GB", "en-IE", "en-IN", + "en-MT", "en-NZ", "en-PH", "en-SG", "en-US", "en-ZA", "es", "es-AR", + "es-BO", "es-CL", "es-CO", "es-CR", "es-DO", "es-EC", "es-ES", "es-GT", + "es-HN", "es-MX", "es-NI", "es-PA", "es-PE", "es-PR", "es-PY", "es-SV", + "es-US", "es-UY", "es-VE", "et", "et-EE", "fi", "fi-FI", "fr", "fr-BE", + "fr-CA", "fr-CH", "fr-FR", "fr-LU", "ga", "ga-IE", "he", "he-IL", + "hi-IN", "hr", "hr-HR", "hu", "hu-HU", "id", "id-ID", "is", "is-IS", + "it", "it-CH", "it-IT", "ja", "ja-JP", + "ja-JP-u-ca-japanese-x-lvariant-JP", "ko", "ko-KR", "lt", "lt-LT", "lv", + "lv-LV", "mk", "mk-MK", "ms", "ms-MY", "mt", "mt-MT", "nl", "nl-BE", + "nl-NL", "no", "no-NO", "no-NO-x-lvariant-NY", "pl", "pl-PL", "pt", + "pt-BR", "pt-PT", "ro", "ro-RO", "ru", "ru-RU", "sk", "sk-SK", "sl", + "sl-SI", "sq", "sq-AL", "sr", "sr-BA", "sr-CS", "sr-Latn", "sr-Latn-BA", + "sr-Latn-ME", "sr-Latn-RS", "sr-ME", "sr-RS", "sv", "sv-SE", "th", + "th-TH", "th-TH-u-nu-thai-x-lvariant-TH", "tr", "tr-TR", "uk", "uk-UA", + "vi", "vi-VN", "zh", "zh-CN", "zh-HK", "zh-SG", "zh-TW"); + static List jdk7availLocs; + static { - for (String locStr : jdk7availTags) { - jdk7availLocs.add(Locale.forLanguageTag(locStr)); - } + jdk7availLocs = jdk7availTags.stream() + .map(Locale::forLanguageTag) + .collect(Collectors.toList()); } public static void main(String[] args) { @@ -86,13 +95,13 @@ diffLocale(Locale.class, avail); } - static void diffLocale(Class c, List locs) { + static void diffLocale(Class c, List locs) { String diff = ""; System.out.printf("Only in target locales (%s.getAvailableLocales()): ", c.getSimpleName()); for (Locale l : locs) { if (!jdk7availLocs.contains(l)) { - diff += "\""+l.toLanguageTag()+"\", "; + diff += "\"" + l.toLanguageTag() + "\", "; } } System.out.println(diff); @@ -101,7 +110,7 @@ System.out.printf("Only in JDK7 (%s.getAvailableLocales()): ", c.getSimpleName()); for (Locale l : jdk7availLocs) { if (!locs.contains(l)) { - diff += "\""+l.toLanguageTag()+"\", "; + diff += "\"" + l.toLanguageTag() + "\", "; } } System.out.println(diff); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Locale/HashCodeTest.java --- a/jdk/test/java/util/Locale/HashCodeTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Locale/HashCodeTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -27,14 +27,17 @@ * @modules jdk.localedata */ -import java.util.*; +import java.util.HashMap; +import java.util.Locale; +import java.util.Map; public class HashCodeTest { + public static void main(String[] args) { Locale[] locales = Locale.getAvailableLocales(); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; - Map map = new HashMap(locales.length); + Map map = new HashMap<>(locales.length); int conflicts = 0; for (int i = 0; i < locales.length; i++) { @@ -42,19 +45,19 @@ int hc = loc.hashCode(); min = Math.min(hc, min); max = Math.max(hc, max); - Integer key = new Integer(hc); + Integer key = hc; if (map.containsKey(key)) { conflicts++; - System.out.println("conflict: " + (Locale) map.get(key) + ", " + loc); + System.out.println("conflict: " + map.get(key) + ", " + loc); } else { map.put(key, loc); } } - System.out.println(locales.length+" locales: conflicts="+conflicts - +", min="+min+", max="+max +", diff="+(max-min)); + System.out.println(locales.length + " locales: conflicts=" + conflicts + + ", min=" + min + ", max=" + max + ", diff=" + (max - min)); if (conflicts >= (locales.length / 10)) { throw new RuntimeException("too many conflicts: " + conflicts - + " per " + locales.length + " locales"); + + " per " + locales.length + " locales"); } } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Locale/LocaleEnhanceTest.java --- a/jdk/test/java/util/Locale/LocaleEnhanceTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Locale/LocaleEnhanceTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -46,11 +46,12 @@ * @bug 6875847 6992272 7002320 7015500 7023613 7032820 7033504 7004603 * 7044019 8008577 * @summary test API changes to Locale + * @library /java/text/testlib * @modules jdk.localedata * @compile LocaleEnhanceTest.java * @run main/othervm -Djava.locale.providers=JRE,SPI -esa LocaleEnhanceTest */ -public class LocaleEnhanceTest extends LocaleTestFmwk { +public class LocaleEnhanceTest extends IntlTest { public static void main(String[] args) throws Exception { List argList = new ArrayList(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Locale/LocaleTest.java --- a/jdk/test/java/util/Locale/LocaleTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Locale/LocaleTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -27,6 +27,7 @@ * 4147315 4147317 4147552 4335196 4778440 4940539 5010672 6475525 6544471 6627549 * 6786276 7066203 7085757 8008577 8030696 * @summary test Locales + * @library /java/text/testlib * @modules jdk.localedata * @run main/othervm -Djava.locale.providers=JRE,SPI LocaleTest */ @@ -63,16 +64,25 @@ * */ -import java.text.*; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.io.OptionalDataException; +import java.io.StreamCorruptedException; +import java.text.DateFormat; +import java.text.DecimalFormat; +import java.text.NumberFormat; +import java.text.SimpleDateFormat; import java.util.Arrays; +import java.util.Calendar; +import java.util.Date; import java.util.List; import java.util.Locale; import java.util.MissingResourceException; -import java.util.Date; -import java.util.Calendar; -import java.io.*; -public class LocaleTest extends LocaleTestFmwk { +public class LocaleTest extends IntlTest { public LocaleTest() { } @@ -186,18 +196,22 @@ Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); logln("Testing " + testLocale + "..."); - if (!testLocale.getLanguage().equals(dataTable[LANG][i])) + if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " - + dataTable[LANG][i]); - if (!testLocale.getCountry().equals(dataTable[CTRY][i])) + + dataTable[LANG][i]); + } + if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { errln(" Country code mismatch: " + testLocale.getCountry() + " versus " - + dataTable[CTRY][i]); - if (!testLocale.getVariant().equals(dataTable[VAR][i])) + + dataTable[CTRY][i]); + } + if (!testLocale.getVariant().equals(dataTable[VAR][i])) { errln(" Variant code mismatch: " + testLocale.getVariant() + " versus " - + dataTable[VAR][i]); - if (!testLocale.toString().equals(dataTable[NAME][i])) + + dataTable[VAR][i]); + } + if (!testLocale.toString().equals(dataTable[NAME][i])) { errln(" Locale name mismatch: " + testLocale.toString() + " versus " - + dataTable[NAME][i]); + + dataTable[NAME][i]); + } } logln("Same thing without variant codes..."); @@ -205,31 +219,37 @@ Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i]); logln("Testing " + testLocale + "..."); - if (!testLocale.getLanguage().equals(dataTable[LANG][i])) + if (!testLocale.getLanguage().equals(dataTable[LANG][i])) { errln(" Language code mismatch: " + testLocale.getLanguage() + " versus " - + dataTable[LANG][i]); - if (!testLocale.getCountry().equals(dataTable[CTRY][i])) + + dataTable[LANG][i]); + } + if (!testLocale.getCountry().equals(dataTable[CTRY][i])) { errln(" Country code mismatch: " + testLocale.getCountry() + " versus " - + dataTable[CTRY][i]); - if (!testLocale.getVariant().equals("")) + + dataTable[CTRY][i]); + } + if (!testLocale.getVariant().equals("")) { errln(" Variant code mismatch: " + testLocale.getVariant() + " versus \"\""); + } } } public void TestSimpleResourceInfo() { for (int i = 0; i <= MAX_LOCALES; i++) { - if (dataTable[LANG][i].equals("xx")) + if (dataTable[LANG][i].equals("xx")) { continue; + } Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); logln("Testing " + testLocale + "..."); - if (!testLocale.getISO3Language().equals(dataTable[LANG3][i])) + if (!testLocale.getISO3Language().equals(dataTable[LANG3][i])) { errln(" ISO-3 language code mismatch: " + testLocale.getISO3Language() - + " versus " + dataTable[LANG3][i]); - if (!testLocale.getISO3Country().equals(dataTable[CTRY3][i])) + + " versus " + dataTable[LANG3][i]); + } + if (!testLocale.getISO3Country().equals(dataTable[CTRY3][i])) { errln(" ISO-3 country code mismatch: " + testLocale.getISO3Country() - + " versus " + dataTable[CTRY3][i]); + + " versus " + dataTable[CTRY3][i]); + } /* // getLCID() is currently private if (!String.valueOf(testLocale.getLCID()).equals(dataTable[LCID][i])) @@ -246,11 +266,11 @@ * @bug 4052440 Stop falling back to the default locale. */ public void TestDisplayNames() { - Locale saveDefault = Locale.getDefault(); - Locale english = new Locale("en", "US"); - Locale french = new Locale("fr", "FR"); - Locale croatian = new Locale("hr", "HR"); - Locale greek = new Locale("el", "GR"); + Locale saveDefault = Locale.getDefault(); + Locale english = new Locale("en", "US"); + Locale french = new Locale("fr", "FR"); + Locale croatian = new Locale("hr", "HR"); + Locale greek = new Locale("el", "GR"); Locale.setDefault(english); logln("With default = en_US..."); @@ -282,97 +302,116 @@ } private void doTestDisplayNames(Locale inLocale, int compareIndex, boolean defaultIsFrench) { - if (defaultIsFrench && !Locale.getDefault().getLanguage().equals("fr")) - errln("Default locale should be French, but it's really " + Locale.getDefault().getLanguage()); - else if (!defaultIsFrench && !Locale.getDefault().getLanguage().equals("en")) - errln("Default locale should be English, but it's really " + Locale.getDefault().getLanguage()); + String language = Locale.getDefault().getLanguage(); + + if (defaultIsFrench && !language.equals("fr")) { + errln("Default locale should be French, but it's really " + language); + } else if (!defaultIsFrench && !language.equals("en")) { + errln("Default locale should be English, but it's really " + language); + } for (int i = 0; i <= MAX_LOCALES; i++) { Locale testLocale = new Locale(dataTable[LANG][i], dataTable[CTRY][i], dataTable[VAR][i]); logln(" Testing " + testLocale + "..."); - String testLang; - String testCtry; - String testVar; - String testName; + String testLang; + String testCtry; + String testVar; + String testName; if (inLocale == null) { testLang = testLocale.getDisplayLanguage(); testCtry = testLocale.getDisplayCountry(); testVar = testLocale.getDisplayVariant(); testName = testLocale.getDisplayName(); - } - else { + } else { testLang = testLocale.getDisplayLanguage(inLocale); testCtry = testLocale.getDisplayCountry(inLocale); testVar = testLocale.getDisplayVariant(inLocale); testName = testLocale.getDisplayName(inLocale); } - String expectedLang; - String expectedCtry; - String expectedVar; - String expectedName; + String expectedLang; + String expectedCtry; + String expectedVar; + String expectedName; expectedLang = dataTable[compareIndex][i]; - if (expectedLang.equals("") && defaultIsFrench) + if (expectedLang.equals("") && defaultIsFrench) { expectedLang = dataTable[DLANG_EN][i]; - if (expectedLang.equals("")) + } + if (expectedLang.equals("")) { expectedLang = dataTable[DLANG_ROOT][i]; + } expectedCtry = dataTable[compareIndex + 1][i]; - if (expectedCtry.equals("") && defaultIsFrench) + if (expectedCtry.equals("") && defaultIsFrench) { expectedCtry = dataTable[DCTRY_EN][i]; - if (expectedCtry.equals("")) + } + if (expectedCtry.equals("")) { expectedCtry = dataTable[DCTRY_ROOT][i]; + } expectedVar = dataTable[compareIndex + 2][i]; - if (expectedVar.equals("") && defaultIsFrench) + if (expectedVar.equals("") && defaultIsFrench) { expectedVar = dataTable[DVAR_EN][i]; - if (expectedVar.equals("")) + } + if (expectedVar.equals("")) { expectedVar = dataTable[DVAR_ROOT][i]; + } expectedName = dataTable[compareIndex + 3][i]; - if (expectedName.equals("") && defaultIsFrench) + if (expectedName.equals("") && defaultIsFrench) { expectedName = dataTable[DNAME_EN][i]; - if (expectedName.equals("")) + } + if (expectedName.equals("")) { expectedName = dataTable[DNAME_ROOT][i]; + } - if (!testLang.equals(expectedLang)) + if (!testLang.equals(expectedLang)) { errln("Display language mismatch: " + testLang + " versus " + expectedLang); - if (!testCtry.equals(expectedCtry)) + } + if (!testCtry.equals(expectedCtry)) { errln("Display country mismatch: " + testCtry + " versus " + expectedCtry); - if (!testVar.equals(expectedVar)) + } + if (!testVar.equals(expectedVar)) { errln("Display variant mismatch: " + testVar + " versus " + expectedVar); - if (!testName.equals(expectedName)) + } + if (!testName.equals(expectedName)) { errln("Display name mismatch: " + testName + " versus " + expectedName); + } } } public void TestSimpleObjectStuff() { - Locale test1 = new Locale("aa", "AA"); - Locale test2 = new Locale("aa", "AA"); - Locale test3 = (Locale)test1.clone(); - Locale test4 = new Locale("zz", "ZZ"); + Locale test1 = new Locale("aa", "AA"); + Locale test2 = new Locale("aa", "AA"); + Locale test3 = (Locale) test1.clone(); + Locale test4 = new Locale("zz", "ZZ"); - if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3) + if (test1 == test2 || test1 == test3 || test1 == test4 || test2 == test3) { errln("Some of the test variables point to the same locale!"); + } - if (test3 == null) + if (test3 == null) { errln("clone() failed to produce a valid object!"); + } - if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3)) + if (!test1.equals(test2) || !test1.equals(test3) || !test2.equals(test3)) { errln("clone() or equals() failed: objects that should compare equal don't"); + } - if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4)) + if (test1.equals(test4) || test2.equals(test4) || test3.equals(test4)) { errln("equals() failed: objects that shouldn't compare equal do"); + } int hash1 = test1.hashCode(); int hash2 = test2.hashCode(); int hash3 = test3.hashCode(); - if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3) + if (hash1 != hash2 || hash1 != hash3 || hash2 != hash3) { errln("hashCode() failed: objects that should have the same hash code don't"); + } } /** @@ -385,22 +424,22 @@ try { result = test.getISO3Language(); - } - catch (MissingResourceException e) { + } catch (MissingResourceException e) { gotException = true; } - if (!gotException) + if (!gotException) { errln("getISO3Language() on xx_YY returned " + result + " instead of throwing an exception"); + } gotException = false; try { result = test.getISO3Country(); - } - catch (MissingResourceException e) { + } catch (MissingResourceException e) { gotException = true; } - if (!gotException) + if (!gotException) { errln("getISO3Country() on xx_YY returned " + result + " instead of throwing an exception"); + } } /** @@ -416,53 +455,65 @@ // all lower case for the language codes, all upper case for the country codes) // 4) Is each list in sorted order? String[] test = Locale.getISOLanguages(); - String[] spotCheck1 = { "en", "es", "fr", "de", "it", "ja", "ko", "zh", "th", - "he", "id", "iu", "ug", "yi", "za" }; + String[] spotCheck1 = {"en", "es", "fr", "de", "it", "ja", "ko", "zh", "th", + "he", "id", "iu", "ug", "yi", "za"}; - if (test.length != 188) + if (test.length != 188) { errln("Expected getISOLanguages() to return 188 languages; it returned " + test.length); - else { + } else { for (int i = 0; i < spotCheck1.length; i++) { int j; - for (j = 0; j < test.length; j++) - if (test[j].equals(spotCheck1[i])) + for (j = 0; j < test.length; j++) { + if (test[j].equals(spotCheck1[i])) { break; - if (j == test.length || !test[j].equals(spotCheck1[i])) + } + } + if (j == test.length || !test[j].equals(spotCheck1[i])) { errln("Couldn't find " + spotCheck1[i] + " in language list."); + } } } for (int i = 0; i < test.length; i++) { - if (!test[i].equals(test[i].toLowerCase())) + if (!test[i].equals(test[i].toLowerCase())) { errln(test[i] + " is not all lower case."); - if (test[i].length() != 2) + } + if (test[i].length() != 2) { errln(test[i] + " is not two characters long."); - if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) + } + if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { errln(test[i] + " appears in an out-of-order position in the list."); + } } test = Locale.getISOCountries(); - String[] spotCheck2 = { "US", "CA", "GB", "FR", "DE", "IT", "JP", "KR", "CN", "TW", "TH" }; + String[] spotCheck2 = {"US", "CA", "GB", "FR", "DE", "IT", "JP", "KR", "CN", "TW", "TH"}; - if (test.length != 250) + if (test.length != 250) { errln("Expected getISOCountries to return 250 countries; it returned " + test.length); - else { + } else { for (int i = 0; i < spotCheck2.length; i++) { int j; - for (j = 0; j < test.length; j++) - if (test[j].equals(spotCheck2[i])) + for (j = 0; j < test.length; j++) { + if (test[j].equals(spotCheck2[i])) { break; - if (j == test.length || !test[j].equals(spotCheck2[i])) + } + } + if (j == test.length || !test[j].equals(spotCheck2[i])) { errln("Couldn't find " + spotCheck2[i] + " in country list."); + } } } for (int i = 0; i < test.length; i++) { - if (!test[i].equals(test[i].toUpperCase())) + if (!test[i].equals(test[i].toUpperCase())) { errln(test[i] + " is not all upper case."); - if (test[i].length() != 2) + } + if (test[i].length() != 2) { errln(test[i] + " is not two characters long."); - if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) + } + if (i > 0 && test[i].compareTo(test[i - 1]) <= 0) { errln(test[i] + " appears in an out-of-order position in the list."); + } } } @@ -475,14 +526,16 @@ test = Locale.getISOCountries(); test[0] = "SUCKER!!!"; test = Locale.getISOCountries(); - if (test[0].equals("SUCKER!!!")) + if (test[0].equals("SUCKER!!!")) { errln("Changed internal country code list!"); + } test = Locale.getISOLanguages(); test[0] = "HAHAHAHA!!!"; test = Locale.getISOLanguages(); - if (test[0].equals("HAHAHAHA!!!")) // Fixed typo + if (test[0].equals("HAHAHAHA!!!")) { // Fixed typo errln("Changes internal language code list!"); + } } /** @@ -490,12 +543,13 @@ */ public void TestGetAvailableLocales() { Locale[] locales = Locale.getAvailableLocales(); - if (locales == null || locales.length == 0) + if (locales == null || locales.length == 0) { errln("Locale.getAvailableLocales() returned no installed locales!"); - else { + } else { logln("Locale.getAvailableLocales() returned a list of " + locales.length + " locales."); - for (int i = 0; i < locales.length; i++) + for (int i = 0; i < locales.length; i++) { logln(locales[i].toString()); + } } } @@ -505,8 +559,9 @@ public void TestBug4135316() { Locale[] locales1 = Locale.getAvailableLocales(); Locale[] locales2 = Locale.getAvailableLocales(); - if (locales1 == locales2) + if (locales1 == locales2) { errln("Locale.getAvailableLocales() doesn't clone its internal storage!"); + } } /** @@ -548,8 +603,7 @@ * @bug 4110613 */ public void TestSerialization() throws ClassNotFoundException, OptionalDataException, - IOException, StreamCorruptedException - { + IOException, StreamCorruptedException { ObjectOutputStream ostream; ByteArrayOutputStream obstream; byte[] bytes = null; @@ -565,10 +619,11 @@ ObjectInputStream istream = new ObjectInputStream(new ByteArrayInputStream(bytes)); - Locale test2 = (Locale)(istream.readObject()); + Locale test2 = (Locale) (istream.readObject()); - if (!test1.equals(test2) || test1.hashCode() != test2.hashCode()) + if (!test1.equals(test2) || test1.hashCode() != test2.hashCode()) { errln("Locale failed to deserialize correctly."); + } } /** @@ -579,15 +634,16 @@ // fallback behavior, combination of language and country names to form locale // names, and other stuff like that. This test just checks specific language // and country codes to make sure we have the correct names for them. - String[] languageCodes = { "he", "id", "iu", "ug", "yi", "za" }; - String[] languageNames = { "Hebrew", "Indonesian", "Inuktitut", "Uighur", "Yiddish", - "Zhuang" }; + String[] languageCodes = {"he", "id", "iu", "ug", "yi", "za"}; + String[] languageNames = {"Hebrew", "Indonesian", "Inuktitut", "Uighur", "Yiddish", + "Zhuang"}; for (int i = 0; i < languageCodes.length; i++) { String test = (new Locale(languageCodes[i], "", "")).getDisplayLanguage(Locale.US); - if (!test.equals(languageNames[i])) - errln("Got wrong display name for " + languageCodes[i] + ": Expected \"" + - languageNames[i] + "\", got \"" + test + "\"."); + if (!test.equals(languageNames[i])) { + errln("Got wrong display name for " + languageCodes[i] + ": Expected \"" + + languageNames[i] + "\", got \"" + test + "\"."); + } } } @@ -597,24 +653,26 @@ public void TestUninstalledISO3Names() { // This test checks to make sure getISO3Language and getISO3Country work right // even for locales that are not installed. - String[] iso2Languages = { "am", "ba", "fy", "mr", "rn", "ss", "tw", "zu" }; - String[] iso3Languages = { "amh", "bak", "fry", "mar", "run", "ssw", "twi", "zul" }; + String[] iso2Languages = {"am", "ba", "fy", "mr", "rn", "ss", "tw", "zu"}; + String[] iso3Languages = {"amh", "bak", "fry", "mar", "run", "ssw", "twi", "zul"}; for (int i = 0; i < iso2Languages.length; i++) { String test = (new Locale(iso2Languages[i], "", "")).getISO3Language(); - if (!test.equals(iso3Languages[i])) - errln("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + - iso3Languages[i] + "\", got \"" + test + "\"."); + if (!test.equals(iso3Languages[i])) { + errln("Got wrong ISO3 code for " + iso2Languages[i] + ": Expected \"" + + iso3Languages[i] + "\", got \"" + test + "\"."); + } } - String[] iso2Countries = { "AF", "BW", "KZ", "MO", "MN", "SB", "TC", "ZW" }; - String[] iso3Countries = { "AFG", "BWA", "KAZ", "MAC", "MNG", "SLB", "TCA", "ZWE" }; + String[] iso2Countries = {"AF", "BW", "KZ", "MO", "MN", "SB", "TC", "ZW"}; + String[] iso3Countries = {"AFG", "BWA", "KAZ", "MAC", "MNG", "SLB", "TCA", "ZWE"}; for (int i = 0; i < iso2Countries.length; i++) { String test = (new Locale("", iso2Countries[i], "")).getISO3Country(); - if (!test.equals(iso3Countries[i])) - errln("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + - iso3Countries[i] + "\", got \"" + test + "\"."); + if (!test.equals(iso3Countries[i])) { + errln("Got wrong ISO3 code for " + iso2Countries[i] + ": Expected \"" + + iso3Countries[i] + "\", got \"" + test + "\"."); + } } } @@ -629,15 +687,18 @@ Locale indonesianOld = new Locale("in", "", ""); Locale indonesianNew = new Locale("id", "", ""); - if (!hebrewNew.getLanguage().equals("iw")) - errln("Got back wrong language code for Hebrew: expected \"iw\", got \"" + - hebrewNew.getLanguage() + "\""); - if (!yiddishNew.getLanguage().equals("ji")) - errln("Got back wrong language code for Yiddish: expected \"ji\", got \"" + - yiddishNew.getLanguage() + "\""); - if (!indonesianNew.getLanguage().equals("in")) - errln("Got back wrong language code for Indonesian: expected \"in\", got \"" + - indonesianNew.getLanguage() + "\""); + if (!hebrewNew.getLanguage().equals("iw")) { + errln("Got back wrong language code for Hebrew: expected \"iw\", got \"" + + hebrewNew.getLanguage() + "\""); + } + if (!yiddishNew.getLanguage().equals("ji")) { + errln("Got back wrong language code for Yiddish: expected \"ji\", got \"" + + yiddishNew.getLanguage() + "\""); + } + if (!indonesianNew.getLanguage().equals("in")) { + errln("Got back wrong language code for Indonesian: expected \"in\", got \"" + + indonesianNew.getLanguage() + "\""); + } } /** @@ -703,25 +764,28 @@ for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.US); logln(name); - if (!name.equals(englishDisplayNames[i])) + if (!name.equals(englishDisplayNames[i])) { errln("Lookup in English failed: expected \"" + englishDisplayNames[i] - + "\", got \"" + name + "\""); + + "\", got \"" + name + "\""); + } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(new Locale("es", "ES")); logln(name); - if (!name.equals(spanishDisplayNames[i])) + if (!name.equals(spanishDisplayNames[i])) { errln("Lookup in Spanish failed: expected \"" + spanishDisplayNames[i] - + "\", got \"" + name + "\""); + + "\", got \"" + name + "\""); + } } for (int i = 0; i < localesToTest.length; i++) { String name = localesToTest[i].getDisplayName(Locale.FRANCE); logln(name); - if (!name.equals(frenchDisplayNames[i])) + if (!name.equals(frenchDisplayNames[i])) { errln("Lookup in French failed: expected \"" + frenchDisplayNames[i] - + "\", got \"" + name + "\""); + + "\", got \"" + name + "\""); + } } // restore the default locale for other tests @@ -737,15 +801,16 @@ boolean gotException = false; try { Locale.setDefault(null); - } - catch (NullPointerException e) { + } catch (NullPointerException e) { // all other exception types propagate through here back to the test harness gotException = true; } - if (Locale.getDefault() == null) + if (Locale.getDefault() == null) { errln("Locale.getDefault() allowed us to set default to NULL!"); - if (!gotException) + } + if (!gotException) { errln("Trying to set default locale to NULL didn't throw exception!"); + } } /** @@ -754,14 +819,16 @@ * get the LocaleDataTest working again. */ public void TestThaiCurrencyFormat() { - DecimalFormat thaiCurrency = (DecimalFormat)NumberFormat.getCurrencyInstance( - new Locale("th", "TH")); - if (!thaiCurrency.getPositivePrefix().equals("\u0e3f")) - errln("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + - thaiCurrency.getPositivePrefix() + "\""); - if (!thaiCurrency.getPositiveSuffix().equals("")) - errln("Thai currency suffix wrong: expected \"\", got \"" + - thaiCurrency.getPositiveSuffix() + "\""); + DecimalFormat thaiCurrency = (DecimalFormat) NumberFormat.getCurrencyInstance( + new Locale("th", "TH")); + if (!thaiCurrency.getPositivePrefix().equals("\u0e3f")) { + errln("Thai currency prefix wrong: expected \"\u0e3f\", got \"" + + thaiCurrency.getPositivePrefix() + "\""); + } + if (!thaiCurrency.getPositiveSuffix().equals("")) { + errln("Thai currency suffix wrong: expected \"\", got \"" + + thaiCurrency.getPositiveSuffix() + "\""); + } } /** @@ -778,26 +845,25 @@ * iterate through all locales. */ public void TestEuroSupport() { - final String EURO_VARIANT = "EURO"; + final String EURO_VARIANT = "EURO"; final String EURO_CURRENCY = "\u20AC"; // Look for this string in formatted Euro currency Locale[] locales = NumberFormat.getAvailableLocales(); - for (int i=0; i= 0) { NumberFormat nf = NumberFormat.getCurrencyInstance(loc); String pos = nf.format(271828.182845); String neg = nf.format(-271828.182845); - if (pos.indexOf(EURO_CURRENCY) >= 0 && - neg.indexOf(EURO_CURRENCY) >= 0) { - logln("Ok: " + loc.toString() + - ": " + pos + " / " + neg); - } - else { - errln("Fail: " + loc.toString() + - " formats without " + EURO_CURRENCY + - ": " + pos + " / " + neg + - "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***"); + if (pos.indexOf(EURO_CURRENCY) >= 0 + && neg.indexOf(EURO_CURRENCY) >= 0) { + logln("Ok: " + loc.toString() + + ": " + pos + " / " + neg); + } else { + errln("Fail: " + loc.toString() + + " formats without " + EURO_CURRENCY + + ": " + pos + " / " + neg + + "\n*** THIS FAILURE MAY ONLY MEAN THAT LOCALE DATA HAS CHANGED ***"); } } } @@ -811,15 +877,15 @@ Object[] DATA = { new Locale("xx", "", ""), "xx", new Locale("", "YY", ""), "_YY", - new Locale("", "", "ZZ"), "", + new Locale("", "", "ZZ"), "", new Locale("xx", "YY", ""), "xx_YY", new Locale("xx", "", "ZZ"), "xx__ZZ", new Locale("", "YY", "ZZ"), "_YY_ZZ", new Locale("xx", "YY", "ZZ"), "xx_YY_ZZ", }; - for (int i=0; i" + loc); } @@ -832,9 +898,9 @@ * end to test the whole pipe. */ public void Test4105828() { - Locale[] LOC = { Locale.CHINESE, new Locale("zh", "CN", ""), - new Locale("zh", "TW", ""), new Locale("zh", "HK", "") }; - for (int i=0; i= 0) + if (str.indexOf('\u0151') < 0 || str.indexOf('\u00F4') >= 0) { errln("Fail: Monday in Hungarian is wrong"); + } } /** @@ -894,9 +962,10 @@ try { String result = locale.getISO3Country(); - errln("ERROR: getISO3Country() returns: " + result + - " for locale '" + locale + "' rather than exception" ); - } catch(MissingResourceException e) { } + errln("ERROR: getISO3Country() returns: " + result + + " for locale '" + locale + "' rather than exception"); + } catch (MissingResourceException e) { + } } /** @@ -912,8 +981,8 @@ String result = locale.getISO3Language(); if (!result.equals("aaa")) { - errln("ERROR: getISO3Language() returns: " + result + - " for locale '" + locale + "' rather than returning it as is" ); + errln("ERROR: getISO3Language() returns: " + result + + " for locale '" + locale + "' rather than returning it as is"); } // Try an invalid two letter language code, and check whether it @@ -923,36 +992,39 @@ try { result = locale.getISO3Language(); - errln("ERROR: getISO3Language() returns: " + result + - " for locale '" + locale + "' rather than exception" ); - } catch(MissingResourceException e) { } + errln("ERROR: getISO3Language() returns: " + result + + " for locale '" + locale + "' rather than exception"); + } catch (MissingResourceException e) { + } } /* * @bug 4147552 4778440 8030696 */ public void Test4147552() { - Locale[] locales = { new Locale("no", "NO"), new Locale("no", "NO", "B"), - new Locale("no", "NO", "NY"), new Locale("nb", "NO"), - new Locale("nn", "NO") }; - String[] englishDisplayNames = { "Norwegian (Norway)", - "Norwegian (Norway,Bokm\u00e5l)", - "Norwegian (Norway,Nynorsk)", - "Norwegian Bokm\u00e5l (Norway)", - "Norwegian Nynorsk (Norway)" }; - String[] norwegianDisplayNames = { "norsk (Norge)", - "norsk (Norge,bokm\u00e5l)", "norsk (Noreg,nynorsk)", - "bokm\u00e5l (Norge)", "nynorsk (Noreg)" }; + Locale[] locales = {new Locale("no", "NO"), new Locale("no", "NO", "B"), + new Locale("no", "NO", "NY"), new Locale("nb", "NO"), + new Locale("nn", "NO")}; + String[] englishDisplayNames = {"Norwegian (Norway)", + "Norwegian (Norway,Bokm\u00e5l)", + "Norwegian (Norway,Nynorsk)", + "Norwegian Bokm\u00e5l (Norway)", + "Norwegian Nynorsk (Norway)"}; + String[] norwegianDisplayNames = {"norsk (Norge)", + "norsk (Norge,bokm\u00e5l)", "norsk (Noreg,nynorsk)", + "bokm\u00e5l (Norge)", "nynorsk (Noreg)"}; for (int i = 0; i < locales.length; i++) { Locale loc = locales[i]; - if (!loc.getDisplayName(Locale.US).equals(englishDisplayNames[i])) - errln("English display-name mismatch: expected " + - englishDisplayNames[i] + ", got " + loc.getDisplayName()); - if (!loc.getDisplayName(loc).equals(norwegianDisplayNames[i])) - errln("Norwegian display-name mismatch: expected " + - norwegianDisplayNames[i] + ", got " + - loc.getDisplayName(loc)); + if (!loc.getDisplayName(Locale.US).equals(englishDisplayNames[i])) { + errln("English display-name mismatch: expected " + + englishDisplayNames[i] + ", got " + loc.getDisplayName()); + } + if (!loc.getDisplayName(loc).equals(norwegianDisplayNames[i])) { + errln("Norwegian display-name mismatch: expected " + + norwegianDisplayNames[i] + ", got " + + loc.getDisplayName(loc)); + } } } @@ -961,21 +1033,24 @@ */ public void Test8030696() { List av = Arrays.asList(Locale.getAvailableLocales()); - if (!av.contains(new Locale("nb", "NO")) || - !av.contains(new Locale("nn", "NO"))) { - errln("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); + if (!av.contains(new Locale("nb", "NO")) + || !av.contains(new Locale("nn", "NO"))) { + errln("\"nb-NO\" and/or \"nn-NO\" locale(s) not returned from getAvailableLocales()."); } } static String escapeUnicode(String s) { StringBuffer buf = new StringBuffer(); - for (int i=0; i= 0x20 && c <= 0x7F) buf.append(c); - else { + if (c >= 0x20 && c <= 0x7F) { + buf.append(c); + } else { buf.append("\\u"); String h = "000" + Integer.toHexString(c); - if (h.length() > 4) h = h.substring(h.length() - 4); + if (h.length() > 4) { + h = h.substring(h.length() - 4); + } buf.append(h); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Locale/LocaleTestFmwk.java --- a/jdk/test/java/util/Locale/LocaleTestFmwk.java Wed Jul 05 22:29:12 2017 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,267 +0,0 @@ -/* - * Copyright (c) 2010, 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. - */ - -/* - * - * - * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved - * (C) Copyright IBM Corp. 1996 - 1999 - All Rights Reserved - * - * Portions copyright (c) 2007 Sun Microsystems, Inc. - * All Rights Reserved. - * - * The original version of this source code and documentation - * is copyrighted and owned by Taligent, Inc., a wholly-owned - * subsidiary of IBM. These materials are provided under terms - * of a License Agreement between Taligent and Sun. This technology - * is protected by multiple US and International patents. - * - * This notice and attribution to Taligent may not be removed. - * Taligent is a registered trademark of Taligent, Inc. - * - * Permission to use, copy, modify, and distribute this software - * and its documentation for NON-COMMERCIAL purposes and without - * fee is hereby granted provided that this copyright notice - * appears in all copies. Please refer to the file "copyright.html" - * for further important copyright and licensing information. - * - * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF - * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED - * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A - * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR - * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR - * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. - * - */ - -import java.lang.reflect.*; -import java.util.Hashtable; -import java.util.Enumeration; -import java.util.Vector; -import java.io.*; -import java.text.*; - -/** - * LocaleTestFmwk is a base class for tests that can be run conveniently from - * the command line as well as under the Java test harness. - *

    - * Sub-classes implement a set of methods named Test. Each - * of these methods performs some test. Test methods should indicate - * errors by calling either err or errln. This will increment the - * errorCount field and may optionally print a message to the log. - * Debugging information may also be added to the log via the log - * and logln methods. These methods will add their arguments to the - * log only if the test is being run in verbose mode. - */ -public class LocaleTestFmwk { - //------------------------------------------------------------------------ - // 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 LocaleTestFmwk() { - // Create a hashtable containing all the test methods. - testMethods = new Hashtable(); - Method[] methods = getClass().getDeclaredMethods(); - for( int i=0; i 0) { - throw new IllegalArgumentException("encountered " + errorCount + " errors"); - } - } - } - - /** - * Adds given string to the log if we are in verbose mode. - */ - protected void log( String message ) { - if( verbose ) { - indent(indentLevel + 1); - log.print( message ); - } - } - - protected void logln( String message ) { - log(message + System.getProperty("line.separator")); - } - - /** - * Report an error - */ - protected void err( String message ) { - errorCount++; - indent(indentLevel + 1); - log.print( message ); - log.flush(); - - if (!nothrow) { - throw new RuntimeException(message); - } - } - - protected void errln( String message ) { - err(message + System.getProperty("line.separator")); - } - - - protected void writeTestName(String testName) { - indent(indentLevel); - log.print(testName); - log.flush(); - needLineFeed = true; - } - - protected void writeTestResult(int count) { - if (!needLineFeed) { - indent(indentLevel); - log.print("}"); - } - needLineFeed = false; - - if (count != 0) - log.println(" FAILED"); - else - log.println(" Passed"); - } - - private final void indent(int distance) { - if (needLineFeed) { - log.println(" {"); - needLineFeed = false; - } - log.print(spaces.substring(0, distance * 2)); - } - - /** - * Print a usage message for this test class. - */ - void usage() { - System.out.println(getClass().getName() + - ": [-verbose] [-nothrow] [-exitcode] [-prompt] [test names]"); - - System.out.println("test names:"); - Enumeration methodNames = testMethods.keys(); - while( methodNames.hasMoreElements() ) { - System.out.println("\t" + methodNames.nextElement() ); - } - } - - private boolean prompt = false; - private boolean nothrow = false; - private boolean exitcode = false; - protected boolean verbose = false; - - private PrintWriter log; - private int indentLevel = 0; - private boolean needLineFeed = false; - private int errorCount = 0; - - private Hashtable testMethods; - private final String spaces = " "; -} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java --- a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -25,7 +25,7 @@ * @test * @summary Spliterator traversing and splitting tests * @run testng SpliteratorTraversingAndSplittingTest - * @bug 8020016 8071477 + * @bug 8020016 8071477 8072784 8169838 */ import org.testng.annotations.DataProvider; @@ -37,6 +37,7 @@ import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; +import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; @@ -80,7 +81,9 @@ import java.util.function.LongConsumer; import java.util.function.Supplier; import java.util.function.UnaryOperator; +import java.util.stream.IntStream; +import static java.util.stream.Collectors.toList; import static org.testng.Assert.*; import static org.testng.Assert.assertEquals; @@ -883,6 +886,30 @@ cdb.add("new StringBuffer(\"%s\")", StringBuffer::new); } + + Object[][] bitStreamTestcases = new Object[][] { + { "none", IntStream.empty().toArray() }, + { "index 0", IntStream.of(0).toArray() }, + { "index 255", IntStream.of(255).toArray() }, + { "index 0 and 255", IntStream.of(0, 255).toArray() }, + { "every bit", IntStream.range(0, 255).toArray() }, + { "step 2", IntStream.range(0, 255).map(f -> f * 2).toArray() }, + { "step 3", IntStream.range(0, 255).map(f -> f * 3).toArray() }, + { "step 5", IntStream.range(0, 255).map(f -> f * 5).toArray() }, + { "step 7", IntStream.range(0, 255).map(f -> f * 7).toArray() }, + { "1, 10, 100, 1000", IntStream.of(1, 10, 100, 1000).toArray() }, + }; + for (Object[] tc : bitStreamTestcases) { + String description = (String)tc[0]; + int[] exp = (int[])tc[1]; + SpliteratorOfIntDataBuilder db = new SpliteratorOfIntDataBuilder( + data, IntStream.of(exp).boxed().collect(toList())); + + db.add("BitSet.stream.spliterator() {" + description + "}", () -> + IntStream.of(exp).collect(BitSet::new, BitSet::set, BitSet::or). + stream().spliterator() + ); + } return spliteratorOfIntDataProvider = data.toArray(new Object[0][]); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/imageio/plugins/tiff/ReadWithoutBaselineTagSet.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/imageio/plugins/tiff/ReadWithoutBaselineTagSet.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * @test + * @bug 8164750 + * @summary Verify reader does not fail when the BaselineTIFFTagSet is + * removed via the TIFFImageReadParam both when ignoring and + * not ignoring metadata. + */ + +import java.awt.image.BufferedImage; +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.util.Map; +import javax.imageio.IIOImage; +import javax.imageio.ImageIO; +import javax.imageio.ImageReader; +import javax.imageio.ImageWriteParam; +import javax.imageio.ImageWriter; +import javax.imageio.plugins.tiff.BaselineTIFFTagSet; +import javax.imageio.plugins.tiff.TIFFImageReadParam; +import javax.imageio.stream.ImageInputStream; +import javax.imageio.stream.ImageOutputStream; +import javax.imageio.stream.MemoryCacheImageInputStream; +import javax.imageio.stream.MemoryCacheImageOutputStream; + +public class ReadWithoutBaselineTagSet { + private static final int WIDTH = 47; + private static final int HEIGHT = 53; + + private static final Map typeToCompression = + Map.of(BufferedImage.TYPE_3BYTE_BGR, + new String[] {null, "LZW", "JPEG", "ZLib", "PackBits"}, + BufferedImage.TYPE_BYTE_BINARY, + new String[] {null, "CCITT RLE", "CCITT T.4", "CCITT T.6", + "LZW", "PackBits"}, + BufferedImage.TYPE_BYTE_GRAY, + new String[] {null, "LZW", "JPEG", "ZLib", "PackBits"}, + BufferedImage.TYPE_USHORT_GRAY, + new String[] {null, "LZW", "ZLib", "PackBits"}); + + public static void main(String[] args) throws IOException { + test(); + } + + private static void test() throws IOException { + int failures = 0; + + for (int imageType : typeToCompression.keySet()) { + BufferedImage image = new BufferedImage(WIDTH, HEIGHT, imageType); + System.out.println("Image: " + image.toString()); + + for (String compression : typeToCompression.get(imageType)) { + System.out.println("Compression: " + + (compression == null ? "None" : compression)); + ByteArrayOutputStream output = new ByteArrayOutputStream(); + ImageOutputStream ios = new MemoryCacheImageOutputStream(output); + ImageWriter writer = + ImageIO.getImageWritersByFormatName("TIFF").next(); + ImageWriteParam wparam = writer.getDefaultWriteParam(); + if (compression == null) { + wparam.setCompressionMode(ImageWriteParam.MODE_DEFAULT); + } else { + wparam.setCompressionMode(ImageWriteParam.MODE_EXPLICIT); + wparam.setCompressionType(compression); + } + writer.setOutput(ios); + writer.write(null, new IIOImage(image, null, null), wparam); + ios.flush(); + + ImageReader reader = + ImageIO.getImageReadersByFormatName("TIFF").next(); + ByteArrayInputStream input + = new ByteArrayInputStream(output.toByteArray()); + ImageInputStream iis = new MemoryCacheImageInputStream(input); + iis.mark(); + + TIFFImageReadParam rparam = new TIFFImageReadParam(); + rparam.removeAllowedTagSet(BaselineTIFFTagSet.getInstance()); + + reader.setInput(iis, false, false); + BufferedImage resultFalse = reader.read(0, rparam); + if (resultFalse.getWidth() != WIDTH + || resultFalse.getHeight() != HEIGHT) { + System.err.printf("Read image dimensions != %d x %d%n", + WIDTH, HEIGHT); + failures++; + } else { + System.out.println("ignoreMetadata == false test passed"); + } + + iis.reset(); + reader.setInput(iis, false, true); + BufferedImage resultTrue; + try { + resultTrue = reader.read(0, rparam); + if (resultTrue.getWidth() != WIDTH + || resultTrue.getHeight() != HEIGHT) { + System.err.printf("Read image dimensions != %d x %d%n", + WIDTH, HEIGHT); + failures++; + } else { + System.out.println("ignoreMetadata == true test passed"); + } + } catch (Exception e) { + e.printStackTrace(); + failures++; + } + } + } + + if (failures != 0) { + throw new RuntimeException("Test failed with " + + failures + " errors!"); + } + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/net/ssl/finalize/SSLSessionFinalizeTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/net/ssl/finalize/SSLSessionFinalizeTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,355 @@ +/* + * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Test behavior related to finalize + * @run main/othervm SSLSessionFinalizeTest + * @run main/othervm/policy=security.policy SSLSessionFinalizeTest + */ + +import java.io.InputStream; +import java.io.OutputStream; +import java.lang.ref.Reference; +import java.lang.ref.WeakReference; +import java.util.concurrent.ArrayBlockingQueue; + +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSession; +import javax.net.ssl.SSLSessionBindingEvent; +import javax.net.ssl.SSLSessionBindingListener; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +public class SSLSessionFinalizeTest { + + /* + * ============================================================= + * Set the various variables needed for the tests, then + * specify what tests to run on each side. + */ + + /* + * Should we run the client or server in a separate thread? + * Both sides can throw exceptions, but do you have a preference + * as to which side should be the main thread. + */ + static boolean separateServerThread = true; + + /* + * Where do we find the keystores? + */ + static String pathToStores = "../etc"; + static String keyStoreFile = "keystore"; + static String trustStoreFile = "truststore"; + static String passwd = "passphrase"; + + /* + * Is the server ready to serve? + */ + volatile static boolean serverReady = false; + + /* + * Turn on SSL debugging? + */ + static boolean debug = false; + + /* + * If the client or server is doing some kind of object creation + * that the other side depends on, and that thread prematurely + * exits, you may experience a hang. The test harness will + * terminate all hung threads after its timeout has expired, + * currently 3 minutes by default, but you might try to be + * smart about it.... + */ + + /* + * Define the server side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + void doServerSide() throws Exception { + SSLServerSocketFactory sslssf = + (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); + SSLServerSocket sslServerSocket = + (SSLServerSocket) sslssf.createServerSocket(serverPort); + serverPort = sslServerSocket.getLocalPort(); + + /* + * Signal Client, we're ready for his connect. + */ + serverReady = true; + + while (serverReady) { + SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept(); +// System.out.printf(" accept: %s%n", sslSocket); + InputStream sslIS = sslSocket.getInputStream(); + OutputStream sslOS = sslSocket.getOutputStream(); + + sslIS.read(); + sslOS.write(85); + sslOS.flush(); + + sslSocket.close(); + } + } + + /* + * Define the client side of the test. + * + * If the server prematurely exits, serverReady will be set to true + * to avoid infinite hangs. + */ + SBListener doClientSide() throws Exception { + + /* + * Wait for server to get started. + */ + while (!serverReady) { + Thread.sleep(50); + } + + SSLSocketFactory sslsf = + (SSLSocketFactory) SSLSocketFactory.getDefault(); + + try { + SSLSocket sslSocket = (SSLSocket) + sslsf.createSocket("localhost", serverPort); + InputStream sslIS = sslSocket.getInputStream(); + OutputStream sslOS = sslSocket.getOutputStream(); + + sslOS.write(280); + sslOS.flush(); + sslIS.read(); + + sslOS.close(); + sslIS.close(); + + SSLSession sslSession = sslSocket.getSession(); + System.out.printf(" sslSession: %s %n %s%n", sslSession, sslSession.getClass()); + SBListener sbListener = new SBListener(sslSession); + + sslSession.putValue("x", sbListener); + + sslSession.invalidate(); + + sslSocket.close(); + + sslOS = null; + sslIS = null; + sslSession = null; + sslSocket = null; + Reference.reachabilityFence(sslOS); + Reference.reachabilityFence(sslIS); + Reference.reachabilityFence(sslSession); + Reference.reachabilityFence(sslSocket); + + return sbListener; + } catch (Exception ex) { + ex.printStackTrace(); + throw ex; + } + } + + /* + * ============================================================= + * The remainder is just support stuff + */ + + // use any free port by default + volatile int serverPort = 0; + + volatile Exception serverException = null; + volatile Exception clientException = null; + + public static void main(String[] args) throws Exception { + String keyFilename = + System.getProperty("test.src", "./") + "/" + pathToStores + + "/" + keyStoreFile; + String trustFilename = + System.getProperty("test.src", "./") + "/" + pathToStores + + "/" + trustStoreFile; + + System.setProperty("javax.net.ssl.keyStore", keyFilename); + System.setProperty("javax.net.ssl.keyStorePassword", passwd); + System.setProperty("javax.net.ssl.trustStore", trustFilename); + System.setProperty("javax.net.ssl.trustStorePassword", passwd); + + if (debug) + System.setProperty("javax.net.debug", "all"); + + /* + * Start the tests. + */ + new SSLSessionFinalizeTest(); + } + + ArrayBlockingQueue threads = new ArrayBlockingQueue(100); + + ArrayBlockingQueue sbListeners = new ArrayBlockingQueue<>(100); + + /* + * Primary constructor, used to drive remainder of the test. + * + * Fork off the other side, then do your work. + */ + SSLSessionFinalizeTest() throws Exception { + final int count = 1; + if (separateServerThread) { + startServer(true); + startClients(true, count); + } else { + startClients(true, count); + startServer(true); + } + + /* + * Wait for other side to close down. + */ + Thread t; + while ((t = threads.take()) != Thread.currentThread()) { + System.out.printf(" joining: %s%n", t); + t.join(1000L); + } + serverReady = false; + System.gc(); + System.gc(); + + + SBListener listener = null; + while ((listener = sbListeners.poll()) != null) { + if (!listener.check()) { + System.out.printf(" sbListener not called on finalize: %s%n", + listener); + } + } + + /* + * When we get here, the test is pretty much over. + * + * If the main thread excepted, that propagates back + * immediately. If the other thread threw an exception, we + * should report back. + */ + if (serverException != null) { + System.out.print("Server Exception:"); + throw serverException; + } + if (clientException != null) { + System.out.print("Client Exception:"); + throw clientException; + } + } + + void startServer(boolean newThread) throws Exception { + if (newThread) { + Thread t = new Thread("Server") { + public void run() { + try { + doServerSide(); + } catch (Exception e) { + /* + * Our server thread just died. + * + * Release the client, if not active already... + */ + System.err.println("Server died..." + e); + serverReady = true; + serverException = e; + } + } + }; + threads.add(t); + t.setDaemon(true); + t.start(); + } else { + doServerSide(); + } + } + + void startClients(boolean newThread, int count) throws Exception { + for (int i = 0; i < count; i++) { + System.out.printf(" newClient: %d%n", i); + startClient(newThread); + } + serverReady = false; + + threads.add(Thread.currentThread()); // add ourselves at the 'end' + } + void startClient(boolean newThread) throws Exception { + if (newThread) { + Thread t = new Thread("Client") { + public void run() { + try { + sbListeners.add(doClientSide()); + } catch (Exception e) { + /* + * Our client thread just died. + */ + System.err.println("Client died..." + e); + clientException = e; + } + } + }; + System.out.printf(" starting: %s%n", t); + threads.add(t); + t.start(); + } else { + sbListeners.add(doClientSide()); + } + } + + + static class SBListener implements SSLSessionBindingListener { + private volatile int unboundNotified; + private final WeakReference session; + + SBListener(SSLSession session) { + this.unboundNotified = 0; + this.session = new WeakReference(session); + } + + boolean check() { + System.out.printf(" check: %s%n", this); + return unboundNotified > 0 && session.get() == null; + } + + @Override + public void valueBound(SSLSessionBindingEvent event) { + System.out.printf(" valueBound: %s%n", event.getName()); + } + + @Override + public void valueUnbound(SSLSessionBindingEvent event) { + System.out.printf(" valueUnbound: %s%n", event.getName()); + unboundNotified++; + } + + public String toString() { + return "count: " + unboundNotified + + ", ref: " + session.get(); + } + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/net/ssl/finalize/security.policy --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/net/ssl/finalize/security.policy Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,13 @@ +/* + * + */ +grant { + + // used by TestLibrary to determine test environment + permission java.util.PropertyPermission "test.*", "read"; + permission java.util.PropertyPermission "user.dir", "read"; + permission java.util.PropertyPermission "java.home", "read"; + permission java.util.PropertyPermission "javax.net.ssl.*", "write"; + permission java.lang.RuntimePermission "accessClassInPackage.sun.security.ssl"; + permission java.security.AllPermission; +}; diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/net/ssl/templates/SSLSocketSample.java --- a/jdk/test/javax/net/ssl/templates/SSLSocketSample.java Wed Jul 05 22:29:12 2017 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,404 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -// Please run in othervm mode. SunJSSE does not support dynamic system -// properties, no way to re-use system properties in samevm/agentvm mode. - -/* - * @test - * @bug 8161106 - * @summary Improve SSLSocket test template - * @run main/othervm SSLSocketSample - */ - -import java.io.*; -import javax.net.ssl.*; -import java.net.*; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; - -/** - * Template to help speed your client/server tests. - */ -public final class SSLSocketSample { - - /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. - */ - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - private static final boolean separateServerThread = false; - - /* - * Where do we find the keystores? - */ - private static final String pathToStores = "../etc"; - private static final String keyStoreFile = "keystore"; - private static final String trustStoreFile = "truststore"; - private static final String passwd = "passphrase"; - - /* - * Turn on SSL debugging? - */ - private static final boolean debug = false; - - /* - * Is the server ready to serve? - */ - private static final CountDownLatch serverCondition = new CountDownLatch(1); - - /* - * Is the client ready to handshake? - */ - private static final CountDownLatch clientCondition = new CountDownLatch(1); - - /* - * What's the server port? Use any free port by default - */ - private volatile int serverPort = 0; - - /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... - */ - - /* - * Define the server side of the test. - */ - void doServerSide() throws Exception { - SSLServerSocket sslServerSocket; - - // kick start the server side service - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); - sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort); - - serverPort = sslServerSocket.getLocalPort(); - - // Signal the client, the server is ready to accept connection. - serverCondition.countDown(); - - - // Try to accept a connection in 30 seconds. - SSLSocket sslSocket; - try { - sslServerSocket.setSoTimeout(30000); - sslSocket = (SSLSocket)sslServerSocket.accept(); - } catch (SocketTimeoutException ste) { - sslServerSocket.close(); - - // Ignore the test case if no connection within 30 seconds. - System.out.println( - "No incoming client connection in 30 seconds. " + - "Ignore in server side."); - return; - } - - // handle the connection - try { - // Is it the expected client connection? - // - // Naughty test cases or third party routines may try to - // connection to this server port unintentionally. In - // order to mitigate the impact of unexpected client - // connections and avoid intermittent failure, it should - // be checked that the accepted connection is really linked - // to the expected client. - boolean clientIsReady = - clientCondition.await(30L, TimeUnit.SECONDS); - - if (clientIsReady) { - // Run the application in server side. - runServerApplication(sslSocket); - } else { // Otherwise, ignore - // We don't actually care about plain socket connections - // for TLS communication testing generally. Just ignore - // the test if the accepted connection is not linked to - // the expected client or the client connection timeout - // in 30 seconds. - System.out.println( - "The client is not the expected one or timeout. " + - "Ignore in server side."); - } - } finally { - sslSocket.close(); - sslServerSocket.close(); - } - } - - /* - * Define the server side application of the test for the specified socket. - */ - void runServerApplication(SSLSocket socket) throws Exception { - // here comes the test logic - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - /* - * Define the client side of the test. - */ - void doClientSide() throws Exception { - - // Wait for server to get started. - // - // The server side takes care of the issue if the server cannot - // get started in 90 seconds. The client side would just ignore - // the test case if the serer is not ready. - boolean serverIsReady = - serverCondition.await(90L, TimeUnit.SECONDS); - if (!serverIsReady) { - System.out.println( - "The server is not ready yet in 90 seconds. " + - "Ignore in client side."); - return; - } - - SSLSocketFactory sslsf = - (SSLSocketFactory)SSLSocketFactory.getDefault(); - try (SSLSocket sslSocket = (SSLSocket)sslsf.createSocket()) { - try { - sslSocket.connect( - new InetSocketAddress("localhost", serverPort), 15000); - } catch (IOException ioe) { - // The server side may be impacted by naughty test cases or - // third party routines, and cannot accept connections. - // - // Just ignore the test if the connection cannot be - // established. - System.out.println( - "Cannot make a connection in 15 seconds. " + - "Ignore in client side."); - return; - } - - // OK, here the client and server get connected. - - // Signal the server, the client is ready to communicate. - clientCondition.countDown(); - - // There is still a chance in theory that the server thread may - // wait client-ready timeout and then quit. The chance should - // be really rare so we don't consider it until it becomes a - // real problem. - - // Run the application in client side. - runClientApplication(sslSocket); - } - } - - /* - * Define the server side application of the test for the specified socket. - */ - void runClientApplication(SSLSocket socket) throws Exception { - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - /* - * ============================================================= - * The remainder is just support stuff - */ - - private volatile Exception serverException = null; - private volatile Exception clientException = null; - - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Start the tests. - */ - new SSLSocketSample(); - } - - private Thread clientThread = null; - private Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketSample() throws Exception { - Exception startException = null; - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } - - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(boolean newThread) throws Exception { - if (newThread) { - serverThread = new Thread() { - @Override - public void run() { - try { - doServerSide(); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - System.out.println("Server died: " + e); - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - doServerSide(); - } catch (Exception e) { - System.out.println("Server failed: " + e); - serverException = e; - } - } - } - - void startClient(boolean newThread) throws Exception { - if (newThread) { - clientThread = new Thread() { - @Override - public void run() { - try { - doClientSide(); - } catch (Exception e) { - /* - * Our client thread just died. - */ - System.out.println("Client died: " + e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - doClientSide(); - } catch (Exception e) { - System.out.println("Client failed: " + e); - clientException = e; - } - } - } -} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/net/ssl/templates/SSLSocketTemplate.java --- a/jdk/test/javax/net/ssl/templates/SSLSocketTemplate.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/javax/net/ssl/templates/SSLSocketTemplate.java Wed Jul 05 22:30:52 2017 +0200 @@ -21,251 +21,561 @@ * questions. */ -// SunJSSE does not support dynamic system properties, no way to re-use -// system properties in samevm/agentvm mode. +import java.io.FileInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.net.InetSocketAddress; +import java.net.SocketTimeoutException; +import java.security.KeyStore; +import java.security.Security; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLServerSocket; +import javax.net.ssl.SSLServerSocketFactory; +import javax.net.ssl.SSLSocket; +import javax.net.ssl.SSLSocketFactory; + +/** + * This class defines a framework for JSSE tests. + * + * Please run in othervm mode. SunJSSE does not support dynamic system + * properties, no way to re-use system properties in samevm/agentvm mode. + */ /* * @test * @bug 1234567 - * @summary Use this template to help speed your client/server tests. + * @summary Use this class for JSSE tests * @run main/othervm SSLSocketTemplate * @author Brad Wetmore */ -import java.io.*; -import javax.net.ssl.*; - public class SSLSocketTemplate { + public static final String TEST_SRC = System.getProperty("test.src", "."); + /* - * ============================================================= - * Set the various variables needed for the tests, then - * specify what tests to run on each side. + * Where do we find the keystores? */ + public static final String PATH_TO_STORES = "../etc"; + public static final String KEY_STORE_FILE = "keystore"; + public static final String TRUST_STORE_FILE = "truststore"; + public static final String PASSWORD = "passphrase"; + + public static final int FREE_PORT = 0; + + // in seconds + public static final long CLIENT_SIGNAL_TIMEOUT = 30L; + public static final long SERVER_SIGNAL_TIMEOUT = 90L; + + // in millis + public static final int CLIENT_TIMEOUT = 15000; + public static final int SERVER_TIMEOUT = 30000; /* * Should we run the client or server in a separate thread? * Both sides can throw exceptions, but do you have a preference * as to which side should be the main thread. */ - static boolean separateServerThread = false; + private boolean separateServerThread = false; /* - * Where do we find the keystores? + * What's the server port? Use any free port by default */ - static String pathToStores = "../etc"; - static String keyStoreFile = "keystore"; - static String trustStoreFile = "truststore"; - static String passwd = "passphrase"; + private volatile int serverPort; + + private volatile Exception serverException; + private volatile Exception clientException; + + private Thread clientThread; + private Thread serverThread; + + private Peer serverPeer; + private Peer clientPeer; + + private Application serverApplication; + private Application clientApplication; + + private SSLContext context; /* * Is the server ready to serve? */ - volatile static boolean serverReady = false; + private final CountDownLatch serverReadyCondition = new CountDownLatch(1); + + /* + * Is the client ready to handshake? + */ + private final CountDownLatch clientReadyCondition = new CountDownLatch(1); + + /* + * Is the server done? + */ + private final CountDownLatch serverDoneCondition = new CountDownLatch(1); + + /* + * Is the client done? + */ + private final CountDownLatch clientDoneCondition = new CountDownLatch(1); /* - * Turn on SSL debugging? + * Public API. */ - static boolean debug = false; + + public static interface Peer { + void run(SSLSocketTemplate test) throws Exception; + } + + public static interface Application { + void run(SSLSocket socket, SSLSocketTemplate test) throws Exception; + } + + public static void debug() { + debug("ssl"); + } + + public static void debug(String mode) { + System.setProperty("javax.net.debug", mode); + } + + public static void setup(String keyFilename, String trustFilename, + String password) { + + System.setProperty("javax.net.ssl.keyStore", keyFilename); + System.setProperty("javax.net.ssl.keyStorePassword", password); + System.setProperty("javax.net.ssl.trustStore", trustFilename); + System.setProperty("javax.net.ssl.trustStorePassword", password); + } + + public static void setup() throws Exception { + String keyFilename = TEST_SRC + "/" + PATH_TO_STORES + "/" + + KEY_STORE_FILE; + String trustFilename = TEST_SRC + "/" + PATH_TO_STORES + "/" + + TRUST_STORE_FILE; + + setup(keyFilename, trustFilename, PASSWORD); + } + + public static void print(String message, Throwable... errors) { + synchronized (System.out) { + System.out.println(message); + for (Throwable e : errors) { + e.printStackTrace(System.out); + } + } + } + + public static KeyStore loadJksKeyStore(String filename, String password) + throws Exception { + + return loadKeyStore(filename, password, "JKS"); + } + + public static KeyStore loadKeyStore(String filename, String password, + String type) throws Exception { + + KeyStore keystore = KeyStore.getInstance(type); + FileInputStream fis = new FileInputStream(filename); + try { + keystore.load(fis, password.toCharArray()); + } finally { + fis.close(); + } + return keystore; + } + + // Try to accept a connection in 30 seconds. + public static SSLSocket accept(SSLServerSocket sslServerSocket) + throws IOException { + + return accept(sslServerSocket, SERVER_TIMEOUT); + } + + public static SSLSocket accept(SSLServerSocket sslServerSocket, int timeout) + throws IOException { + + try { + sslServerSocket.setSoTimeout(timeout); + return (SSLSocket) sslServerSocket.accept(); + } catch (SocketTimeoutException ste) { + print("Warning: ", ste); + return null; + } + } + + public SSLSocketTemplate setSeparateServerThread( + boolean separateServerThread) { + + this.separateServerThread = separateServerThread; + return this; + } + + public SSLSocketTemplate setServerPort(int serverPort) { + this.serverPort = serverPort; + return this; + } + + public int getServerPort() { + return serverPort; + } + + public SSLSocketTemplate setSSLContext(SSLContext context) { + this.context = context; + return this; + } + + public SSLContext getSSLContext() { + return context; + } + + public SSLServerSocketFactory getSSLServerSocketFactory() { + if (context != null) { + return context.getServerSocketFactory(); + } + + return (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); + } + + public SSLSocketFactory getSSLSocketFactory() { + if (context != null) { + return context.getSocketFactory(); + } + + return (SSLSocketFactory) SSLSocketFactory.getDefault(); + } + + public void signalServerReady() { + serverReadyCondition.countDown(); + } + + public void signalServerDone() { + serverDoneCondition.countDown(); + } + + public boolean waitForClientSignal(long timeout, TimeUnit unit) + throws InterruptedException { + + return clientReadyCondition.await(timeout, unit); + } + + public boolean waitForClientSignal() throws InterruptedException { + return waitForClientSignal(CLIENT_SIGNAL_TIMEOUT, TimeUnit.SECONDS); + } + + public boolean waitForClientDone(long timeout, TimeUnit unit) + throws InterruptedException { + + return clientDoneCondition.await(timeout, unit); + } + + public boolean waitForClientDone() throws InterruptedException { + return waitForClientDone(CLIENT_SIGNAL_TIMEOUT, TimeUnit.SECONDS); + } + + public void signalClientReady() { + clientReadyCondition.countDown(); + } + + public void signalClientDone() { + clientDoneCondition.countDown(); + } + + public boolean waitForServerSignal(long timeout, TimeUnit unit) + throws InterruptedException { + + return serverReadyCondition.await(timeout, unit); + } + + public boolean waitForServerSignal() throws InterruptedException { + return waitForServerSignal(SERVER_SIGNAL_TIMEOUT, TimeUnit.SECONDS); + } + + public boolean waitForServerDone(long timeout, TimeUnit unit) + throws InterruptedException { + + return serverDoneCondition.await(timeout, unit); + } + + public boolean waitForServerDone() throws InterruptedException { + return waitForServerDone(SERVER_SIGNAL_TIMEOUT, TimeUnit.SECONDS); + } + + public SSLSocketTemplate setServerPeer(Peer serverPeer) { + this.serverPeer = serverPeer; + return this; + } + + public Peer getServerPeer() { + return serverPeer; + } + + public SSLSocketTemplate setServerApplication( + Application serverApplication) { + + this.serverApplication = serverApplication; + return this; + } + + public Application getServerApplication() { + return serverApplication; + } + + public SSLSocketTemplate setClientPeer(Peer clientPeer) { + this.clientPeer = clientPeer; + return this; + } + + public Peer getClientPeer() { + return clientPeer; + } + + public SSLSocketTemplate setClientApplication( + Application clientApplication) { + + this.clientApplication = clientApplication; + return this; + } + + public Application getClientApplication() { + return clientApplication; + } + + public void runTest() throws Exception { + if (separateServerThread) { + startServer(true, this); + startClient(false, this); + serverThread.join(); + } else { + startClient(true, this); + startServer(false, this); + clientThread.join(); + } + + if (clientException != null || serverException != null) { + throw new RuntimeException("Test failed"); + } + } + + public SSLSocketTemplate() { + serverPeer = new Peer() { + + @Override + public void run(SSLSocketTemplate test) throws Exception { + doServerSide(test); + } + }; + + clientPeer = new Peer() { + + @Override + public void run(SSLSocketTemplate test) throws Exception { + doClientSide(test); + } + }; + + serverApplication = new Application() { + + @Override + public void run(SSLSocket socket, SSLSocketTemplate test) + throws Exception { + + runServerApplication(socket); + } + + }; + + clientApplication = new Application() { + + @Override + public void run(SSLSocket socket, SSLSocketTemplate test) + throws Exception { + + runClientApplication(socket); + } + }; + } + + public static void main(String args[]) throws Exception { + // reset the security property to make sure that the algorithms + // and keys used in this test are not disabled. + Security.setProperty("jdk.tls.disabledAlgorithms", ""); + + // MD5 is used in this test case, don't disable MD5 algorithm. + Security.setProperty( + "jdk.certpath.disabledAlgorithms", "MD2, RSA keySize < 1024"); + + setup(); + + new SSLSocketTemplate().runTest(); + } /* - * If the client or server is doing some kind of object creation - * that the other side depends on, and that thread prematurely - * exits, you may experience a hang. The test harness will - * terminate all hung threads after its timeout has expired, - * currently 3 minutes by default, but you might try to be - * smart about it.... + * Private part. */ /* * Define the server side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. */ - void doServerSide() throws Exception { - SSLServerSocketFactory sslssf = - (SSLServerSocketFactory)SSLServerSocketFactory.getDefault(); - try (SSLServerSocket sslServerSocket = - (SSLServerSocket)sslssf.createServerSocket(serverPort)) { + private static void doServerSide(SSLSocketTemplate test) throws Exception { + SSLServerSocket sslServerSocket; + + // kick start the server side service + SSLServerSocketFactory sslssf = test.getSSLServerSocketFactory(); + sslServerSocket = (SSLServerSocket)sslssf.createServerSocket(FREE_PORT); + + test.setServerPort(sslServerSocket.getLocalPort()); + print("Server is listening on port " + test.getServerPort()); - serverPort = sslServerSocket.getLocalPort(); + // Signal the client, the server is ready to accept connection. + test.signalServerReady(); + + // Try to accept a connection in 30 seconds. + SSLSocket sslSocket = accept(sslServerSocket); + if (sslSocket == null) { + // Ignore the test case if no connection within 30 seconds. + print("No incoming client connection in 30 seconds. " + + "Ignore in server side."); + return; + } + print("Server accepted connection"); - /* - * Signal Client, we're ready for his connect. - */ - serverReady = true; + // handle the connection + try { + // Is it the expected client connection? + // + // Naughty test cases or third party routines may try to + // connection to this server port unintentionally. In + // order to mitigate the impact of unexpected client + // connections and avoid intermittent failure, it should + // be checked that the accepted connection is really linked + // to the expected client. + boolean clientIsReady = test.waitForClientSignal(); - try (SSLSocket sslSocket = (SSLSocket)sslServerSocket.accept()) { - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); + if (clientIsReady) { + // Run the application in server side. + print("Run server application"); + test.getServerApplication().run(sslSocket, test); + } else { // Otherwise, ignore + // We don't actually care about plain socket connections + // for TLS communication testing generally. Just ignore + // the test if the accepted connection is not linked to + // the expected client or the client connection timeout + // in 30 seconds. + print("The client is not the expected one or timeout. " + + "Ignore in server side."); + } + } finally { + sslSocket.close(); + sslServerSocket.close(); + } - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - } + test.signalServerDone(); + } + + /* + * Define the server side application of the test for the specified socket. + */ + private static void runServerApplication(SSLSocket socket) + throws Exception { + + // here comes the test logic + InputStream sslIS = socket.getInputStream(); + OutputStream sslOS = socket.getOutputStream(); + + sslIS.read(); + sslOS.write(85); + sslOS.flush(); } /* * Define the client side of the test. - * - * If the server prematurely exits, serverReady will be set to true - * to avoid infinite hangs. */ - void doClientSide() throws Exception { + private static void doClientSide(SSLSocketTemplate test) throws Exception { - /* - * Wait for server to get started. - */ - while (!serverReady) { - Thread.sleep(50); + // Wait for server to get started. + // + // The server side takes care of the issue if the server cannot + // get started in 90 seconds. The client side would just ignore + // the test case if the serer is not ready. + boolean serverIsReady = test.waitForServerSignal(); + if (!serverIsReady) { + print("The server is not ready yet in 90 seconds. " + + "Ignore in client side."); + return; } - SSLSocketFactory sslsf = - (SSLSocketFactory)SSLSocketFactory.getDefault(); - try (SSLSocket sslSocket = - (SSLSocket)sslsf.createSocket("localhost", serverPort)) { + SSLSocketFactory sslsf = test.getSSLSocketFactory(); + SSLSocket sslSocket = (SSLSocket)sslsf.createSocket(); + try { + try { + sslSocket.connect( + new InetSocketAddress("localhost", + test.getServerPort()), CLIENT_TIMEOUT); + print("Client connected to server"); + } catch (IOException ioe) { + // The server side may be impacted by naughty test cases or + // third party routines, and cannot accept connections. + // + // Just ignore the test if the connection cannot be + // established. + print("Cannot make a connection in 15 seconds. " + + "Ignore in client side.", ioe); + return; + } - InputStream sslIS = sslSocket.getInputStream(); - OutputStream sslOS = sslSocket.getOutputStream(); + // OK, here the client and server get connected. + + // Signal the server, the client is ready to communicate. + test.signalClientReady(); - sslOS.write(280); - sslOS.flush(); - sslIS.read(); + // There is still a chance in theory that the server thread may + // wait client-ready timeout and then quit. The chance should + // be really rare so we don't consider it until it becomes a + // real problem. + + // Run the application in client side. + print("Run client application"); + test.getClientApplication().run(sslSocket, test); + } finally { + sslSocket.close(); } + + test.signalClientDone(); } /* - * ============================================================= - * The remainder is just support stuff + * Define the client side application of the test for the specified socket. */ - - // use any free port by default - volatile int serverPort = 0; - - volatile Exception serverException = null; - volatile Exception clientException = null; + private static void runClientApplication(SSLSocket socket) + throws Exception { - public static void main(String[] args) throws Exception { - String keyFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + keyStoreFile; - String trustFilename = - System.getProperty("test.src", ".") + "/" + pathToStores + - "/" + trustStoreFile; + InputStream sslIS = socket.getInputStream(); + OutputStream sslOS = socket.getOutputStream(); - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", passwd); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", passwd); - - if (debug) { - System.setProperty("javax.net.debug", "all"); - } - - /* - * Start the tests. - */ - new SSLSocketTemplate(); + sslOS.write(280); + sslOS.flush(); + sslIS.read(); } - Thread clientThread = null; - Thread serverThread = null; - - /* - * Primary constructor, used to drive remainder of the test. - * - * Fork off the other side, then do your work. - */ - SSLSocketTemplate() throws Exception { - Exception startException = null; - try { - if (separateServerThread) { - startServer(true); - startClient(false); - } else { - startClient(true); - startServer(false); - } - } catch (Exception e) { - startException = e; - } - - /* - * Wait for other side to close down. - */ - if (separateServerThread) { - if (serverThread != null) { - serverThread.join(); - } - } else { - if (clientThread != null) { - clientThread.join(); - } - } + private void startServer(boolean newThread, SSLSocketTemplate test) + throws Exception { - /* - * When we get here, the test is pretty much over. - * Which side threw the error? - */ - Exception local; - Exception remote; - - if (separateServerThread) { - remote = serverException; - local = clientException; - } else { - remote = clientException; - local = serverException; - } - - Exception exception = null; - - /* - * Check various exception conditions. - */ - if ((local != null) && (remote != null)) { - // If both failed, return the curthread's exception. - local.initCause(remote); - exception = local; - } else if (local != null) { - exception = local; - } else if (remote != null) { - exception = remote; - } else if (startException != null) { - exception = startException; - } - - /* - * If there was an exception *AND* a startException, - * output it. - */ - if (exception != null) { - if (exception != startException && startException != null) { - exception.addSuppressed(startException); - } - throw exception; - } - - // Fall-through: no exception to throw! - } - - void startServer(boolean newThread) throws Exception { if (newThread) { serverThread = new Thread() { + @Override public void run() { try { - doServerSide(); + serverPeer.run(test); } catch (Exception e) { /* * Our server thread just died. * * Release the client, if not active already... */ - System.err.println("Server died..."); - serverReady = true; + print("Server died ...", e); serverException = e; } } @@ -273,27 +583,29 @@ serverThread.start(); } else { try { - doServerSide(); + serverPeer.run(test); } catch (Exception e) { + print("Server failed ...", e); serverException = e; - } finally { - serverReady = true; } } } - void startClient(boolean newThread) throws Exception { + private void startClient(boolean newThread, SSLSocketTemplate test) + throws Exception { + if (newThread) { clientThread = new Thread() { + @Override public void run() { try { - doClientSide(); + clientPeer.run(test); } catch (Exception e) { /* * Our client thread just died. */ - System.err.println("Client died..."); + print("Client died ...", e); clientException = e; } } @@ -301,8 +613,9 @@ clientThread.start(); } else { try { - doClientSide(); + clientPeer.run(test); } catch (Exception e) { + print("Client failed ...", e); clientException = e; } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/net/ssl/templates/SSLTest.java --- a/jdk/test/javax/net/ssl/templates/SSLTest.java Wed Jul 05 22:29:12 2017 +0200 +++ /dev/null Thu Jan 01 00:00:00 1970 +0000 @@ -1,549 +0,0 @@ -/* - * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - */ - -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.OutputStream; -import java.net.InetSocketAddress; -import java.net.SocketTimeoutException; -import java.security.KeyStore; -import java.util.Arrays; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import javax.net.ssl.SSLContext; -import javax.net.ssl.SSLServerSocket; -import javax.net.ssl.SSLServerSocketFactory; -import javax.net.ssl.SSLSocket; -import javax.net.ssl.SSLSocketFactory; - -/** - * Helper class for JSSE tests. - * - * Please run in othervm mode. SunJSSE does not support dynamic system - * properties, no way to re-use system properties in samevm/agentvm mode. - */ -public class SSLTest { - - public static final String TEST_SRC = System.getProperty("test.src", "."); - - /* - * Where do we find the keystores? - */ - public static final String PATH_TO_STORES = "../etc"; - public static final String KEY_STORE_FILE = "keystore"; - public static final String TRUST_STORE_FILE = "truststore"; - public static final String PASSWORD = "passphrase"; - - public static final int FREE_PORT = 0; - - // in seconds - public static final long CLIENT_SIGNAL_TIMEOUT = 30L; - public static final long SERVER_SIGNAL_TIMEOUT = 90L; - - // in millis - public static final int CLIENT_TIMEOUT = 15000; - public static final int SERVER_TIMEOUT = 30000; - - /* - * Should we run the client or server in a separate thread? - * Both sides can throw exceptions, but do you have a preference - * as to which side should be the main thread. - */ - private boolean separateServerThread = false; - - /* - * What's the server port? Use any free port by default - */ - private volatile int serverPort; - - private volatile Exception serverException; - private volatile Exception clientException; - - private Thread clientThread; - private Thread serverThread; - - private Peer serverPeer; - private Peer clientPeer; - - private Application serverApplication; - private Application clientApplication; - - private SSLContext context; - - /* - * Is the server ready to serve? - */ - private final CountDownLatch serverReadyCondition = new CountDownLatch(1); - - /* - * Is the client ready to handshake? - */ - private final CountDownLatch clientReadyCondition = new CountDownLatch(1); - - /* - * Is the server done? - */ - private final CountDownLatch serverDoneCondition = new CountDownLatch(1); - - /* - * Is the client done? - */ - private final CountDownLatch clientDoneCondition = new CountDownLatch(1); - - /* - * Public API. - */ - - public static interface Peer { - void run(SSLTest test) throws Exception; - } - - public static interface Application { - void run(SSLSocket socket, SSLTest test) throws Exception; - } - - public static void debug() { - debug("ssl"); - } - - public static void debug(String mode) { - System.setProperty("javax.net.debug", mode); - } - - public static void setup(String keyFilename, String trustFilename, - String password) { - - System.setProperty("javax.net.ssl.keyStore", keyFilename); - System.setProperty("javax.net.ssl.keyStorePassword", password); - System.setProperty("javax.net.ssl.trustStore", trustFilename); - System.setProperty("javax.net.ssl.trustStorePassword", password); - } - - public static void setup() throws Exception { - String keyFilename = TEST_SRC + "/" + PATH_TO_STORES + "/" - + KEY_STORE_FILE; - String trustFilename = TEST_SRC + "/" + PATH_TO_STORES + "/" - + TRUST_STORE_FILE; - - setup(keyFilename, trustFilename, PASSWORD); - } - - public static void print(String message, Throwable... errors) { - synchronized (System.out) { - System.out.println(message); - Arrays.stream(errors).forEach(e -> e.printStackTrace(System.out)); - } - } - - public static KeyStore loadJksKeyStore(String filename, String password) - throws Exception { - - return loadKeyStore(filename, password, "JKS"); - } - - public static KeyStore loadKeyStore(String filename, String password, - String type) throws Exception { - - KeyStore keystore = KeyStore.getInstance(type); - try (FileInputStream fis = new FileInputStream(filename)) { - keystore.load(fis, password.toCharArray()); - } - return keystore; - } - - // Try to accept a connection in 30 seconds. - public static SSLSocket accept(SSLServerSocket sslServerSocket) - throws IOException { - - return accept(sslServerSocket, SERVER_TIMEOUT); - } - - public static SSLSocket accept(SSLServerSocket sslServerSocket, int timeout) - throws IOException { - - try { - sslServerSocket.setSoTimeout(timeout); - return (SSLSocket) sslServerSocket.accept(); - } catch (SocketTimeoutException ste) { - sslServerSocket.close(); - return null; - } - } - - public SSLTest setSeparateServerThread(boolean separateServerThread) { - this.separateServerThread = separateServerThread; - return this; - } - - public SSLTest setServerPort(int serverPort) { - this.serverPort = serverPort; - return this; - } - - public int getServerPort() { - return serverPort; - } - - public SSLTest setSSLContext(SSLContext context) { - this.context = context; - return this; - } - - public SSLContext getSSLContext() { - return context; - } - - public SSLServerSocketFactory getSSLServerSocketFactory() { - if (context != null) { - return context.getServerSocketFactory(); - } - - return (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); - } - - public SSLSocketFactory getSSLSocketFactory() { - if (context != null) { - return context.getSocketFactory(); - } - - return (SSLSocketFactory) SSLSocketFactory.getDefault(); - } - - public void signalServerReady() { - serverReadyCondition.countDown(); - } - - public void signalServerDone() { - serverDoneCondition.countDown(); - } - - public boolean waitForClientSignal(long timeout, TimeUnit unit) - throws InterruptedException { - - return clientReadyCondition.await(timeout, unit); - } - - public boolean waitForClientSignal() throws InterruptedException { - return waitForClientSignal(CLIENT_SIGNAL_TIMEOUT, TimeUnit.SECONDS); - } - - public boolean waitForClientDone(long timeout, TimeUnit unit) - throws InterruptedException { - - return clientDoneCondition.await(timeout, unit); - } - - public boolean waitForClientDone() throws InterruptedException { - return waitForClientDone(CLIENT_SIGNAL_TIMEOUT, TimeUnit.SECONDS); - } - - public void signalClientReady() { - clientReadyCondition.countDown(); - } - - public void signalClientDone() { - clientDoneCondition.countDown(); - } - - public boolean waitForServerSignal(long timeout, TimeUnit unit) - throws InterruptedException { - - return serverReadyCondition.await(timeout, unit); - } - - public boolean waitForServerSignal() throws InterruptedException { - return waitForServerSignal(SERVER_SIGNAL_TIMEOUT, TimeUnit.SECONDS); - } - - public boolean waitForServerDone(long timeout, TimeUnit unit) - throws InterruptedException { - - return serverDoneCondition.await(timeout, unit); - } - - public boolean waitForServerDone() throws InterruptedException { - return waitForServerDone(SERVER_SIGNAL_TIMEOUT, TimeUnit.SECONDS); - } - - public SSLTest setServerPeer(Peer serverPeer) { - this.serverPeer = serverPeer; - return this; - } - - public Peer getServerPeer() { - return serverPeer; - } - - public SSLTest setServerApplication(Application serverApplication) { - this.serverApplication = serverApplication; - return this; - } - - public Application getServerApplication() { - return serverApplication; - } - - public SSLTest setClientPeer(Peer clientPeer) { - this.clientPeer = clientPeer; - return this; - } - - public Peer getClientPeer() { - return clientPeer; - } - - public SSLTest setClientApplication(Application clientApplication) { - this.clientApplication = clientApplication; - return this; - } - - public Application getClientApplication() { - return clientApplication; - } - - public void runTest() throws Exception { - if (separateServerThread) { - startServer(true, this); - startClient(false, this); - serverThread.join(); - } else { - startClient(true, this); - startServer(false, this); - clientThread.join(); - } - - if (clientException != null || serverException != null) { - throw new RuntimeException("Test failed"); - } - } - - public SSLTest() { - serverPeer = (test) -> doServerSide(test); - clientPeer = (test) -> doClientSide(test); - serverApplication = (socket, test) -> runServerApplication(socket); - clientApplication = (socket, test) -> runClientApplication(socket); - } - - /* - * Private part. - */ - - - /* - * Define the server side of the test. - */ - private static void doServerSide(SSLTest test) throws Exception { - SSLServerSocket sslServerSocket; - - // kick start the server side service - SSLServerSocketFactory sslssf = test.getSSLServerSocketFactory(); - sslServerSocket = (SSLServerSocket)sslssf.createServerSocket(FREE_PORT); - - test.setServerPort(sslServerSocket.getLocalPort()); - print("Server is listening on port " + test.getServerPort()); - - // Signal the client, the server is ready to accept connection. - test.signalServerReady(); - - // Try to accept a connection in 30 seconds. - SSLSocket sslSocket = accept(sslServerSocket); - if (sslSocket == null) { - // Ignore the test case if no connection within 30 seconds. - print("No incoming client connection in 30 seconds. " - + "Ignore in server side."); - return; - } - print("Server accepted connection"); - - // handle the connection - try { - // Is it the expected client connection? - // - // Naughty test cases or third party routines may try to - // connection to this server port unintentionally. In - // order to mitigate the impact of unexpected client - // connections and avoid intermittent failure, it should - // be checked that the accepted connection is really linked - // to the expected client. - boolean clientIsReady = test.waitForClientSignal(); - - if (clientIsReady) { - // Run the application in server side. - print("Run server application"); - test.getServerApplication().run(sslSocket, test); - } else { // Otherwise, ignore - // We don't actually care about plain socket connections - // for TLS communication testing generally. Just ignore - // the test if the accepted connection is not linked to - // the expected client or the client connection timeout - // in 30 seconds. - print("The client is not the expected one or timeout. " - + "Ignore in server side."); - } - } finally { - sslSocket.close(); - sslServerSocket.close(); - } - - test.signalServerDone(); - } - - /* - * Define the server side application of the test for the specified socket. - */ - private static void runServerApplication(SSLSocket socket) - throws Exception { - - // here comes the test logic - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslIS.read(); - sslOS.write(85); - sslOS.flush(); - } - - /* - * Define the client side of the test. - */ - private static void doClientSide(SSLTest test) throws Exception { - - // Wait for server to get started. - // - // The server side takes care of the issue if the server cannot - // get started in 90 seconds. The client side would just ignore - // the test case if the serer is not ready. - boolean serverIsReady = test.waitForServerSignal(); - if (!serverIsReady) { - print("The server is not ready yet in 90 seconds. " - + "Ignore in client side."); - return; - } - - SSLSocketFactory sslsf = test.getSSLSocketFactory(); - try (SSLSocket sslSocket = (SSLSocket)sslsf.createSocket()) { - try { - sslSocket.connect( - new InetSocketAddress("localhost", - test.getServerPort()), CLIENT_TIMEOUT); - print("Client connected to server"); - } catch (IOException ioe) { - // The server side may be impacted by naughty test cases or - // third party routines, and cannot accept connections. - // - // Just ignore the test if the connection cannot be - // established. - print("Cannot make a connection in 15 seconds. " - + "Ignore in client side.", ioe); - return; - } - - // OK, here the client and server get connected. - - // Signal the server, the client is ready to communicate. - test.signalClientReady(); - - // There is still a chance in theory that the server thread may - // wait client-ready timeout and then quit. The chance should - // be really rare so we don't consider it until it becomes a - // real problem. - - // Run the application in client side. - print("Run client application"); - test.getClientApplication().run(sslSocket, test); - } - - test.signalClientDone(); - } - - /* - * Define the client side application of the test for the specified socket. - */ - private static void runClientApplication(SSLSocket socket) - throws Exception { - - InputStream sslIS = socket.getInputStream(); - OutputStream sslOS = socket.getOutputStream(); - - sslOS.write(280); - sslOS.flush(); - sslIS.read(); - } - - private void startServer(boolean newThread, SSLTest test) throws Exception { - if (newThread) { - serverThread = new Thread() { - @Override - public void run() { - try { - serverPeer.run(test); - } catch (Exception e) { - /* - * Our server thread just died. - * - * Release the client, if not active already... - */ - print("Server died ...", e); - serverException = e; - } - } - }; - serverThread.start(); - } else { - try { - serverPeer.run(test); - } catch (Exception e) { - print("Server failed ...", e); - serverException = e; - } - } - } - - private void startClient(boolean newThread, SSLTest test) throws Exception { - if (newThread) { - clientThread = new Thread() { - @Override - public void run() { - try { - clientPeer.run(test); - } catch (Exception e) { - /* - * Our client thread just died. - */ - print("Client died ...", e); - clientException = e; - } - } - }; - clientThread.start(); - } else { - try { - clientPeer.run(test); - } catch (Exception e) { - print("Client failed ...", e); - clientException = e; - } - } - } -} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java --- a/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -27,6 +27,8 @@ * @key intermittent * @summary test RMI-IIOP with value object return * @modules java.corba + * java.naming + * java.rmi * @library /lib/testlibrary * @build jdk.testlibrary.* * @compile Test.java Test3.java Test4.java diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java --- a/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -27,6 +27,8 @@ * @summary test RMI-IIOP call with ConcurrentHashMap as an argument * @library /lib/testlibrary * @modules java.corba + * java.naming + * java.rmi * @build jdk.testlibrary.* * @compile Test.java HelloInterface.java HelloServer.java HelloClient.java * HelloImpl.java _HelloImpl_Tie.java _HelloInterface_Stub.java ConcurrentHashMapTest.java diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/sound/sampled/AudioFileFormat/TypeEqualsToNull.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/sound/sampled/AudioFileFormat/TypeEqualsToNull.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.sound.sampled.AudioFileFormat; + +/** + * @test + * @bug 8168998 + */ +public final class TypeEqualsToNull { + + public static void main(final String[] args) { + final AudioFileFormat.Type type; + try { + type = new AudioFileFormat.Type(null, null); + } catch (final Exception ignored) { + // behaviour of null is not specified so ignore possible exceptions + return; + } + final Object stub = new Object() { + @Override + public String toString() { + return null; + } + }; + if (stub.equals(type) || type.equals(stub)) { + throw new RuntimeException("Should not be equal"); + } + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/sound/sampled/AudioFormat/EncodingEqualsToNull.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/sound/sampled/AudioFormat/EncodingEqualsToNull.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import javax.sound.sampled.AudioFormat; + +/** + * @test + * @bug 8168998 + */ +public final class EncodingEqualsToNull { + + public static void main(final String[] args) { + final AudioFormat.Encoding enc; + try { + enc = new AudioFormat.Encoding(null); + } catch (final Exception ignored) { + // behaviour of null is not specified so ignore possible exceptions + return; + } + final Object stub = new Object() { + @Override + public String toString() { + return null; + } + }; + if (stub.equals(enc) || enc.equals(stub)) { + throw new RuntimeException("Should not be equal"); + } + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java --- a/jdk/test/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/javax/sound/sampled/Clip/OpenNonIntegralNumberOfSampleframes.java Wed Jul 05 22:30:52 2017 +0200 @@ -97,7 +97,8 @@ System.err.println("af = " + af); System.err.println("bufferSize = " + bufferSize); throw new RuntimeException("Expected exception is not thrown"); - } catch (final LineUnavailableException ignored) { + } catch (IllegalArgumentException + | LineUnavailableException ignored) { // the test is not applicable } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/swing/JEditorPane/8080972/TestJEditor.java --- a/jdk/test/javax/swing/JEditorPane/8080972/TestJEditor.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/javax/swing/JEditorPane/8080972/TestJEditor.java Wed Jul 05 22:30:52 2017 +0200 @@ -36,7 +36,7 @@ /* * @test - * @bug 8080972 + * @bug 8080972 8169887 * @summary Audit Core Reflection in module java.desktop for places that will * require changes to work with modules * @author Alexander Scherbatiy diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/swing/JViewport/8164032/JViewPortBackingStoreImageTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/swing/JViewport/8164032/JViewPortBackingStoreImageTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,258 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.WindowAdapter; +import java.awt.event.WindowEvent; +import java.util.HashMap; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; +import javax.swing.JButton; +import javax.swing.JComponent; +import javax.swing.JFrame; +import javax.swing.JPanel; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextPane; +import javax.swing.JViewport; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.text.BadLocationException; +import javax.swing.text.DefaultStyledDocument; +import javax.swing.text.Style; +import javax.swing.text.StyleConstants; +import javax.swing.text.StyleContext; + +/* + * @test + * @bug 8164032 8156217 + * @summary JViewport backing store image is not scaled on HiDPI display + * @run main/manual JViewPortBackingStoreImageTest + */ +public class JViewPortBackingStoreImageTest { + + private static volatile boolean testResult = false; + private static volatile CountDownLatch countDownLatch; + private static final String INSTRUCTIONS = "INSTRUCTIONS:\n\n" + + "Verify text is drawn with high resolution and text selection " + + "is not shifted when JViewPort is used on HiDPI display.\n\n" + + "If the display does not support HiDPI mode press PASS.\n\n" + + "1. Check that the text does not have low resolution.\n" + + "If no, press FAIL.\n\n" + + "2. Select the current text from the end to the beginning.\n" + + "\n" + + "If the text is slightly shiftted from one side to another\n" + + "and back during selection press Fail.\n" + + "Otherwise, press Pass."; + + private static DefaultStyledDocument doc; + private static StyleContext styles; + private static HashMap contentAttributes; + + public static void main(String args[]) throws Exception { + countDownLatch = new CountDownLatch(1); + + SwingUtilities.invokeLater(JViewPortBackingStoreImageTest::createUI); + countDownLatch.await(15, TimeUnit.MINUTES); + + if (!testResult) { + throw new RuntimeException("Test fails!"); + } + } + + private static void createUI() { + + try { + UIManager.setLookAndFeel("javax.swing.plaf.nimbus.NimbusLookAndFeel"); + } catch (Exception e) { + throw new RuntimeException(e); + } + + final JFrame mainFrame = new JFrame(); + GridBagLayout layout = new GridBagLayout(); + JPanel mainControlPanel = new JPanel(layout); + JPanel resultButtonPanel = new JPanel(layout); + + GridBagConstraints gbc = new GridBagConstraints(); + + gbc.gridx = 0; + gbc.gridy = 0; + gbc.insets = new Insets(5, 15, 5, 15); + gbc.fill = GridBagConstraints.HORIZONTAL; + mainControlPanel.add(createComponent(), gbc); + + JTextArea instructionTextArea = new JTextArea(); + instructionTextArea.setText(INSTRUCTIONS); + instructionTextArea.setEditable(false); + instructionTextArea.setBackground(Color.white); + + gbc.gridx = 0; + gbc.gridy = 1; + gbc.fill = GridBagConstraints.HORIZONTAL; + mainControlPanel.add(instructionTextArea, gbc); + + JButton passButton = new JButton("Pass"); + passButton.setActionCommand("Pass"); + passButton.addActionListener((ActionEvent e) -> { + testResult = true; + mainFrame.dispose(); + countDownLatch.countDown(); + + }); + + JButton failButton = new JButton("Fail"); + failButton.setActionCommand("Fail"); + failButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(ActionEvent e) { + mainFrame.dispose(); + countDownLatch.countDown(); + } + }); + + gbc.gridx = 0; + gbc.gridy = 0; + + resultButtonPanel.add(passButton, gbc); + + gbc.gridx = 1; + gbc.gridy = 0; + resultButtonPanel.add(failButton, gbc); + + gbc.gridx = 0; + gbc.gridy = 2; + mainControlPanel.add(resultButtonPanel, gbc); + + mainFrame.add(mainControlPanel); + mainFrame.pack(); + + mainFrame.addWindowListener(new WindowAdapter() { + + @Override + public void windowClosing(WindowEvent e) { + mainFrame.dispose(); + countDownLatch.countDown(); + } + }); + mainFrame.setVisible(true); + } + + private static JComponent createComponent() { + createStyles(); + for (int i = 0; i < data.length; i++) { + Paragraph p = data[i]; + addParagraph(p); + } + + JTextPane textPane = new JTextPane(doc); + + JScrollPane scroller = new JScrollPane(); + JViewport port = scroller.getViewport(); + port.setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); + port.add(textPane); + + return scroller; + } + + static void createStyles() { + styles = new StyleContext(); + doc = new DefaultStyledDocument(styles); + contentAttributes = new HashMap<>(); + + // no attributes defined + Style s = styles.addStyle(null, null); + contentAttributes.put("none", s); + + Style def = styles.getStyle(StyleContext.DEFAULT_STYLE); + + Style heading = styles.addStyle("heading", def); + StyleConstants.setFontFamily(heading, "SansSerif"); + StyleConstants.setBold(heading, true); + StyleConstants.setAlignment(heading, StyleConstants.ALIGN_CENTER); + StyleConstants.setSpaceAbove(heading, 10); + StyleConstants.setSpaceBelow(heading, 10); + StyleConstants.setFontSize(heading, 18); + + // Title + Style sty = styles.addStyle("title", heading); + StyleConstants.setFontSize(sty, 32); + + // author + sty = styles.addStyle("author", heading); + StyleConstants.setItalic(sty, true); + StyleConstants.setSpaceBelow(sty, 25); + } + + static void addParagraph(Paragraph p) { + try { + Style s = null; + for (int i = 0; i < p.data.length; i++) { + AttributedContent run = p.data[i]; + s = contentAttributes.get(run.attr); + doc.insertString(doc.getLength(), run.content, s); + } + + Style ls = styles.getStyle(p.logical); + doc.setLogicalStyle(doc.getLength() - 1, ls); + doc.insertString(doc.getLength(), "\n", null); + } catch (BadLocationException e) { + throw new RuntimeException(e); + } + } + + private static Paragraph[] data = new Paragraph[]{ + new Paragraph("title", new AttributedContent[]{ + new AttributedContent("none", "ALICE'S ADVENTURES IN WONDERLAND") + }), + new Paragraph("author", new AttributedContent[]{ + new AttributedContent("none", "Lewis Carroll") + }), + new Paragraph("heading", new AttributedContent[]{ + new AttributedContent("alice", " ") + })}; + + static class Paragraph { + + Paragraph(String logical, AttributedContent[] data) { + this.logical = logical; + this.data = data; + } + String logical; + AttributedContent[] data; + } + + static class AttributedContent { + + AttributedContent(String attr, String content) { + this.attr = attr; + this.content = content; + } + String attr; + String content; + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/swing/plaf/basic/BasicGraphicsUtils/8132119/bug8132119.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/javax/swing/plaf/basic/BasicGraphicsUtils/8132119/bug8132119.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,339 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.awt.Color; +import java.awt.Font; +import java.awt.FontMetrics; +import java.awt.Graphics2D; +import java.awt.GraphicsEnvironment; +import java.awt.font.FontRenderContext; +import java.awt.font.NumericShaper; +import java.awt.font.TextAttribute; +import java.awt.font.TextLayout; +import java.awt.image.BufferedImage; +import java.util.HashMap; +import javax.swing.JComponent; +import javax.swing.JLabel; +import javax.swing.SwingUtilities; +import javax.swing.UIManager; +import javax.swing.plaf.basic.BasicGraphicsUtils; +import javax.swing.plaf.metal.MetalLookAndFeel; + +/** + * @test + * @bug 8132119 8168992 + * @author Alexandr Scherbatiy + * @summary Provide public API for text related methods in SwingBasicGraphicsUtils2 + */ +public class bug8132119 { + + private static final int WIDTH = 50; + private static final int HEIGHT = 50; + private static final Color DRAW_COLOR = Color.RED; + private static final Color BACKGROUND_COLOR = Color.GREEN; + private static final NumericShaper NUMERIC_SHAPER = NumericShaper.getShaper( + NumericShaper.ARABIC); + + public static void main(String[] args) throws Exception { + SwingUtilities.invokeAndWait(bug8132119::testStringMethods); + } + + private static void testStringMethods() { + setMetalLAF(); + testStringWidth(); + testStringClip(); + testDrawEmptyString(); + testDrawString(false); + testDrawString(true); + checkNullArguments(); + } + + private static void testStringWidth() { + + String str = "12345678910\u036F"; + JComponent comp = createComponent(str); + Font font = comp.getFont(); + FontMetrics fontMetrics = comp.getFontMetrics(font); + float stringWidth = BasicGraphicsUtils.getStringWidth(comp, fontMetrics, str); + + if (stringWidth == fontMetrics.stringWidth(str)) { + throw new RuntimeException("Numeric shaper is not used!"); + } + + if (stringWidth != getLayoutWidth(str, font, NUMERIC_SHAPER)) { + throw new RuntimeException("Wrong text width!"); + } + } + + private static void testStringClip() { + + String str = "1234567890"; + JComponent comp = createComponent(str); + FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont()); + + int width = (int) BasicGraphicsUtils.getStringWidth(comp, fontMetrics, str); + + String clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, width); + checkClippedString(str, clip, str); + + clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, width + 1); + checkClippedString(str, clip, str); + + clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, -1); + checkClippedString(str, clip, "..."); + + clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, str, 0); + checkClippedString(str, clip, "..."); + + clip = BasicGraphicsUtils.getClippedString(comp, fontMetrics, + str, width - width / str.length()); + int endIndex = str.length() - 3; + checkClippedString(str, clip, str.substring(0, endIndex) + "..."); + } + + private static void checkClippedString(String str, String res, String golden) { + if (!golden.equals(res)) { + throw new RuntimeException(String.format("The string '%s' is not " + + "properly clipped. The result is '%s' instead of '%s'", + str, res, golden)); + } + } + + private static void testDrawEmptyString() { + JLabel label = new JLabel(); + BufferedImage buffImage = createBufferedImage(50, 50); + Graphics2D g2 = buffImage.createGraphics(); + g2.setColor(DRAW_COLOR); + BasicGraphicsUtils.drawString(null, g2, null, 0, 0); + BasicGraphicsUtils.drawString(label, g2, null, 0, 0); + BasicGraphicsUtils.drawString(null, g2, "", 0, 0); + BasicGraphicsUtils.drawString(label, g2, "", 0, 0); + BasicGraphicsUtils.drawStringUnderlineCharAt(null, g2, null, 3, 0, 0); + BasicGraphicsUtils.drawStringUnderlineCharAt(label, g2, null, 3, 0, 0); + BasicGraphicsUtils.drawStringUnderlineCharAt(null, g2, "", 3, 0, 0); + BasicGraphicsUtils.drawStringUnderlineCharAt(label, g2, "", 3, 0, 0); + g2.dispose(); + checkImageIsEmpty(buffImage); + } + + private static void testDrawString(boolean underlined) { + String str = "AOB"; + JComponent comp = createComponent(str); + + BufferedImage buffImage = createBufferedImage(WIDTH, HEIGHT); + Graphics2D g2 = buffImage.createGraphics(); + + g2.setColor(DRAW_COLOR); + g2.setFont(comp.getFont()); + + FontMetrics fontMetrices = comp.getFontMetrics(comp.getFont()); + float width = BasicGraphicsUtils.getStringWidth(comp, fontMetrices, str); + float x = (WIDTH - width) / 2; + int y = 3 * HEIGHT / 4; + + if (underlined) { + BasicGraphicsUtils.drawStringUnderlineCharAt(comp, g2, str, 1, x, y); + } else { + BasicGraphicsUtils.drawString(comp, g2, str, x, y); + } + g2.dispose(); + + float xx = (WIDTH - width / 8) / 2; + checkImageContainsSymbol(buffImage, (int) xx, underlined ? 3 : 2); + } + + private static void checkNullArguments() { + + Graphics2D g = null; + try { + String text = "Test"; + JComponent component = new JLabel(text); + BufferedImage img = createBufferedImage(100, 100); + g = img.createGraphics(); + checkNullArguments(component, g, text); + } finally { + g.dispose(); + } + } + + private static void checkNullArguments(JComponent comp, Graphics2D g, + String text) { + + checkNullArgumentsDrawString(comp, g, text); + checkNullArgumentsDrawStringUnderlineCharAt(comp, g, text); + checkNullArgumentsGetClippedString(comp, text); + checkNullArgumentsGetStringWidth(comp, text); + } + + private static void checkNullArgumentsDrawString(JComponent comp, Graphics2D g, + String text) { + + float x = 50; + float y = 50; + BasicGraphicsUtils.drawString(null, g, text, x, y); + BasicGraphicsUtils.drawString(comp, g, null, x, y); + + try { + BasicGraphicsUtils.drawString(comp, null, text, x, y); + } catch (NullPointerException e) { + return; + } + + throw new RuntimeException("NPE is not thrown"); + } + + private static void checkNullArgumentsDrawStringUnderlineCharAt( + JComponent comp, Graphics2D g, String text) { + + int x = 50; + int y = 50; + BasicGraphicsUtils.drawStringUnderlineCharAt(null, g, text, 1, x, y); + BasicGraphicsUtils.drawStringUnderlineCharAt(comp, g, null, 1, x, y); + + try { + BasicGraphicsUtils.drawStringUnderlineCharAt(comp, null, text, 1, x, y); + } catch (NullPointerException e) { + return; + } + + throw new RuntimeException("NPE is not thrown"); + } + + private static void checkNullArgumentsGetClippedString( + JComponent comp, String text) { + + FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont()); + + BasicGraphicsUtils.getClippedString(null, fontMetrics, text, 1); + String result = BasicGraphicsUtils.getClippedString(comp, fontMetrics, null, 1); + if (!"".equals(result)) { + throw new RuntimeException("Empty string is not returned!"); + } + + try { + BasicGraphicsUtils.getClippedString(comp, null, text, 1); + } catch (NullPointerException e) { + return; + } + + throw new RuntimeException("NPE is not thrown"); + } + + private static void checkNullArgumentsGetStringWidth(JComponent comp, + String text) { + + FontMetrics fontMetrics = comp.getFontMetrics(comp.getFont()); + BasicGraphicsUtils.getStringWidth(null, fontMetrics, text); + float result = BasicGraphicsUtils.getStringWidth(comp, fontMetrics, null); + + if (result != 0) { + throw new RuntimeException("The string length is not 0"); + } + + try { + BasicGraphicsUtils.getStringWidth(comp, null, text); + } catch (NullPointerException e) { + return; + } + + throw new RuntimeException("NPE is not thrown"); + } + + private static void setMetalLAF() { + try { + UIManager.setLookAndFeel(new MetalLookAndFeel()); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + private static JComponent createComponent(String str) { + JComponent comp = new JLabel(str); + comp.setSize(WIDTH, HEIGHT); + comp.putClientProperty(TextAttribute.NUMERIC_SHAPING, NUMERIC_SHAPER); + comp.setFont(getFont()); + return comp; + } + + private static Font getFont() { + GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment(); + String[] fontNames = ge.getAvailableFontFamilyNames(); + String fontName = fontNames[0]; + for (String name : fontNames) { + if ("Arial".equals(name)) { + fontName = name; + break; + } + } + return new Font(fontName, Font.PLAIN, 28); + } + + private static float getLayoutWidth(String text, Font font, NumericShaper shaper) { + HashMap map = new HashMap(); + map.put(TextAttribute.FONT, font); + map.put(TextAttribute.NUMERIC_SHAPING, shaper); + FontRenderContext frc = new FontRenderContext(null, false, false); + TextLayout layout = new TextLayout(text, map, frc); + return layout.getAdvance(); + } + + private static void checkImageIsEmpty(BufferedImage buffImage) { + int background = BACKGROUND_COLOR.getRGB(); + + for (int i = 0; i < buffImage.getWidth(); i++) { + for (int j = 0; j < buffImage.getHeight(); j++) { + if (background != buffImage.getRGB(i, j)) { + throw new RuntimeException("Image is not empty!"); + } + } + } + } + + private static void checkImageContainsSymbol(BufferedImage buffImage, + int x, int intersections) { + int background = BACKGROUND_COLOR.getRGB(); + boolean isBackground = true; + int backgroundChangesCount = 0; + + for (int y = 0; y < buffImage.getHeight(); y++) { + if (!(isBackground ^ (background != buffImage.getRGB(x, y)))) { + isBackground = !isBackground; + backgroundChangesCount++; + } + } + if (backgroundChangesCount != intersections * 2) { + throw new RuntimeException("String is not properly drawn!"); + } + } + + private static BufferedImage createBufferedImage(int width, int height) { + BufferedImage bufffImage = new BufferedImage(width, height, + BufferedImage.TYPE_INT_RGB); + + Graphics2D g = bufffImage.createGraphics(); + g.setColor(BACKGROUND_COLOR); + g.fillRect(0, 0, width, height); + g.dispose(); + return bufffImage; + } +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/swing/text/GlyphPainter2/6427244/bug6427244.java --- a/jdk/test/javax/swing/text/GlyphPainter2/6427244/bug6427244.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/javax/swing/text/GlyphPainter2/6427244/bug6427244.java Wed Jul 05 22:30:52 2017 +0200 @@ -23,11 +23,11 @@ */ /* @test - @bug 6427244 8144240 + @bug 6427244 8144240 8166003 @summary Test that pressing HOME correctly moves caret in I18N document. @author Sergey Groznyh @library ../../../regtesthelpers - @build JRobot Util TestCase + @build JRobot @run main bug6427244 */ @@ -36,12 +36,13 @@ import java.awt.Point; import java.awt.Shape; import java.awt.event.KeyEvent; +import javax.swing.JComponent; import javax.swing.JFrame; import javax.swing.JTextPane; import javax.swing.SwingUtilities; import javax.swing.text.Position; -public class bug6427244 extends TestCase { +public class bug6427244 { private static final JRobot ROBOT = JRobot.getRobot(); final static int TP_SIZE = 200; @@ -105,13 +106,25 @@ dim = c.getSize(); } }); - Util.blockTillDisplayed(tp); + blockTillDisplayed(tp); ROBOT.waitForIdle(); } catch (Exception ex) { throw new RuntimeException(ex); } } + void blockTillDisplayed(JComponent comp) { + if(comp != null) { + while (!comp.isVisible()) { + try { + Thread.sleep(1000); + } catch (InterruptedException ie) { + /* No-op */ + } + } + } + } + public void testCaretPosition() { Point p = tp.getLocationOnScreen(); // the right-top corner position @@ -122,7 +135,9 @@ ROBOT.hitKey(KeyEvent.VK_HOME); ROBOT.waitForIdle(); // this will fail if caret moves out of the 1st line. - assertEquals(0, getCaretOrdinate()); + if (getCaretOrdinate() != 0) { + throw new RuntimeException("Test Failed."); + } } int getCaretOrdinate() { diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/javax/swing/text/View/8080972/TestObjectView.java --- a/jdk/test/javax/swing/text/View/8080972/TestObjectView.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/javax/swing/text/View/8080972/TestObjectView.java Wed Jul 05 22:30:52 2017 +0200 @@ -32,7 +32,7 @@ import javax.swing.text.html.ObjectView; /* * @test - * @bug 8080972 + * @bug 8080972 8169887 * @summary Audit Core Reflection in module java.desktop for places that will * require changes to work with modules * @author Alexander Scherbatiy diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java --- a/jdk/test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/sun/net/www/protocol/https/HttpsClient/ProxyAuthTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -63,7 +63,7 @@ * authentication proxy */ -public class ProxyAuthTest { +public class ProxyAuthTest extends SSLSocketTemplate { /* * Where do we find the keystores? */ @@ -96,13 +96,13 @@ expectSuccess = args[0].equals("succeed"); String keyFilename = - SSLTest.TEST_SRC + "/" + pathToStores + "/" + keyStoreFile; + TEST_SRC + "/" + pathToStores + "/" + keyStoreFile; String trustFilename = - SSLTest.TEST_SRC + "/" + pathToStores + "/" + trustStoreFile; + TEST_SRC + "/" + pathToStores + "/" + trustStoreFile; - SSLTest.setup(keyFilename, trustFilename, passwd); + setup(keyFilename, trustFilename, passwd); - new SSLTest() + new SSLSocketTemplate() .setServerApplication((socket, test) -> { DataOutputStream out = new DataOutputStream( socket.getOutputStream()); @@ -164,7 +164,7 @@ .runTest(); } - static void doClientSide(SSLTest test) throws IOException { + static void doClientSide(SSLSocketTemplate test) throws IOException { // Wait for server to get started. // diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java --- a/jdk/test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/sun/net/www/protocol/https/HttpsClient/ServerIdentityTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -45,20 +45,20 @@ import javax.net.ssl.KeyManager; import javax.net.ssl.SSLContext; -public class ServerIdentityTest { +public class ServerIdentityTest extends SSLSocketTemplate { private static final String PASSWORD = "changeit"; public static void main(String[] args) throws Exception { final String keystore = args[0]; - String keystoreFilename = SSLTest.TEST_SRC + "/" + keystore; + String keystoreFilename = TEST_SRC + "/" + keystore; - SSLTest.setup(keystoreFilename, keystoreFilename, PASSWORD); + setup(keystoreFilename, keystoreFilename, PASSWORD); SSLContext context = SSLContext.getInstance("SSL"); KeyManager[] kms = new KeyManager[1]; - KeyStore ks = SSLTest.loadJksKeyStore(keystoreFilename, PASSWORD); + KeyStore ks = loadJksKeyStore(keystoreFilename, PASSWORD); KeyManager km = new MyKeyManager(ks, PASSWORD.toCharArray()); kms[0] = km; context.init(kms, null, null); @@ -70,7 +70,7 @@ */ System.out.println("Testing " + keystore); - new SSLTest() + new SSLSocketTemplate() .setSSLContext(context) .setServerApplication((socket, test) -> { BufferedWriter bw = new BufferedWriter( @@ -79,12 +79,12 @@ bw.flush(); Thread.sleep(2000); socket.getSession().invalidate(); - SSLTest.print("Server application is done"); + print("Server application is done"); }) .setClientPeer((test) -> { boolean serverIsReady = test.waitForServerSignal(); if (!serverIsReady) { - SSLTest.print( + print( "The server is not ready, ignore on client side."); return; } @@ -100,7 +100,7 @@ ((HttpURLConnection) url.openConnection()) .getInputStream().close(); - SSLTest.print("Client is done"); + print("Client is done"); }).runTest(); } } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java --- a/jdk/test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/sun/security/ssl/ServerHandshaker/AnonCipherWithWantClientAuth.java Wed Jul 05 22:30:52 2017 +0200 @@ -42,7 +42,7 @@ import javax.net.ssl.SSLServerSocketFactory; import javax.net.ssl.SSLSocket; -public class AnonCipherWithWantClientAuth { +public class AnonCipherWithWantClientAuth extends SSLSocketTemplate { /* * Where do we find the keystores? @@ -62,16 +62,16 @@ String trustFilename = System.getProperty("test.src", "./") + "/" + pathToStores + "/" + trustStoreFile; - SSLTest.setup(keyFilename, trustFilename, passwd); + setup(keyFilename, trustFilename, passwd); - new SSLTest() + new SSLSocketTemplate() .setServerPeer(test -> { SSLServerSocketFactory sslssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault(); SSLServerSocket sslServerSocket = - (SSLServerSocket) sslssf.createServerSocket(SSLTest.FREE_PORT); + (SSLServerSocket) sslssf.createServerSocket(FREE_PORT); test.setServerPort(sslServerSocket.getLocalPort()); - SSLTest.print("Server is listening on port " + print("Server is listening on port " + test.getServerPort()); String ciphers[] = { @@ -85,14 +85,14 @@ test.signalServerReady(); // Try to accept a connection in 30 seconds. - SSLSocket sslSocket = SSLTest.accept(sslServerSocket); + SSLSocket sslSocket = accept(sslServerSocket); if (sslSocket == null) { // Ignore the test case if no connection within 30 seconds. - SSLTest.print("No incoming client connection in 30 seconds." + print("No incoming client connection in 30 seconds." + " Ignore in server side."); return; } - SSLTest.print("Server accepted connection"); + print("Server accepted connection"); // handle the connection try { @@ -108,7 +108,7 @@ if (clientIsReady) { // Run the application in server side. - SSLTest.print("Run server application"); + print("Run server application"); InputStream sslIS = sslSocket.getInputStream(); OutputStream sslOS = sslSocket.getOutputStream(); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/sun/security/tools/jarsigner/TimestampCheck.java --- a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java Wed Jul 05 22:30:52 2017 +0200 @@ -58,7 +58,7 @@ /* * @test - * @bug 6543842 6543440 6939248 8009636 8024302 8163304 + * @bug 6543842 6543440 6939248 8009636 8024302 8163304 8169911 * @summary checking response of timestamp * @modules java.base/sun.security.pkcs * java.base/sun.security.timestamp @@ -349,6 +349,18 @@ .shouldMatch("MD5withRSA.*-sigalg.*risk"); checkWeak("weak.jar"); + signWithAliasAndTsa("halfWeak", "old.jar", "old", "-digestalg", "MD5") + .shouldHaveExitValue(0); + checkHalfWeak("halfWeak.jar"); + + // sign with DSA key + signWithAliasAndTsa("sign1", "old.jar", "dsakey") + .shouldHaveExitValue(0); + // sign with RSAkeysize < 1024 + signWithAliasAndTsa("sign2", "sign1.jar", "weakkeysize") + .shouldHaveExitValue(0); + checkMultiple("sign2.jar"); + // When .SF or .RSA is missing or invalid checkMissingOrInvalidFiles("normal.jar"); } else { // Run as a standalone server @@ -447,6 +459,37 @@ .shouldMatch("SignatureException:.*Disabled"); } + static void checkHalfWeak(String file) throws Throwable { + verify(file) + .shouldHaveExitValue(0) + .shouldContain("treated as unsigned") + .shouldMatch("weak algorithm that is now disabled.") + .shouldMatch("Re-run jarsigner with the -verbose option for more details"); + verify(file, "-verbose") + .shouldHaveExitValue(0) + .shouldContain("treated as unsigned") + .shouldMatch("weak algorithm that is now disabled by") + .shouldMatch("Digest algorithm: .*weak") + .shouldNotMatch("Signature algorithm: .*weak") + .shouldNotMatch("Timestamp digest algorithm: .*weak") + .shouldNotMatch("Timestamp signature algorithm: .*weak.*weak") + .shouldNotMatch("Timestamp signature algorithm: .*key.*weak"); + } + + static void checkMultiple(String file) throws Throwable { + verify(file) + .shouldHaveExitValue(0) + .shouldContain("jar verified"); + verify(file, "-verbose", "-certs") + .shouldHaveExitValue(0) + .shouldContain("jar verified") + .shouldMatch("X.509.*CN=dsakey") + .shouldNotMatch("X.509.*CN=weakkeysize") + .shouldMatch("Signed by .*CN=dsakey") + .shouldMatch("Signed by .*CN=weakkeysize") + .shouldMatch("Signature algorithm: .*key.*weak"); + } + static void checkTimestamp(String file, String policyId, String digestAlg) throws Exception { try (JarFile jf = new JarFile(file)) { @@ -480,11 +523,16 @@ */ static OutputAnalyzer sign(String path, String... extra) throws Throwable { + String alias = path.equals("badku") ? "badku" : "old"; + return signWithAliasAndTsa(path, "old.jar", alias, extra); + } + + static OutputAnalyzer signWithAliasAndTsa (String path, String jar, + String alias, String...extra) throws Throwable { which++; System.err.println("\n>> Test #" + which + ": " + Arrays.toString(extra)); List args = List.of("-J-Djava.security.egd=file:/dev/./urandom", - "-debug", "-signedjar", path + ".jar", "old.jar", - path.equals("badku") ? "badku" : "old"); + "-debug", "-signedjar", path + ".jar", jar, alias); args = new ArrayList<>(args); if (!path.equals("none") && !path.equals("badku")) { args.add("-tsa"); @@ -499,6 +547,8 @@ Files.deleteIfExists(Paths.get("tsks")); keytool("-alias ca -genkeypair -ext bc -dname CN=CA"); keytool("-alias old -genkeypair -dname CN=old"); + keytool("-alias dsakey -genkeypair -keyalg DSA -dname CN=dsakey"); + keytool("-alias weakkeysize -genkeypair -keysize 512 -dname CN=weakkeysize"); keytool("-alias badku -genkeypair -dname CN=badku"); keytool("-alias ts -genkeypair -dname CN=ts"); keytool("-alias tsweak -genkeypair -keysize 512 -dname CN=tsbad1"); @@ -507,6 +557,8 @@ keytool("-alias tsbad3 -genkeypair -dname CN=tsbad3"); gencert("old"); + gencert("dsakey"); + gencert("weakkeysize"); gencert("badku", "-ext ku:critical=keyAgreement"); gencert("ts", "-ext eku:critical=ts"); gencert("tsweak", "-ext eku:critical=ts"); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/sun/util/locale/provider/Bug8038436.java --- a/jdk/test/sun/util/locale/provider/Bug8038436.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/sun/util/locale/provider/Bug8038436.java Wed Jul 05 22:30:52 2017 +0200 @@ -23,7 +23,7 @@ /* * @test - * @bug 8038436 8158504 + * @bug 8038436 8158504 8065555 * @summary Test for changes in 8038436 * @modules java.base/sun.util.locale.provider * java.base/sun.util.spi @@ -136,7 +136,7 @@ static final String[] nfpLocs = ("ar, ar-AE, ar-BH, ar-DZ, ar-EG, ar-IQ, " + "ar-JO, ar-KW, ar-LB, ar-LY, ar-MA, ar-OM, ar-QA, ar-SA, ar-SD, ar-SY, " + "ar-TN, ar-YE, be, be-BY, bg, bg-BG, ca, ca-ES, cs, cs-CZ, da, da-DK, " + - "de, de-AT, de-CH, de-DE, de-GR, de-LU, el, el-CY, el-GR, en, en-AU, " + + "de, de-AT, de-CH, de-DE, de-LU, el, el-CY, el-GR, en, en-AU, " + "en-CA, en-GB, en-IE, en-IN, en-MT, en-NZ, en-PH, en-SG, en-US, en-ZA, " + "es, es-AR, es-BO, es-CL, es-CO, es-CR, es-CU, es-DO, es-EC, es-ES, " + "es-GT, es-HN, es-MX, es-NI, es-PA, es-PE, es-PR, es-PY, es-SV, es-US, " + @@ -154,7 +154,7 @@ static final String[] currencynpLocs = ("ar-AE, ar-BH, ar-DZ, ar-EG, ar-IQ, " + "ar-JO, ar-KW, ar-LB, ar-LY, ar-MA, ar-OM, ar-QA, ar-SA, ar-SD, ar-SY, " + "ar-TN, ar-YE, be-BY, bg-BG, ca-ES, cs-CZ, da-DK, de, de-AT, de-CH, " + - "de-DE, de-GR, de-LU, el-CY, el-GR, en-AU, en-CA, en-GB, en-IE, en-IN, " + + "de-DE, de-LU, el-CY, el-GR, en-AU, en-CA, en-GB, en-IE, en-IN, " + "en-MT, en-NZ, en-PH, en-SG, en-US, en-ZA, es, es-AR, es-BO, es-CL, " + "es-CO, es-CR, es-CU, es-DO, es-EC, es-ES, es-GT, es-HN, es-MX, es-NI, " + "es-PA, es-PE, es-PR, es-PY, es-SV, es-US, es-UY, es-VE, et-EE, fi-FI, " + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/jimage/JImageBasicsTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/tools/jimage/JImageBasicsTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,89 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage basic options, i.e. --version, -h + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main JImageBasicsTest + */ + +import static jdk.test.lib.Asserts.assertTrue; + +public class JImageBasicsTest extends JImageCliTest { + + public void testVersion() { + jimage("--version") + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.contains(System.getProperty("java.version")), "Contains java version."); + }); + } + + public void testFullVersion() { + jimage("--full-version") + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.contains(System.getProperty("java.version")), "Contains java version."); + }); + } + + public void testHelp() { + jimage("--help") + .assertSuccess() + .resultChecker(r -> verifyHelpOutput(r.output)); + } + + public void testShortHelp() { + jimage("-h") + .assertSuccess() + .resultChecker(r -> verifyHelpOutput(r.output)); + } + + public void testUnknownAction() { + jimage("unknown") + .assertFailure() + .assertShowsError(); + } + + public void testUnknownOption() { + jimage("--unknown") + .assertFailure() + .assertShowsError(); + } + + private void verifyHelpOutput(String output) { + assertTrue(output.startsWith("Usage: jimage"), "Usage is printed."); + assertTrue(output.contains("extract"), "Option 'extract' is found."); + assertTrue(output.contains("info"), "Option 'info' is found."); + assertTrue(output.contains("list"), "Option 'list' is found."); + assertTrue(output.contains("verify"), "Option 'verify' is found."); + } + + public static void main(String[] args) throws Throwable { + new JImageBasicsTest().runTests(); + } +} + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/jimage/JImageCliTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/tools/jimage/JImageCliTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,120 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.io.PrintWriter; +import java.lang.reflect.Method; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.function.Consumer; +import java.util.regex.Pattern; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static jdk.test.lib.Asserts.assertFalse; +import static jdk.test.lib.Asserts.assertTrue; +import static jdk.test.lib.Asserts.fail; + +/** + * This class is intended to be a base class for classes which are about to test + * command line interface of jimage. + */ +public class JImageCliTest { + + private String bootImagePath; + + public JImageCliTest() { + Path imagePath = Paths.get(System.getProperty("java.home"), "lib", "modules"); + if (Files.exists(imagePath)) { + this.bootImagePath = imagePath.toAbsolutePath().toString(); + } + } + + public void assertMatches(String regex, String output) { + Pattern pattern = Pattern.compile(regex); + if (!pattern.matcher(output).find()) { + fail(String.format("Expected to find a string match for [%s] in output \n[\n%s\n]\n.", + pattern, output)); + } + } + + /** + * Returns a path to a tested image to share it across tests. By default it returns a path to the boot image + * of tested JDK. This behavior can be redefined by descendants. + */ + public String getImagePath() { + return bootImagePath; + } + + /** + * Runs jimage task with the supplied arguments. + */ + protected static JImageResult jimage(String... args) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + PrintStream ps = new PrintStream(baos); + System.out.println("jimage " + Arrays.asList(args)); + int exitCode = jdk.tools.jimage.Main.run(args, new PrintWriter(ps)); + return new JImageResult(exitCode, new String(baos.toByteArray(), UTF_8)); + } + + protected static class JImageResult { + final int exitCode; + final String output; + + JImageResult(int exitCode, String output) { + this.exitCode = exitCode; + this.output = output; + } + + JImageResult assertSuccess() { assertTrue(exitCode == 0, output); return this; } + JImageResult assertFailure() { assertFalse(exitCode == 0, output); return this; } + + // a helper to ensure the error output doesn't exhibit implementation details + JImageResult assertShowsError() { + assertTrue(output.contains("Error"), + String.format("Output contains error, output=[%s]\n", output)); + assertFalse(output.contains("Exception"), + String.format("Output doesn't contain a stacktrace, output=[%s]\n", output)); + return this; + } + + JImageResult resultChecker(Consumer r) { r.accept(this); return this; } + } + + protected final void runTests() throws Throwable { + if (getImagePath() != null) { + for (Method m : getClass().getDeclaredMethods()) { + if (m.getName().startsWith("test")) { + System.out.printf("Invoking %s\n", m.getName()); + m.invoke(this); + } + } + } else { + System.out.println("This is not an image build. Skipping."); + } + } + +} + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/jimage/JImageExtractTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/tools/jimage/JImageExtractTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,181 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage 'extract' action + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main/othervm JImageExtractTest + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.nio.file.attribute.FileAttribute; +import java.nio.file.attribute.PosixFilePermission; +import java.nio.file.attribute.PosixFilePermissions; +import java.util.Arrays; +import java.util.HashSet; +import java.util.Set; +import java.util.stream.Collectors; + +import static jdk.test.lib.Asserts.assertEquals; +import static jdk.test.lib.Asserts.assertTrue; + +public class JImageExtractTest extends JImageCliTest { + public void testExtract() throws IOException { + jimage("extract", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.isEmpty(), "Output is not expected"); + }); + verifyExplodedImage(Paths.get(".")); + } + + public void testExtractHelp() { + for (String opt : Arrays.asList("-h", "--help")) { + jimage("extract", "--help") + .assertSuccess() + .resultChecker(r -> { + // extract - descriptive text + assertMatches("\\s+extract\\s+-\\s+.*", r.output); + }); + } + } + + public void testExtractToDir() throws IOException { + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName()); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.isEmpty(), "Output is not expected"); + }); + verifyExplodedImage(tmp); + } + + public void testExtractNoImageSpecified() { + jimage("extract", "") + .assertFailure() + .assertShowsError(); + } + + public void testExtractNotAnImage() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "not_an_image"); + jimage("extract", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractNotExistingImage() throws IOException { + Path tmp = Paths.get(".", "not_existing_image"); + Files.deleteIfExists(tmp); + jimage("extract", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToUnspecifiedDir() { + jimage("extract", "--dir", "--", getImagePath()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToNotExistingDir() throws IOException { + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName()); + Files.delete(tmp); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.isEmpty(), "Output is not expected"); + }); + verifyExplodedImage(tmp); + } + + public void testExtractFromDir() { + Path imagePath = Paths.get(getImagePath()); + Path imageDirPath = imagePath.subpath(0, imagePath.getNameCount() - 1); + jimage("extract", imageDirPath.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToDirBySymlink() throws IOException { + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName()); + try { + Path symlink = Files.createSymbolicLink(Paths.get(".", "symlink"), tmp); + jimage("extract", "--dir", symlink.toString(), getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.isEmpty(), "Output is not expected"); + }); + verifyExplodedImage(tmp); + } catch (UnsupportedOperationException e) { + // symlinks are not supported + // nothing to test + } + } + + public void testExtractToReadOnlyDir() throws IOException { + Set perms = PosixFilePermissions.fromString("r-xr--r--"); + FileAttribute> atts = PosixFilePermissions.asFileAttribute(perms); + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName(), atts); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToNotEmptyDir() throws IOException { + Path tmp = Files.createTempDirectory(Paths.get("."), getClass().getName()); + Files.createFile(Paths.get(tmp.toString(), ".not_empty")); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertFailure() + .assertShowsError(); + } + + public void testExtractToFile() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "not_a_dir"); + jimage("extract", "--dir", tmp.toString(), getImagePath()) + .assertFailure() + .assertShowsError(); + } + + private void verifyExplodedImage(Path imagePath) throws IOException { + Set allModules = Files.walk(imagePath, 1).collect(Collectors.toSet()); + assertTrue(allModules.stream().anyMatch(p -> "java.base".equals(p.getFileName().toString())), + "Exploded image contains java.base module."); + + Set badModules = allModules.stream() + .filter(p -> !Files.exists(p.resolve("module-info.class"))) + .collect(Collectors.toSet()); + assertEquals(badModules, new HashSet() {{ add(imagePath); }}, + "There are no exploded modules with missing 'module-info.class'"); + } + + public static void main(String[] args) throws Throwable { + new JImageExtractTest().runTests(); + } +} + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/jimage/JImageInfoTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/tools/jimage/JImageInfoTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage 'info' action + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main JImageInfoTest + */ + +import java.util.Arrays; + +public class JImageInfoTest extends JImageCliTest { + public void testInfo() { + jimage("info", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertMatches("(?m)^\\s+Major Version: +[1-9]\\d*$.*", r.output); + assertMatches("(?m)^\\s+Minor Version: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Flags: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Resource Count: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Table Length: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Offsets Size: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Redirects Size: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Locations Size: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Strings Size: +\\d+$.*", r.output); + assertMatches("(?m)^\\s+Index Size: +\\d+$.*", r.output); + }); + } + + public void testInfoHelp() { + for (String opt : Arrays.asList("-h", "--help")) { + jimage("info", opt) + .assertSuccess() + .resultChecker(r -> { + // info - descriptive text + assertMatches("\\s+info\\s+-\\s+.*", r.output); + }); + } + } + + public void testInfoUnknownOption() { + jimage("info", "--unknown") + .assertFailure() + .assertShowsError(); + } + + public static void main(String[] args) throws Throwable { + new JImageInfoTest().runTests(); + } +} + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/jimage/JImageListTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/tools/jimage/JImageListTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,229 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage 'list' action + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main JImageListTest + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.*; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static jdk.test.lib.Asserts.assertEquals; +import static jdk.test.lib.Asserts.assertFalse; +import static jdk.test.lib.Asserts.assertTrue; + +public class JImageListTest extends JImageCliTest { + public void testList() { + jimage("list", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + String[] lines = r.output.split(System.lineSeparator()); + assertTrue(lines.length > 0, "Option --list has output."); + assertTrue(lines[0].startsWith("jimage: " + getImagePath()), + "Output should start with jimage path."); + + List modules = Stream.of(lines) + .filter(s -> s.startsWith("Module: ")) + .map(s -> s.substring(s.indexOf(':') + 1).trim()) + .collect(Collectors.toList()); + assertTrue(modules.size() > 0, "Image contains at least one module."); + assertTrue(modules.indexOf("java.base") > 0, "Module java.base found."); + }); + } + + public void testListHelp() { + for (String opt : Arrays.asList("-h", "--help")) { + jimage("list", opt) + .assertSuccess() + .resultChecker(r -> { + // list - descriptive text + assertMatches("\\s+list\\s+-\\s+.*", r.output); + }); + } + } + + public void testListVerbose() { + jimage("list", "--verbose", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertMatches("Offset\\s+Size\\s+Compressed\\s+Entry", r.output); + + String[] lines = r.output.split("[" + System.lineSeparator() + "]+"); + assertTrue(lines.length > 0, "Option --list has output."); + assertTrue(lines[0].startsWith("jimage: " + getImagePath()), + "Output should start with jimage path."); + + List modules = Stream.of(lines) + .filter(s -> s.startsWith("Module: ")) + .map(s -> s.substring(s.indexOf(':') + 1).trim()) + .collect(Collectors.toList()); + assertTrue(modules.size() > 0, "Image contains at least one module."); + assertTrue(modules.indexOf("java.base") > 0, "Module java.base found."); + + Set entries = Stream.of(lines) + .filter(s -> { return !s.startsWith("Module: ") && !s.startsWith("Offset"); }) + // Offset \d+ Size \d+ Compressed \d+ Entry \.* + .filter(s -> !s.matches("\\s+\\d+\\s+\\d+\\s+\\d+\\s+.*")) + .collect(Collectors.toSet()); + assertEquals(entries, new HashSet<>() {{ add("jimage: " + getImagePath()); }}, + "All entries should be in format: Offset Size Compressed Entry"); + }); + } + + public void testListIncludeAllWithGlob() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + JImageResult listAllGlob = jimage("list", "--include", "**", getImagePath()).assertSuccess(); + assertEquals(listAllGlob.output, listAll.output, "--include ** should produce the same output"); + } + + public void testListIncludeWithGlob() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + Set expected = Stream.of(listAll.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> s.startsWith("java/util/zip")) + .collect(Collectors.toSet()); + + JImageResult listJavaUtil = jimage("list", "--include", "/java.base/java/util/zip/**", getImagePath()).assertSuccess(); + Set actual = Stream.of(listJavaUtil.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + assertEquals(actual, expected, "All java.util.zip classes are listed"); + } + + public void testListIncludeNoMatchWithGlob() { + JImageResult listNotMatching = jimage("list", "--include", "not_matching", getImagePath()).assertSuccess(); + Set entries = Stream.of(listNotMatching.output.split("["+ System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + assertEquals(entries, Collections.emptySet(), "No java.util classes are listed"); + } + + public void testListIncludeAllWithExplicitGlob() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + JImageResult listAllGlob = jimage("list", "--include", "glob:**", getImagePath()).assertSuccess(); + assertEquals(listAllGlob.output, listAll.output, "--include glob:** should produce the same output"); + } + + public void testListIncludeAllWithRegex() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + JImageResult listAllRegex = jimage("list", "--include", "regex:.*", getImagePath()).assertSuccess(); + assertEquals(listAllRegex.output, listAll.output, "--include regex:.* should produce the same output"); + } + + public void testListIncludeWithRegex() { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + Set expected = Stream.of(listAll.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> s.startsWith("java/text/")) + .collect(Collectors.toSet()); + assertFalse(expected.isEmpty(), "There should be classes from java.text package"); + + JImageResult listJavaText = jimage("list", "--include", "regex:/java.base/java/text/.*", getImagePath()).assertSuccess(); + Set actual = Stream.of(listJavaText.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + + assertEquals(actual, expected, "All java.text classes are listed"); + } + + public void testListIncludeNoMatchWithRegex() { + JImageResult listNotMatching = jimage("list", "--include", "regex:not_matching", + getImagePath()).assertSuccess(); + Set entries = Stream.of(listNotMatching.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + assertEquals(entries, Collections.emptySet(), "No classes are listed"); + } + + public void testListIncludeMultiplePatterns() throws IOException { + JImageResult listAll = jimage("list", getImagePath()).assertSuccess(); + Set expected = Stream.of(listAll.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> s.startsWith("java/time/") || s.startsWith("java/util/zip")) + .collect(Collectors.toSet()); + assertFalse(expected.isEmpty(), "There should be classes from java.time and java.io packages"); + + JImageResult listMatched = jimage("list", "--include", "glob:/java.base/java/time/**,regex:/java.base/java/util/zip/.*", + getImagePath()).assertSuccess(); + Set actual = Stream.of(listMatched.output.split("[" + System.lineSeparator() + "]+")) + .map(String::trim) + .filter(s -> !s.startsWith("jimage:") && !s.startsWith("Module:")) + .collect(Collectors.toSet()); + + assertEquals(actual, expected, "All java.time and java.util.zip classes are listed"); + } + + public void testListNoImageSpecified() { + jimage("list", "") + .assertFailure() + .assertShowsError(); + } + + public void testListEmptyFile() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "empty_file"); + jimage("list", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testListNotAnImage() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "not_an_image"); + Files.write(tmp, "This is not an image".getBytes()); + jimage("list", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testListNotExistingImage() throws IOException { + Path tmp = Paths.get(".", "not_existing_image"); + Files.deleteIfExists(tmp); + jimage("list", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testListWithUnknownOption() { + jimage("list", "--unknown") + .assertFailure() + .assertShowsError(); + } + + public static void main(String[] args) throws Throwable { + new JImageListTest().runTests(); + } +} + diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/jimage/JImageToolTest.java --- a/jdk/test/tools/jimage/JImageToolTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/tools/jimage/JImageToolTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2015, 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 @@ -23,8 +23,8 @@ /* * @test * @library /lib/testlibrary - * @build jdk.testlibrary.* - * @summary Test to see if jimage tool extracts and recreates correctly. + * @build jdk.testlibrary.ProcessTools + * @summary Test to check if jimage tool exists and is working * @run main/timeout=360 JImageToolTest */ @@ -42,7 +42,7 @@ public class JImageToolTest { private static void jimage(String... jimageArgs) throws Exception { ArrayList args = new ArrayList<>(); - args.add("-ms8m"); + args.add("-ms64m"); args.add("jdk.tools.jimage.Main"); args.addAll(Arrays.asList(jimageArgs)); @@ -61,11 +61,7 @@ if (Files.exists(jimagePath) && Files.exists(modulesimagePath)) { String jimage = jimagePath.toAbsolutePath().toString(); - String bootimage = modulesimagePath.toAbsolutePath().toString(); - String extractDir = Paths.get(".", "extract").toAbsolutePath().toString(); - jimage("list", bootimage); - jimage("verify", bootimage); - jimage("extract", "--dir", extractDir, bootimage); + jimage("--version"); System.out.println("Test successful"); } else { System.out.println("Test skipped, not an images build"); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/jimage/JImageVerifyTest.java --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/jdk/test/tools/jimage/JImageVerifyTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -0,0 +1,94 @@ +/* + * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. + * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. + * + * This code is free software; you can redistribute it and/or modify it + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/* + * @test + * @summary Tests to verify jimage 'verify' action + * @library /test/lib + * @modules jdk.jlink/jdk.tools.jimage + * @build jdk.test.lib.Asserts + * @run main JImageVerifyTest + */ + +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Arrays; + +import static jdk.test.lib.Asserts.assertTrue; + +public class JImageVerifyTest extends JImageCliTest { + + public void testVerify() { + jimage("verify", getImagePath()) + .assertSuccess() + .resultChecker(r -> { + assertTrue(r.output.startsWith("jimage: " + getImagePath()), + "Contains verified image's path"); + }); + } + + public void testVerifyHelp() { + for (String opt : Arrays.asList("-h", "--help")) { + jimage("verify", opt) + .assertSuccess() + .resultChecker(r -> { + // verify - descriptive text + assertMatches("\\s+verify\\s+-\\s+.*", r.output); + }); + } + } + + public void testVerifyImageNotSpecified() { + jimage("verify", "") + .assertFailure() + .assertShowsError(); + } + + public void testVerifyNotAnImage() throws IOException { + Path tmp = Files.createTempFile(Paths.get("."), getClass().getName(), "not_an_image"); + jimage("verify", tmp.toString()) + .assertFailure() + .assertShowsError(); + } + + public void testVerifyNotExistingImage() throws IOException { + Path tmp = Paths.get(".", "not_existing_image"); + Files.deleteIfExists(tmp); + jimage("verify", "") + .assertFailure() + .assertShowsError(); + } + + public void testVerifyWithUnknownOption() { + jimage("verify", "--unknown") + .assertFailure() + .assertShowsError(); + } + + public static void main(String[] args) throws Throwable { + new JImageVerifyTest().runTests(); + } + +} diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/jlink/JLinkSigningTest.java --- a/jdk/test/tools/jlink/JLinkSigningTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/tools/jlink/JLinkSigningTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -26,24 +26,31 @@ * @bug 8159393 * @summary Test signed jars involved in image creation * @modules java.base/jdk.internal.jimage - * jdk.jlink/jdk.tools.jlink.internal + * java.base/sun.security.tools.keytool * jdk.compiler/com.sun.tools.javac - * java.base/sun.security.tools.keytool * jdk.jartool/sun.security.tools.jarsigner * jdk.jartool/sun.tools.jar + * jdk.jlink/jdk.tools.jlink.internal * @run main/othervm JLinkSigningTest */ import java.io.File; import java.io.IOException; -import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; +import java.util.spi.ToolProvider; public class JLinkSigningTest { + private static final ToolProvider JAR_TOOL = ToolProvider.findFirst("jar") + .orElseThrow(() -> new RuntimeException("jar tool not found")); + private static final ToolProvider JAVAC_TOOL = ToolProvider.findFirst("javac") + .orElseThrow(() -> new RuntimeException("javac tool not found")); + private static final ToolProvider JLINK_TOOL = ToolProvider.findFirst("jlink") + .orElseThrow(() -> new RuntimeException("jlink tool not found")); + static final String[] MODULE_INFO = { "module test {", "}", @@ -61,22 +68,29 @@ System.out.println(command + " " + String.join(" ", Arrays.asList(args))); } - static void javac(String[] args) { - report("javac", args); - com.sun.tools.javac.Main javac = new com.sun.tools.javac.Main(); + static void jar(String[] args) { + report("jar", args); + JAR_TOOL.run(System.out, System.err, args); + } - if (javac.compile(args) != 0) { - throw new RuntimeException("javac failed"); + static void jarsigner(String[] args) { + report("jarsigner", args); + + try { + sun.security.tools.jarsigner.Main.main(args); + } catch (Exception ex) { + throw new RuntimeException("jarsigner not found"); } } - static void jar(String[] args) { - report("jar", args); - sun.tools.jar.Main jar = new sun.tools.jar.Main(System.out, System.err, "jar"); + static void javac(String[] args) { + report("javac", args); + JAVAC_TOOL.run(System.out, System.err, args); + } - if (!jar.run(args)) { - throw new RuntimeException("jar failed"); - } + static void jlink(String[] args) { + report("jlink", args); + JLINK_TOOL.run(System.out, System.err, args); } static void keytool(String[] args) { @@ -89,28 +103,6 @@ } } - static void jarsigner(String[] args) { - report("jarsigner", args); - - try { - sun.security.tools.jarsigner.Main.main(args); - } catch (Exception ex) { - throw new RuntimeException("jarsigner failed"); - } - } - - static void jlink(String[] args) { - report("jlink", args); - - try { - jdk.tools.jlink.internal.Main.run(new PrintWriter(System.out, true), - new PrintWriter(System.err, true), - args); - } catch (Exception ex) { - throw new RuntimeException("jlink failed"); - } - } - public static void main(String[] args) { final String JAVA_HOME = System.getProperty("java.home"); Path moduleInfoJavaPath = Paths.get("module-info.java"); diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/launcher/modules/classpath/JavaClassPathTest.java --- a/jdk/test/tools/launcher/modules/classpath/JavaClassPathTest.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/tools/launcher/modules/classpath/JavaClassPathTest.java Wed Jul 05 22:30:52 2017 +0200 @@ -21,12 +21,14 @@ * questions. */ +import java.io.BufferedWriter; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.spi.ToolProvider; import jdk.testlibrary.OutputAnalyzer; import org.testng.annotations.BeforeTest; @@ -42,6 +44,7 @@ * @summary Test the default class path if -Djava.class.path is set * @library /lib/testlibrary * @modules jdk.compiler + * jdk.jartool * @build CompilerUtils jdk.testlibrary.* * @run testng JavaClassPathTest */ @@ -50,6 +53,7 @@ private static final Path SRC_DIR = Paths.get(System.getProperty("test.src"), "src"); private static final Path MODS_DIR = Paths.get("mods"); + private static final Path LIB_DIR = Paths.get("lib"); private static final String TEST_MODULE = "m"; private static final String TEST_MAIN = "jdk.test.Main"; @@ -66,27 +70,47 @@ Path res = Paths.get("jdk/test/res.properties"); Files.createFile(res); + + ToolProvider jartool = ToolProvider.findFirst("jar").orElseThrow( + () -> new RuntimeException("jar tool not found") + ); + + Path jarfile = LIB_DIR.resolve("m.jar"); + Files.createDirectories(LIB_DIR); + assertTrue(jartool.run(System.out, System.err, "cfe", + jarfile.toString(), TEST_MAIN, + file.toString()) == 0); + + Path manifest = LIB_DIR.resolve("manifest"); + try (BufferedWriter writer = Files.newBufferedWriter(manifest)) { + writer.write("CLASS-PATH: lib/m.jar"); + } + jarfile = LIB_DIR.resolve("m1.jar"); + assertTrue(jartool.run(System.out, System.err, "cfme", + jarfile.toString(), manifest.toString(), TEST_MAIN, + file.toString()) == 0); } @DataProvider(name = "classpath") public Object[][] classpath() { return new Object[][]{ // true indicates that class path default to current working directory - { "", true }, - { "-Djava.class.path", true }, - { "-Djava.class.path=", true }, - { "-Djava.class.path=.", true }, + { "", "." }, + { "-Djava.class.path", "." }, + { "-Djava.class.path=", "" }, + { "-Djava.class.path=.", "." }, }; } @Test(dataProvider = "classpath") - public void testUnnamedModule(String option, boolean expected) throws Throwable { + public void testUnnamedModule(String option, String expected) throws Throwable { List args = new ArrayList<>(); if (!option.isEmpty()) { args.add(option); } args.add(TEST_MAIN); - args.add(Boolean.toString(expected)); + args.add(Boolean.toString(true)); + args.add(expected); assertTrue(execute(args).getExitValue() == 0); } @@ -95,15 +119,14 @@ public Object[][] moduleAndClassPath() { return new Object[][]{ // true indicates that class path default to current working directory - { "", false }, - { "-Djava.class.path", false }, - { "-Djava.class.path=", false }, - { "-Djava.class.path=.", true }, + { "", "" }, + { "-Djava.class.path", "" }, + { "-Djava.class.path=", "" }, }; } @Test(dataProvider = "moduleAndClassPath") - public void testNamedModule(String option, boolean expected) throws Throwable { + public void testNamedModule(String option, String expected) throws Throwable { List args = new ArrayList<>(); if (!option.isEmpty()) { args.add(option); @@ -112,7 +135,61 @@ args.add(MODS_DIR.toString()); args.add("-m"); args.add(TEST_MODULE + "/" + TEST_MAIN); - args.add(Boolean.toString(expected)); + // not default to CWD + args.add(Boolean.toString(false)); + args.add(expected); + + + assertTrue(execute(args).getExitValue() == 0); + } + + @Test + public void testClassPath() throws Throwable { + List args = new ArrayList<>(); + args.add("-Djava.class.path=."); + args.add("--module-path"); + args.add(MODS_DIR.toString()); + args.add("-m"); + args.add(TEST_MODULE + "/" + TEST_MAIN); + args.add(Boolean.toString(true)); + args.add("."); + + assertTrue(execute(args).getExitValue() == 0); + } + + @Test + public void testJAR() throws Throwable { + String jarfile = LIB_DIR.resolve("m.jar").toString(); + List args = new ArrayList<>(); + args.add("-jar"); + args.add(jarfile); + args.add(Boolean.toString(false)); + args.add(jarfile); + + assertTrue(execute(args).getExitValue() == 0); + } + + /* + * Test CLASS-PATH attribute in manifest + */ + @Test + public void testClassPathAttribute() throws Throwable { + String jarfile = LIB_DIR.resolve("m1.jar").toString(); + + List args = new ArrayList<>(); + args.add("-jar"); + args.add(jarfile); + args.add(Boolean.toString(false)); + args.add(jarfile); + + assertTrue(execute(args).getExitValue() == 0); + + args.clear(); + args.add("-cp"); + args.add(jarfile); + args.add(TEST_MAIN); + args.add(Boolean.toString(false)); + args.add(jarfile); assertTrue(execute(args).getExitValue() == 0); } diff -r 183ae2332dd9 -r f4e854a77aa3 jdk/test/tools/launcher/modules/classpath/src/m/jdk/test/Main.java --- a/jdk/test/tools/launcher/modules/classpath/src/m/jdk/test/Main.java Wed Jul 05 22:29:12 2017 +0200 +++ b/jdk/test/tools/launcher/modules/classpath/src/m/jdk/test/Main.java Wed Jul 05 22:30:52 2017 +0200 @@ -29,13 +29,14 @@ static final String JAVA_CLASS_PATH = "java.class.path"; public static void main(String[] args) throws Exception { + boolean expected = args[0].equals("true"); + String cpath = args.length > 1 ? args[1] : ""; String value = System.getProperty(JAVA_CLASS_PATH); - if (value == null) { - throw new RuntimeException(JAVA_CLASS_PATH + " is expected non-null" + - " for compatibility"); + if (!value.equals(cpath)) { + throw new RuntimeException(JAVA_CLASS_PATH + "=" + value + + " expected=" + cpath); } - boolean expected = args[0].equals("true"); ClassLoader loader = ClassLoader.getSystemClassLoader(); URL url = loader.getResource("jdk/test/res.properties"); if ((expected && url == null) || (!expected && url != null)) { diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/.hgtags --- a/langtools/.hgtags Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/.hgtags Wed Jul 05 22:30:52 2017 +0200 @@ -388,3 +388,4 @@ 6ef8a1453577832626b0efb7f70a3102b721ebbf jdk-9+143 47871e348144bafddea0ede3a44299461e254a2d jdk-9+144 cb9e896265ef45295fdd09986dee76624e4d41e4 jdk-9+145 +26f972dc2d174a75bc32131c29661c78568586b0 jdk-9+146 diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/java.compiler/share/classes/javax/tools/ForwardingJavaFileManager.java --- a/langtools/src/java.compiler/share/classes/javax/tools/ForwardingJavaFileManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/java.compiler/share/classes/javax/tools/ForwardingJavaFileManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -165,12 +165,12 @@ fileManager.close(); } - public Location getModuleLocation(Location location, String moduleName) throws IOException { - return fileManager.getModuleLocation(location, moduleName); + public Location getLocationForModule(Location location, String moduleName) throws IOException { + return fileManager.getLocationForModule(location, moduleName); } - public Location getModuleLocation(Location location, JavaFileObject fo, String pkgName) throws IOException { - return fileManager.getModuleLocation(location, fo, pkgName); + public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException { + return fileManager.getLocationForModule(location, fo, pkgName); } public ServiceLoader getServiceLoader(Location location, Class service) throws IOException { @@ -181,7 +181,7 @@ return fileManager.inferModuleName(location); } - public Iterable> listModuleLocations(Location location) throws IOException { - return fileManager.listModuleLocations(location); + public Iterable> listLocationsForModules(Location location) throws IOException { + return fileManager.listLocationsForModules(location); } } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/java.compiler/share/classes/javax/tools/JavaFileManager.java --- a/langtools/src/java.compiler/share/classes/javax/tools/JavaFileManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/java.compiler/share/classes/javax/tools/JavaFileManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -109,6 +109,28 @@ /** * Interface for locations of file objects. Used by file managers * to determine where to place or search for file objects. + * + *

    Informally, a {@code Location} corresponds to a "search path", such as a class + * path or module path, as used by command-line tools that use the default file system. + * + *

    Some locations are typically used to identify a place in which + * a tool can find files to be read; others are typically used to identify + * a place where a tool can write files. If a location is used to identify + * a place for reading files, those files may be organized in a simple + * package/class hierarchy: such locations are described as + * package-oriented. + * Alternatively, the files may be organized in a module/package/class + * hierarchy: such locations are described as module-oriented. + * If a location is typically used to identify a place where a tool can write files, + * it is up to the tool that writes the files to specify how those files will be + * organized. + * + *

    You can access the classes in a package-oriented location using methods like + * {@link JavaFileManager#getJavaFileForInput} or {@link JavaFileManager#list}. + * It is not possible to directly list the classes in a module-oriented + * location. Instead, you can get a package-oriented location for any specific module + * using methods like {@link JavaFileManager#getLocationForModule} or + * {@link JavaFileManager#listLocationsForModule}. */ interface Location { /** @@ -119,30 +141,41 @@ String getName(); /** - * Determines if this is an output location. An output - * location is a location that is conventionally used for + * Determines if this is an output location. + * An output location is a location that is conventionally used for * output. * + * @apiNote An output location may be used to write files in either + * a package-oriented organization or in a module-oriented organization. + * * @return true if this is an output location, false otherwise */ boolean isOutputLocation(); /** - * Indicates if this location is expected to contain modules, - * as compared to a location which contains packages and classes. + * Indicates if this location is module-oriented location, and therefore + * expected to contain classes in a module/package/class + * hierarchy, as compared to a package-oriented location, which + * is expected to contain classes in a package/class hierarchy. + * The result of this method is undefined if this is an output + * location. + * + * @implNote This implementation returns true if the name includes + * the word "MODULE". * * @return true if this location is expected to contain modules * @since 9 */ - default boolean isModuleLocation() { - return false; + default boolean isModuleOrientedLocation() { + return getName().matches("\\bMODULE\\b"); } } /** * Returns a class loader for loading plug-ins from the given - * location. For example, to load annotation processors, a - * compiler will request a class loader for the {@link + * package-oriented location. + * For example, to load annotation processors, + * a compiler will request a class loader for the {@link * StandardLocation#ANNOTATION_PROCESSOR_PATH * ANNOTATION_PROCESSOR_PATH} location. * @@ -154,13 +187,14 @@ * in the current security context * @throws IllegalStateException if {@link #close} has been called * and this file manager cannot be reopened + * @throws IllegalArgumentException if the location is a module-oriented location */ ClassLoader getClassLoader(Location location); /** * Lists all file objects matching the given criteria in the given - * location. List file objects in "subpackages" if recurse is - * true. + * package-oriented location. + * List file objects in "subpackages" if recurse is true. * *

    Note: even if the given location is unknown to this file * manager, it may not return {@code null}. Also, an unknown @@ -174,6 +208,7 @@ * @throws IOException if an I/O error occurred, or if {@link * #close} has been called and this file manager cannot be * reopened + * @throws IllegalArgumentException if the location is a module-oriented location * @throws IllegalStateException if {@link #close} has been called * and this file manager cannot be reopened */ @@ -184,14 +219,15 @@ throws IOException; /** - * Infers a binary name of a file object based on a location. The - * binary name returned might not be a valid binary name according to + * Infers a binary name of a file object based on a package-oriented location. + * The binary name returned might not be a valid binary name according to * The Java™ Language Specification. * * @param location a location * @param file a file object * @return a binary name or {@code null} the file object is not * found in the given location + * @throws IllegalArgumentException if the location is a module-oriented location * @throws IllegalStateException if {@link #close} has been called * and this file manager cannot be reopened */ @@ -239,7 +275,7 @@ /** * Returns a {@linkplain JavaFileObject file object} for input * representing the specified class of the specified kind in the - * given location. + * given package-oriented location. * * @param location a location * @param className the name of a class @@ -250,7 +286,8 @@ * file does not exist * @throws IllegalArgumentException if the location is not known * to this file manager and the file manager does not support - * unknown locations, or if the kind is not valid + * unknown locations, or if the kind is not valid, or if the + * location is a module-oriented location * @throws IOException if an I/O error occurred, or if {@link * #close} has been called and this file manager cannot be * reopened @@ -265,7 +302,7 @@ /** * Returns a {@linkplain JavaFileObject file object} for output * representing the specified class of the specified kind in the - * given location. + * given package-oriented location. * *

    Optionally, this file manager might consider the sibling as * a hint for where to place the output. The exact semantics of @@ -276,7 +313,7 @@ * the originating source file as sibling when calling this * method. * - * @param location a location + * @param location a package-oriented location * @param className the name of a class * @param kind the kind of file, must be one of {@link * JavaFileObject.Kind#SOURCE SOURCE} or {@link @@ -287,7 +324,8 @@ * @throws IllegalArgumentException if sibling is not known to * this file manager, or if the location is not known to this file * manager and the file manager does not support unknown - * locations, or if the kind is not valid + * locations, or if the kind is not valid, or if the location is + * not an output location * @throws IOException if an I/O error occurred, or if {@link * #close} has been called and this file manager cannot be * reopened @@ -303,7 +341,7 @@ /** * Returns a {@linkplain FileObject file object} for input * representing the specified relative - * name in the specified package in the given location. + * name in the specified package in the given package-oriented location. * *

    If the returned object represents a {@linkplain * JavaFileObject.Kind#SOURCE source} or {@linkplain @@ -325,14 +363,15 @@ * a valid result would be a file object representing the file * "C:\Documents and Settings\UncleBob\src\share\classes\com\sun\tools\javac\resources\compiler.properties". * - * @param location a location + * @param location a package-oriented location * @param packageName a package name * @param relativeName a relative name * @return a file object, might return {@code null} if the file * does not exist * @throws IllegalArgumentException if the location is not known * to this file manager and the file manager does not support - * unknown locations, or if {@code relativeName} is not valid + * unknown locations, or if {@code relativeName} is not valid, + * or if the location is a module-oriented location * @throws IOException if an I/O error occurred, or if {@link * #close} has been called and this file manager cannot be * reopened @@ -368,7 +407,7 @@ * relative name or next to the sibling argument. See {@link * #getFileForInput getFileForInput} for an example. * - * @param location a location + * @param location an output location * @param packageName a package name * @param relativeName a relative name * @param sibling a file object to be used as hint for placement; @@ -377,7 +416,8 @@ * @throws IllegalArgumentException if sibling is not known to * this file manager, or if the location is not known to this file * manager and the file manager does not support unknown - * locations, or if {@code relativeName} is not valid + * locations, or if {@code relativeName} is not valid, + * or if the location is not an output location * @throws IOException if an I/O error occurred, or if {@link * #close} has been called and this file manager cannot be * reopened @@ -416,7 +456,12 @@ void close() throws IOException; /** - * Gets a location for a named module within a module-oriented location. + * Gets a location for a named module within a location, which may be either + * a module-oriented location or an output location. + * The result will be an output location if the given location is + * an output location, or it will be a package-oriented location. + * + * @implSpec This implementation throws {@code UnsupportedOperationException}. * * @param location the module-oriented location * @param moduleName the name of the module to be found @@ -424,33 +469,49 @@ * * @throws IOException if an I/O error occurred * @throws UnsupportedOperationException if this operation if not supported by this file manager + * @throws IllegalArgumentException if the location is neither an output location nor a + * module-oriented location * @since 9 */ // TODO: describe failure modes - default Location getModuleLocation(Location location, String moduleName) throws IOException { + default Location getLocationForModule(Location location, String moduleName) throws IOException { throw new UnsupportedOperationException(); } /** * Gets a location for the module containing a specific file representing a Java - * source or class. + * source or class, to be found in a module-oriented location. + * The result will be a package-oriented location. * - * @param location a module-oriented location + * @apiNote the package name is used to identify the position of the file object + * within the module/package/class hierarchy identified by by the location. + * + * @implSpec This implementation throws {@code UnsupportedOperationException}. + * + * @param location the module-oriented location * @param fo the file * @param pkgName the package name for the class(es) defined in this file * @return the module containing the file * * @throws IOException if an I/O error occurred * @throws UnsupportedOperationException if this operation if not supported by this file manager + * @throws IllegalArgumentException if the location is not a module-oriented location * @since 9 - */ // TODO: describe failure modes - default Location getModuleLocation(Location location, JavaFileObject fo, String pkgName) throws IOException { + */ + default Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException { throw new UnsupportedOperationException(); } /** * Get a service loader for a specific service class from a given location. * - * @param location the location + * If the location is a module-oriented location, the service loader will use the + * service declarations in the modules found in that location. Otherwise, a service loader + * is created using the package-oriented location, in which case, the services are + * determined using the provider-configuration files in {@code META-INF/services}. + * + * @implSpec This implementation throws {@code UnsupportedOperationException}. + * + * @param location the module-oriented location * @param service the {@code Class} object of the service class * @param the service class * @return a service loader for the given service class @@ -465,13 +526,16 @@ /** * Infer the name of the module from its location, as returned by - * getModuleLocation or listModuleLocations. + * {@code getLocationForModule} or {@code listModuleLocations}. * - * @param location a location representing a module + * @implSpec This implementation throws {@code UnsupportedOperationException}. + * + * @param location a package-oriented location representing a module * @return the name of the module * * @throws IOException if an I/O error occurred * @throws UnsupportedOperationException if this operation if not supported by this file manager + * @throws IllegalArgumentException if the location is not one known to this file manager * @since 9 */ // TODO: describe failure modes default String inferModuleName(Location location) throws IOException { @@ -479,16 +543,20 @@ } /** - * Lists the modules in a module-oriented location. + * Lists the locations for all the modules in a module-oriented location. + * The locations that are returned will be package-oriented locations. * - * @param location the location for which to list the modules + * @implSpec This implementation throws {@code UnsupportedOperationException}. + * + * @param location the module-oriented location for which to list the modules * @return a series of sets of locations containing modules * * @throws IOException if an I/O error occurred * @throws UnsupportedOperationException if this operation if not supported by this file manager + * @throws IllegalArgumentException if the location is not a module-oriented location * @since 9 */ // TODO: describe failure modes - default Iterable> listModuleLocations(Location location) throws IOException { + default Iterable> listLocationsForModules(Location location) throws IOException { throw new UnsupportedOperationException(); } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/java.compiler/share/classes/javax/tools/StandardLocation.java --- a/langtools/src/java.compiler/share/classes/javax/tools/StandardLocation.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/java.compiler/share/classes/javax/tools/StandardLocation.java Wed Jul 05 22:30:52 2017 +0200 @@ -109,7 +109,9 @@ * property must hold: {@code locationFor(x) == * locationFor(y)} if and only if {@code x.equals(y)}. * The returned location will be an output location if and only if - * name ends with {@code "_OUTPUT"}. + * name ends with {@code "_OUTPUT"}. It will be considered to + * be a module-oriented location if the name contains the word + * {@code "MODULE"}. * * @param name a name * @return a location @@ -149,7 +151,7 @@ } @Override - public boolean isModuleLocation() { + public boolean isModuleOrientedLocation() { switch (this) { case MODULE_SOURCE_PATH: case ANNOTATION_PROCESSOR_MODULE_PATH: diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/java.compiler/share/classes/javax/tools/ToolProvider.java --- a/langtools/src/java.compiler/share/classes/javax/tools/ToolProvider.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/java.compiler/share/classes/javax/tools/ToolProvider.java Wed Jul 05 22:30:52 2017 +0200 @@ -57,7 +57,7 @@ * {@code null} if no compiler is provided * @implNote This implementation returns the compiler provided * by the {@code jdk.compiler} module if that module is available, - * and null otherwise. + * and {@code null} otherwise. */ public static JavaCompiler getSystemJavaCompiler() { return getSystemTool(JavaCompiler.class, @@ -78,7 +78,7 @@ * {@code null} if no documentation tool is provided * @implNote This implementation returns the tool provided * by the {@code jdk.javadoc} module if that module is available, - * and null otherwise. + * and {@code null} otherwise. */ public static DocumentationTool getSystemDocumentationTool() { return getSystemTool(DocumentationTool.class, @@ -86,16 +86,19 @@ } /** - * Returns the class loader for tools provided with this platform. - * This does not include user-installed tools. Use the - * {@linkplain java.util.ServiceLoader service provider mechanism} - * for locating user installed tools. - * - * @return the class loader for tools provided with this platform - * or {@code null} if no tools are provided + * Returns a class loader that may be used to load system tools, + * or {@code null} if no such special loader is provided. + * @implSpec This implementation always returns {@code null}. + * @deprecated This method is subject to removal in a future version of + * Java SE. + * Use the {@link java.util.spi.ToolProvider system tool provider} or + * {@link java.util.ServiceLoader service loader} mechanisms to + * locate system tools as well as user-installed tools. + * @return a class loader, or {@code null} */ + @Deprecated public static ClassLoader getSystemToolClassLoader() { - return ClassLoader.getSystemClassLoader(); + return null; } private static final boolean useLegacy; diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java Wed Jul 05 22:30:52 2017 +0200 @@ -348,9 +348,9 @@ } @Override @DefinedBy(Api.COMPILER) - public Location getModuleLocation(Location location, String moduleName) throws IOException { + public Location getLocationForModule(Location location, String moduleName) throws IOException { try { - return clientJavaFileManager.getModuleLocation(location, moduleName); + return clientJavaFileManager.getLocationForModule(location, moduleName); } catch (ClientCodeException e) { throw e; } catch (RuntimeException | Error e) { @@ -359,9 +359,9 @@ } @Override @DefinedBy(Api.COMPILER) - public Location getModuleLocation(Location location, JavaFileObject fo, String pkgName) throws IOException { + public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException { try { - return clientJavaFileManager.getModuleLocation(location, fo, pkgName); + return clientJavaFileManager.getLocationForModule(location, fo, pkgName); } catch (ClientCodeException e) { throw e; } catch (RuntimeException | Error e) { @@ -381,9 +381,9 @@ } @Override @DefinedBy(Api.COMPILER) - public Iterable> listModuleLocations(Location location) throws IOException { + public Iterable> listLocationsForModules(Location location) throws IOException { try { - return clientJavaFileManager.listModuleLocations(location); + return clientJavaFileManager.listLocationsForModules(location); } catch (ClientCodeException e) { throw e; } catch (RuntimeException | Error e) { diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ModuleFinder.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ModuleFinder.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ModuleFinder.java Wed Jul 05 22:30:52 2017 +0200 @@ -131,7 +131,7 @@ if (outerIter.hasNext()) { outer = outerIter.next(); try { - innerIter = fileManager.listModuleLocations(outer).iterator(); + innerIter = fileManager.listLocationsForModules(outer).iterator(); } catch (IOException e) { System.err.println("error listing module locations for " + outer + ": " + e); // FIXME } @@ -282,7 +282,7 @@ if (moduleLocationIterator.outer == StandardLocation.MODULE_SOURCE_PATH) { msym.sourceLocation = l; if (fileManager.hasLocation(StandardLocation.CLASS_OUTPUT)) { - msym.classLocation = fileManager.getModuleLocation(StandardLocation.CLASS_OUTPUT, msym.name.toString()); + msym.classLocation = fileManager.getLocationForModule(StandardLocation.CLASS_OUTPUT, msym.name.toString()); } } else { msym.classLocation = l; diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java Wed Jul 05 22:30:52 2017 +0200 @@ -364,7 +364,7 @@ if (msym.sourceLocation == null) { msym.sourceLocation = locn; if (fileManager.hasLocation(StandardLocation.CLASS_OUTPUT)) { - msym.classLocation = fileManager.getModuleLocation( + msym.classLocation = fileManager.getLocationForModule( StandardLocation.CLASS_OUTPUT, msym.name.toString()); } } @@ -466,7 +466,7 @@ private Location getModuleLocation(JavaFileObject fo, Name pkgName) throws IOException { // For now, just check module source path. // We may want to check source path as well. - return fileManager.getModuleLocation(StandardLocation.MODULE_SOURCE_PATH, + return fileManager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, fo, (pkgName == null) ? null : pkgName.toString()); } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/BaseFileManager.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/BaseFileManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/BaseFileManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -249,8 +249,11 @@ return false; } - if (!o.handleOption(helper, current, remaining)) - throw new IllegalArgumentException(current); + try { + o.handleOption(helper, current, remaining); + } catch (Option.InvalidValueException e) { + throw new IllegalArgumentException(e.getMessage(), e); + } return true; } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JavacFileManager.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JavacFileManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JavacFileManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -671,7 +671,7 @@ @Override @DefinedBy(Api.COMPILER) public ClassLoader getClassLoader(Location location) { - nullCheck(location); + checkNotModuleOrientedLocation(location); Iterable path = getLocation(location); if (path == null) return null; @@ -694,6 +694,7 @@ boolean recurse) throws IOException { + checkNotModuleOrientedLocation(location); // validatePackageName(packageName); nullCheck(packageName); nullCheck(kinds); @@ -715,8 +716,8 @@ @Override @DefinedBy(Api.COMPILER) public String inferBinaryName(Location location, JavaFileObject file) { + checkNotModuleOrientedLocation(location); Objects.requireNonNull(file); - Objects.requireNonNull(location); // Need to match the path semantics of list(location, ...) Iterable path = getLocationAsPaths(location); if (path == null) { @@ -750,7 +751,7 @@ JavaFileObject.Kind kind) throws IOException { - nullCheck(location); + checkNotModuleOrientedLocation(location); // validateClassName(className); nullCheck(className); nullCheck(kind); @@ -765,7 +766,7 @@ String relativeName) throws IOException { - nullCheck(location); + checkNotModuleOrientedLocation(location); // validatePackageName(packageName); nullCheck(packageName); if (!isRelativeUri(relativeName)) @@ -798,7 +799,7 @@ FileObject sibling) throws IOException { - nullCheck(location); + checkOutputLocation(location); // validateClassName(className); nullCheck(className); nullCheck(kind); @@ -814,7 +815,7 @@ FileObject sibling) throws IOException { - nullCheck(location); + checkOutputLocation(location); // validatePackageName(packageName); nullCheck(packageName); if (!isRelativeUri(relativeName)) @@ -948,10 +949,14 @@ } @Override @DefinedBy(Api.COMPILER) - public Location getModuleLocation(Location location, String moduleName) throws IOException { - nullCheck(location); + public Location getLocationForModule(Location location, String moduleName) throws IOException { + Objects.requireNonNull(location); + if (!location.isOutputLocation() && !location.isModuleOrientedLocation()) + throw new IllegalArgumentException( + "location is not an output location or a module-oriented location: " + + location.getName()); nullCheck(moduleName); - return locations.getModuleLocation(location, moduleName); + return locations.getLocationForModule(location, moduleName); } @Override @DefinedBy(Api.COMPILER) @@ -959,7 +964,7 @@ nullCheck(location); nullCheck(service); Module.getModule(getClass()).addUses(service); - if (location.isModuleLocation()) { + if (location.isModuleOrientedLocation()) { Collection paths = locations.getLocation(location); ModuleFinder finder = ModuleFinder.of(paths.toArray(new Path[paths.size()])); Layer bootLayer = Layer.boot(); @@ -972,8 +977,8 @@ } @Override @DefinedBy(Api.COMPILER) - public Location getModuleLocation(Location location, JavaFileObject fo, String pkgName) throws IOException { - nullCheck(location); + public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException { + checkModuleOrientedLocation(location); if (!(fo instanceof PathFileObject)) throw new IllegalArgumentException(fo.getName()); int depth = 1; // allow 1 for filename @@ -993,7 +998,7 @@ Path subpath = p.subpath(0, fc - depth); Path dir = (root == null) ? subpath : root.resolve(subpath); // need to find dir in location - return locations.getModuleLocation(location, dir); + return locations.getLocationForModule(location, dir); } else { return null; } @@ -1001,14 +1006,14 @@ @Override @DefinedBy(Api.COMPILER) public String inferModuleName(Location location) { - nullCheck(location); + checkNotModuleOrientedLocation(location); return locations.inferModuleName(location); } @Override @DefinedBy(Api.COMPILER) - public Iterable> listModuleLocations(Location location) throws IOException { - nullCheck(location); - return locations.listModuleLocations(location); + public Iterable> listLocationsForModules(Location location) throws IOException { + checkModuleOrientedLocation(location); + return locations.listLocationsForModules(location); } @Override @DefinedBy(Api.COMPILER) @@ -1087,6 +1092,24 @@ return e.toString(); } + private void checkOutputLocation(Location location) { + Objects.requireNonNull(location); + if (!location.isOutputLocation()) + throw new IllegalArgumentException("location is not an output location: " + location.getName()); + } + + private void checkModuleOrientedLocation(Location location) { + Objects.requireNonNull(location); + if (!location.isModuleOrientedLocation()) + throw new IllegalArgumentException("location is not module-oriented: " + location.getName()); + } + + private void checkNotModuleOrientedLocation(Location location) { + Objects.requireNonNull(location); + if (location.isModuleOrientedLocation()) + throw new IllegalArgumentException("location is module-oriented: " + location.getName()); + } + /* Converters between files and paths. * These are temporary until we can update the StandardJavaFileManager API. */ diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java Wed Jul 05 22:30:52 2017 +0200 @@ -415,16 +415,16 @@ abstract void setPaths(Iterable files) throws IOException; /** - * @see JavaFileManager#getModuleLocation(Location, String) + * @see JavaFileManager#getLocationForModule(Location, String) */ - Location getModuleLocation(String moduleName) throws IOException { + Location getLocationForModule(String moduleName) throws IOException { return null; } /** - * @see JavaFileManager#getModuleLocation(Location, JavaFileObject, String) + * @see JavaFileManager#getLocationForModule(Location, JavaFileObject, String) */ - Location getModuleLocation(Path dir) { + Location getLocationForModule(Path dir) { return null; } @@ -436,9 +436,9 @@ } /** - * @see JavaFileManager#listModuleLocations + * @see JavaFileManager#listLocationsForModules */ - Iterable> listModuleLocations() throws IOException { + Iterable> listLocationsForModules() throws IOException { return null; } } @@ -524,7 +524,7 @@ } @Override - Location getModuleLocation(String name) { + Location getLocationForModule(String name) { if (moduleLocations == null) moduleLocations = new HashMap<>(); Location l = moduleLocations.get(name); @@ -904,7 +904,7 @@ } @Override - Iterable> listModuleLocations() { + Iterable> listLocationsForModules() { if (searchPath == null) return Collections.emptyList(); @@ -1320,17 +1320,17 @@ } @Override - Location getModuleLocation(String name) { + Location getLocationForModule(String name) { return (moduleLocations == null) ? null : moduleLocations.get(name); } @Override - Location getModuleLocation(Path dir) { + Location getLocationForModule(Path dir) { return (pathLocations == null) ? null : pathLocations.get(dir); } @Override - Iterable> listModuleLocations() { + Iterable> listLocationsForModules() { if (moduleLocations == null) return Collections.emptySet(); Set locns = new LinkedHashSet<>(); @@ -1411,13 +1411,13 @@ } @Override - Location getModuleLocation(String name) throws IOException { + Location getLocationForModule(String name) throws IOException { initSystemModules(); return systemModules.get(name); } @Override - Iterable> listModuleLocations() throws IOException { + Iterable> listLocationsForModules() throws IOException { initSystemModules(); Set locns = new LinkedHashSet<>(); for (Location l: systemModules.values()) @@ -1591,14 +1591,14 @@ h.setPaths(files); } - Location getModuleLocation(Location location, String name) throws IOException { + Location getLocationForModule(Location location, String name) throws IOException { LocationHandler h = getHandler(location); - return (h == null ? null : h.getModuleLocation(name)); + return (h == null ? null : h.getLocationForModule(name)); } - Location getModuleLocation(Location location, Path dir) { + Location getLocationForModule(Location location, Path dir) { LocationHandler h = getHandler(location); - return (h == null ? null : h.getModuleLocation(dir)); + return (h == null ? null : h.getLocationForModule(dir)); } String inferModuleName(Location location) { @@ -1606,9 +1606,9 @@ return (h == null ? null : h.inferModuleName()); } - Iterable> listModuleLocations(Location location) throws IOException { + Iterable> listLocationsForModules(Location location) throws IOException { LocationHandler h = getHandler(location); - return (h == null ? null : h.listModuleLocations()); + return (h == null ? null : h.listLocationsForModules()); } protected LocationHandler getHandler(Location location) { diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/ClassWriter.java Wed Jul 05 22:30:52 2017 +0200 @@ -1626,7 +1626,7 @@ Location outLocn; if (multiModuleMode) { ModuleSymbol msym = c.owner.kind == MDL ? (ModuleSymbol) c.owner : c.packge().modle; - outLocn = fileManager.getModuleLocation(CLASS_OUTPUT, msym.name.toString()); + outLocn = fileManager.getLocationForModule(CLASS_OUTPUT, msym.name.toString()); } else { outLocn = CLASS_OUTPUT; } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/JNIWriter.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/JNIWriter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/JNIWriter.java Wed Jul 05 22:30:52 2017 +0200 @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -179,7 +179,7 @@ Location outLocn; if (multiModuleMode) { ModuleSymbol msym = c.owner.kind == MDL ? (ModuleSymbol) c.owner : c.packge().modle; - outLocn = fileManager.getModuleLocation(StandardLocation.NATIVE_HEADER_OUTPUT, msym.name.toString()); + outLocn = fileManager.getLocationForModule(StandardLocation.NATIVE_HEADER_OUTPUT, msym.name.toString()); } else { outLocn = StandardLocation.NATIVE_HEADER_OUTPUT; } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java Wed Jul 05 22:30:52 2017 +0200 @@ -161,16 +161,6 @@ } @Override - public void error(String key, Object... args) { - Arguments.this.error(key, args); - } - - @Override - public void error(JCDiagnostic.Error error) { - Arguments.this.error(error); - } - - @Override public void addFile(Path p) { files.add(p); } @@ -222,11 +212,6 @@ } @Override - public void error(String key, Object... args) { - Arguments.this.error(key, args); - } - - @Override public Log getLog() { return Arguments.this.log; } @@ -263,6 +248,17 @@ } /** + * Minimal initialization for tools, like javadoc, + * to be able to process javac options for themselves, + * and then call validate. + * @param ownName the name of this tool; used to prefix messages + */ + public void init(String ownName) { + this.ownName = ownName; + errorMode = ErrorMode.LOG; + } + + /** * Gets the files to be compiled. * @return the files to be compiled */ @@ -379,7 +375,10 @@ } if (option != null) { - if (!option.handleOption(helper, arg, argIter)) { + try { + option.handleOption(helper, arg, argIter); + } catch (Option.InvalidValueException e) { + error(e); return false; } continue; @@ -416,11 +415,11 @@ java.util.List modules = Arrays.asList(options.get(Option.MODULE).split(",")); try { for (String module : modules) { - Location sourceLoc = fm.getModuleLocation(StandardLocation.MODULE_SOURCE_PATH, module); + Location sourceLoc = fm.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH, module); if (sourceLoc == null) { log.error(Errors.ModuleNotFoundInModuleSourcePath(module)); } else { - Location classLoc = fm.getModuleLocation(StandardLocation.CLASS_OUTPUT, module); + Location classLoc = fm.getLocationForModule(StandardLocation.CLASS_OUTPUT, module); for (JavaFileObject file : fm.list(sourceLoc, "", EnumSet.of(JavaFileObject.Kind.SOURCE), true)) { String className = fm.inferBinaryName(sourceLoc, file); @@ -446,24 +445,23 @@ // It is allowed to compile nothing if just asking for help or version info. // But also note that none of these options are supported in API mode. if (options.isSet(Option.HELP) - || options.isSet(Option.X) - || options.isSet(Option.VERSION) - || options.isSet(Option.FULLVERSION) - || options.isSet(Option.MODULE)) - return true; - - if (emptyAllowed) + || options.isSet(Option.X) + || options.isSet(Option.VERSION) + || options.isSet(Option.FULLVERSION) + || options.isSet(Option.MODULE)) { return true; - - if (!errors) { - if (JavaCompiler.explicitAnnotationProcessingRequested(options)) { - error("err.no.source.files.classes"); - } else { - error("err.no.source.files"); - } } - return false; + if (!emptyAllowed) { + if (!errors) { + if (JavaCompiler.explicitAnnotationProcessingRequested(options)) { + error("err.no.source.files.classes"); + } else { + error("err.no.source.files"); + } + } + return false; + } } if (!checkDirectory(Option.D)) { @@ -555,7 +553,6 @@ } boolean lintOptions = options.isUnset(Option.XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option); - if (lintOptions && source.compareTo(Source.DEFAULT) < 0 && !options.isSet(Option.RELEASE)) { if (fm instanceof BaseFileManager) { if (((BaseFileManager) fm).isDefaultBootClassPath()) @@ -710,7 +707,6 @@ for (String moduleName : addModules.split(",")) { switch (moduleName) { case "": - case "ALL-DEFAULT": case "ALL-SYSTEM": case "ALL-MODULE-PATH": break; @@ -718,7 +714,7 @@ default: if (!SourceVersion.isName(moduleName, sv)) { // syntactically invalid module name: e.g. --add-modules m1,m! - log.warning(Warnings.BadNameForOption(Option.ADD_MODULES, moduleName)); + log.error(Errors.BadNameForOption(Option.ADD_MODULES, moduleName)); } break; } @@ -742,7 +738,7 @@ default: if (!SourceVersion.isName(moduleName, sv)) { // syntactically invalid module name: e.g. --limit-modules m1,m! - log.warning(Warnings.BadNameForOption(Option.LIMIT_MODULES, moduleName)); + log.error(Errors.BadNameForOption(Option.LIMIT_MODULES, moduleName)); } break; } @@ -757,7 +753,7 @@ public boolean isEmpty() { return ((files == null) || files.isEmpty()) && ((fileObjects == null) || fileObjects.isEmpty()) - && classNames.isEmpty(); + && (classNames == null || classNames.isEmpty()); } public void allowEmpty() { @@ -886,6 +882,21 @@ } } + void error(Option.InvalidValueException f) { + String msg = f.getMessage(); + errors = true; + switch (errorMode) { + case ILLEGAL_ARGUMENT: { + throw new PropagatedException(new IllegalArgumentException(msg, f.getCause())); + } + case ILLEGAL_STATE: { + throw new PropagatedException(new IllegalStateException(msg, f.getCause())); + } + case LOG: + log.printRawLines(ownName + ": " + msg); + } + } + void warning(String key, Object... args) { report(key, args); } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Main.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Main.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Main.java Wed Jul 05 22:30:52 2017 +0200 @@ -194,7 +194,10 @@ @Override public void put(String name, String value) { } }; - Option.HELP.process(h, "-help"); + try { + Option.HELP.process(h, "-help"); + } catch (Option.InvalidValueException ignore) { + } return Result.CMDERR; } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java Wed Jul 05 22:30:52 2017 +0200 @@ -93,9 +93,8 @@ G_NONE("-g:none", "opt.g.none", STANDARD, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { helper.put("-g:", "none"); - return false; } }, @@ -138,11 +137,10 @@ } @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { String prev = helper.get(XDOCLINT_CUSTOM); String next = (prev == null) ? option : (prev + " " + option); helper.put(XDOCLINT_CUSTOM.primaryName, next); - return false; } }, @@ -154,20 +152,18 @@ } @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { String prev = helper.get(XDOCLINT_PACKAGE); String next = (prev == null) ? option : (prev + " " + option); helper.put(XDOCLINT_PACKAGE.primaryName, next); - return false; } }, // -nowarn is retained for command-line backward compatibility NOWARN("-nowarn", "opt.nowarn", STANDARD, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { helper.put("-Xlint:none", option); - return false; } }, @@ -176,9 +172,8 @@ // -deprecation is retained for command-line backward compatibility DEPRECATION("-deprecation", "opt.deprecation", STANDARD, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { helper.put("-Xlint:deprecation", option); - return false; } }, @@ -201,15 +196,13 @@ // the the module=path pairs by an invalid path character, NULL. // The standard file manager code knows to split apart the NULL-separated components. @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { if (arg.isEmpty()) { - helper.error("err.no.value.for.option", option); - return true; + throw helper.newInvalidValueException("err.no.value.for.option", option); } else if (getPattern().matcher(arg).matches()) { String prev = helper.get(PATCH_MODULE); if (prev == null) { super.process(helper, option, arg); - return false; } else { String argModulePackage = arg.substring(0, arg.indexOf('=')); boolean isRepeated = Arrays.stream(prev.split("\0")) @@ -217,16 +210,13 @@ .collect(Collectors.toSet()) .contains(argModulePackage); if (isRepeated) { - helper.error("err.repeated.value.for.patch.module", argModulePackage); - return true; + throw helper.newInvalidValueException("err.repeated.value.for.patch.module", argModulePackage); } else { super.process(helper, option, prev + '\0' + arg); - return false; } } } else { - helper.error("err.bad.value.for.option", option, arg); - return true; + throw helper.newInvalidValueException("err.bad.value.for.option", option, arg); } } @@ -238,10 +228,10 @@ BOOT_CLASS_PATH("--boot-class-path -bootclasspath", "opt.arg.path", "opt.bootclasspath", STANDARD, FILEMANAGER) { @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { helper.remove("-Xbootclasspath/p:"); helper.remove("-Xbootclasspath/a:"); - return super.process(helper, option, arg); + super.process(helper, option, arg); } }, @@ -251,10 +241,10 @@ XBOOTCLASSPATH("-Xbootclasspath:", "opt.arg.path", "opt.bootclasspath", EXTENDED, FILEMANAGER) { @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { helper.remove("-Xbootclasspath/p:"); helper.remove("-Xbootclasspath/a:"); - return super.process(helper, "-bootclasspath", arg); + super.process(helper, "-bootclasspath", arg); } }, @@ -262,8 +252,8 @@ DJAVA_EXT_DIRS("-Djava.ext.dirs=", "opt.arg.dirs", "opt.extdirs", EXTENDED, FILEMANAGER) { @Override - public boolean process(OptionHelper helper, String option, String arg) { - return EXTDIRS.process(helper, "-extdirs", arg); + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { + EXTDIRS.process(helper, "-extdirs", arg); } }, @@ -271,8 +261,8 @@ DJAVA_ENDORSED_DIRS("-Djava.endorsed.dirs=", "opt.arg.dirs", "opt.endorseddirs", EXTENDED, FILEMANAGER) { @Override - public boolean process(OptionHelper helper, String option, String arg) { - return ENDORSEDDIRS.process(helper, "-endorseddirs", arg); + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { + ENDORSEDDIRS.process(helper, "-endorseddirs", arg); } }, @@ -298,25 +288,23 @@ SOURCE("-source", "opt.arg.release", "opt.source", STANDARD, BASIC) { @Override - public boolean process(OptionHelper helper, String option, String operand) { + public void process(OptionHelper helper, String option, String operand) throws InvalidValueException { Source source = Source.lookup(operand); if (source == null) { - helper.error("err.invalid.source", operand); - return true; + throw helper.newInvalidValueException("err.invalid.source", operand); } - return super.process(helper, option, operand); + super.process(helper, option, operand); } }, TARGET("-target", "opt.arg.release", "opt.target", STANDARD, BASIC) { @Override - public boolean process(OptionHelper helper, String option, String operand) { + public void process(OptionHelper helper, String option, String operand) throws InvalidValueException { Target target = Target.lookup(operand); if (target == null) { - helper.error("err.invalid.target", operand); - return true; + throw helper.newInvalidValueException("err.invalid.target", operand); } - return super.process(helper, option, operand); + super.process(helper, option, operand); } }, @@ -345,46 +333,45 @@ PROFILE("-profile", "opt.arg.profile", "opt.profile", STANDARD, BASIC) { @Override - public boolean process(OptionHelper helper, String option, String operand) { + public void process(OptionHelper helper, String option, String operand) throws InvalidValueException { Profile profile = Profile.lookup(operand); if (profile == null) { - helper.error("err.invalid.profile", operand); - return true; + throw helper.newInvalidValueException("err.invalid.profile", operand); } - return super.process(helper, option, operand); + super.process(helper, option, operand); } }, VERSION("-version", "opt.version", STANDARD, INFO) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { Log log = helper.getLog(); String ownName = helper.getOwnName(); log.printLines(WriterKind.STDOUT, PrefixKind.JAVAC, "version", ownName, JavaCompiler.version()); - return super.process(helper, option); + super.process(helper, option); } }, FULLVERSION("-fullversion", null, HIDDEN, INFO) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { Log log = helper.getLog(); String ownName = helper.getOwnName(); log.printLines(WriterKind.STDOUT, PrefixKind.JAVAC, "fullVersion", ownName, JavaCompiler.fullVersion()); - return super.process(helper, option); + super.process(helper, option); } }, // Note: -h is already taken for "native header output directory". HELP("--help -help", "opt.help", STANDARD, INFO) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { Log log = helper.getLog(); String ownName = helper.getOwnName(); log.printLines(WriterKind.STDOUT, PrefixKind.JAVAC, "msg.usage.header", ownName); showHelp(log, OptionKind.STANDARD); log.printNewline(WriterKind.STDOUT); - return super.process(helper, option); + super.process(helper, option); } }, @@ -401,31 +388,28 @@ // Mapping for processor options created in // JavacProcessingEnvironment @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { int argLength = option.length(); if (argLength == 2) { - helper.error("err.empty.A.argument"); - return true; + throw helper.newInvalidValueException("err.empty.A.argument"); } int sepIndex = option.indexOf('='); String key = option.substring(2, (sepIndex != -1 ? sepIndex : argLength) ); if (!JavacProcessingEnvironment.isValidOptionName(key)) { - helper.error("err.invalid.A.key", option); - return true; + throw helper.newInvalidValueException("err.invalid.A.key", option); } helper.put(option, option); - return false; } }, X("-X", "opt.X", STANDARD, INFO) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { Log log = helper.getLog(); showHelp(log, OptionKind.EXTENDED); log.printNewline(WriterKind.STDOUT); log.printLines(WriterKind.STDOUT, PrefixKind.JAVAC, "msg.usage.nonstandard.footer"); - return super.process(helper, option); + super.process(helper, option); } }, @@ -433,16 +417,16 @@ // It's actually implemented by the launcher. J("-J", "opt.arg.flag", "opt.J", STANDARD, INFO, ArgKind.ADJACENT) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { throw new AssertionError("the -J flag should be caught by the launcher."); } }, MOREINFO("-moreinfo", null, HIDDEN, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { Type.moreInfo = true; - return super.process(helper, option); + super.process(helper, option); } }, @@ -462,9 +446,8 @@ // display warnings for generic unchecked operations WARNUNCHECKED("-warnunchecked", null, HIDDEN, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { helper.put("-Xlint:unchecked", option); - return false; } }, @@ -474,15 +457,14 @@ XSTDOUT("-Xstdout", "opt.arg.file", "opt.Xstdout", EXTENDED, INFO) { @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { try { Log log = helper.getLog(); log.setWriters(new PrintWriter(new FileWriter(arg), true)); } catch (java.io.IOException e) { - helper.error("err.error.writing.file", arg, e); - return true; + throw helper.newInvalidValueException("err.error.writing.file", arg, e); } - return super.process(helper, option, arg); + super.process(helper, option, arg); } }, @@ -507,11 +489,10 @@ PLUGIN("-Xplugin:", "opt.arg.plugin", "opt.plugin", EXTENDED, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { String p = option.substring(option.indexOf(':') + 1).trim(); String prev = helper.get(PLUGIN); helper.put(PLUGIN.primaryName, (prev == null) ? p : prev + '\0' + p); - return false; } }, @@ -519,22 +500,22 @@ DEBUG("--debug:", null, HIDDEN, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { - return HiddenGroup.DEBUG.process(helper, option); + public void process(OptionHelper helper, String option) throws InvalidValueException { + HiddenGroup.DEBUG.process(helper, option); } }, SHOULDSTOP("--should-stop:", null, HIDDEN, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { - return HiddenGroup.SHOULDSTOP.process(helper, option); + public void process(OptionHelper helper, String option) throws InvalidValueException { + HiddenGroup.SHOULDSTOP.process(helper, option); } }, DIAGS("--diags:", null, HIDDEN, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { - return HiddenGroup.DIAGS.process(helper, option); + public void process(OptionHelper helper, String option) throws InvalidValueException { + HiddenGroup.DIAGS.process(helper, option); } }, @@ -548,33 +529,29 @@ return s.startsWith(primaryName); } @Override - public boolean process(OptionHelper helper, String option) { - return process(helper, option, option.substring(primaryName.length())); + public void process(OptionHelper helper, String option) { + process(helper, option, option.substring(primaryName.length())); } @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) { int eq = arg.indexOf('='); String key = (eq < 0) ? arg : arg.substring(0, eq); String value = (eq < 0) ? arg : arg.substring(eq+1); helper.put(key, value); - return false; } }, ADD_EXPORTS("--add-exports", "opt.arg.addExports", "opt.addExports", EXTENDED, BASIC) { @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { if (arg.isEmpty()) { - helper.error("err.no.value.for.option", option); - return true; + throw helper.newInvalidValueException("err.no.value.for.option", option); } else if (getPattern().matcher(arg).matches()) { String prev = helper.get(ADD_EXPORTS); helper.put(ADD_EXPORTS.primaryName, (prev == null) ? arg : prev + '\0' + arg); - return false; } else { - helper.error("err.bad.value.for.option", option, arg); - return true; + throw helper.newInvalidValueException("err.bad.value.for.option", option, arg); } } @@ -586,17 +563,14 @@ ADD_READS("--add-reads", "opt.arg.addReads", "opt.addReads", EXTENDED, BASIC) { @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { if (arg.isEmpty()) { - helper.error("err.no.value.for.option", option); - return true; + throw helper.newInvalidValueException("err.no.value.for.option", option); } else if (getPattern().matcher(arg).matches()) { String prev = helper.get(ADD_READS); helper.put(ADD_READS.primaryName, (prev == null) ? arg : prev + '\0' + arg); - return false; } else { - helper.error("err.bad.value.for.option", option, arg); - return true; + throw helper.newInvalidValueException("err.bad.value.for.option", option, arg); } } @@ -608,14 +582,12 @@ XMODULE("-Xmodule:", "opt.arg.module", "opt.module", EXTENDED, BASIC) { @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { String prev = helper.get(XMODULE); if (prev != null) { - helper.error("err.option.too.many", XMODULE.primaryName); - return true; + throw helper.newInvalidValueException("err.option.too.many", XMODULE.primaryName); } helper.put(XMODULE.primaryName, arg); - return false; } }, @@ -623,19 +595,16 @@ ADD_MODULES("--add-modules", "opt.arg.addmods", "opt.addmods", STANDARD, BASIC) { @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { if (arg.isEmpty()) { - helper.error("err.no.value.for.option", option); - return true; + throw helper.newInvalidValueException("err.no.value.for.option", option); } else if (getPattern().matcher(arg).matches()) { String prev = helper.get(ADD_MODULES); // since the individual values are simple names, we can simply join the // values of multiple --add-modules options with ',' helper.put(ADD_MODULES.primaryName, (prev == null) ? arg : prev + ',' + arg); - return false; } else { - helper.error("err.bad.value.for.option", option, arg); - return true; + throw helper.newInvalidValueException("err.bad.value.for.option", option, arg); } } @@ -647,16 +616,13 @@ LIMIT_MODULES("--limit-modules", "opt.arg.limitmods", "opt.limitmods", STANDARD, BASIC) { @Override - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { if (arg.isEmpty()) { - helper.error("err.no.value.for.option", option); - return true; + throw helper.newInvalidValueException("err.no.value.for.option", option); } else if (getPattern().matcher(arg).matches()) { helper.put(LIMIT_MODULES.primaryName, arg); // last one wins - return false; } else { - helper.error("err.bad.value.for.option", option, arg); - return true; + throw helper.newInvalidValueException("err.bad.value.for.option", option, arg); } } @@ -670,7 +636,7 @@ // It's actually implemented by the CommandLine class. AT("@", "opt.arg.file", "opt.AT", STANDARD, INFO, ArgKind.ADJACENT) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) { throw new AssertionError("the @ flag should be caught by CommandLine."); } }, @@ -690,22 +656,19 @@ } } @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { if (option.endsWith(".java") ) { Path p = Paths.get(option); if (!Files.exists(p)) { - helper.error("err.file.not.found", p); - return true; + throw helper.newInvalidValueException("err.file.not.found", p); } if (!Files.isRegularFile(p)) { - helper.error("err.file.not.file", p); - return true; + throw helper.newInvalidValueException("err.file.not.file", p); } helper.addFile(p); } else { helper.addClassName(option); } - return false; } }, @@ -714,7 +677,7 @@ INHERIT_RUNTIME_ENVIRONMENT("--inherit-runtime-environment", "opt.inherit_runtime_environment", EXTENDED, BASIC) { @Override - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { try { Class.forName(JDK9Wrappers.VMHelper.VM_CLASSNAME); String[] runtimeArgs = JDK9Wrappers.VMHelper.getRuntimeArguments(); @@ -723,15 +686,34 @@ // The runtime arguments always use the single token form, e.g. "--name=value". for (Option o : getSupportedRuntimeOptions()) { if (o.matches(arg)) { - o.handleOption(helper, arg, Collections.emptyIterator()); + switch (o) { + case ADD_MODULES: + int eq = arg.indexOf('='); + Assert.check(eq > 0, () -> ("invalid runtime option:" + arg)); + // --add-modules=ALL-DEFAULT is not supported at compile-time + // so remove it from list, and only process the rest + // if the set is non-empty. + // Note that --add-modules=ALL-DEFAULT is automatically added + // by the standard javac launcher. + String mods = Arrays.stream(arg.substring(eq + 1).split(",")) + .filter(s -> !s.isEmpty() && !s.equals("ALL-DEFAULT")) + .collect(Collectors.joining(",")); + if (!mods.isEmpty()) { + String updatedArg = arg.substring(0, eq + 1) + mods; + o.handleOption(helper, updatedArg, Collections.emptyIterator()); + } + break; + default: + o.handleOption(helper, arg, Collections.emptyIterator()); + break; + } break; } } } } catch (ClassNotFoundException | SecurityException e) { - helper.error("err.cannot.access.runtime.env"); + throw helper.newInvalidValueException("err.cannot.access.runtime.env"); } - return false; } private Option[] getSupportedRuntimeOptions() { @@ -748,6 +730,23 @@ }; /** + * This exception is thrown when an invalid value is given for an option. + * The detail string gives a detailed, localized message, suitable for use + * in error messages reported to the user. + */ + public static class InvalidValueException extends Exception { + private static final long serialVersionUID = -1; + + public InvalidValueException(String msg) { + super(msg); + } + + public InvalidValueException(String msg, Throwable cause) { + super(msg, cause); + } + } + + /** * The kind of argument, if any, accepted by this option. The kind is augmented * by characters in the name of the option. */ @@ -831,14 +830,13 @@ this.text = text; } - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { String p = option.substring(option.indexOf(':') + 1).trim(); String[] subOptions = p.split(";"); for (String subOption : subOptions) { subOption = text + "." + subOption.trim(); XD.process(helper, subOption, subOption); } - return false; } static boolean skip(String name) { @@ -1038,7 +1036,7 @@ * @return true if the operation was successful, and false otherwise * @implNote The return value is the opposite of that used by {@link #process}. */ - public boolean handleOption(OptionHelper helper, String arg, Iterator rest) { + public void handleOption(OptionHelper helper, String arg, Iterator rest) throws InvalidValueException { if (hasArg()) { String option; String operand; @@ -1051,15 +1049,14 @@ operand = arg.substring(sep + 1); } else { if (!rest.hasNext()) { - helper.error("err.req.arg", arg); - return false; + throw helper.newInvalidValueException("err.req.arg", arg); } option = arg; operand = rest.next(); } - return !process(helper, option, operand); + process(helper, option, operand); } else { - return !process(helper, arg); + process(helper, arg); } } @@ -1068,14 +1065,14 @@ * or which contains an argument within it, following a separator. * @param helper a helper to provide access to the environment * @param option the option to be processed - * @return true if an error occurred + * @throws InvalidValueException if an error occurred */ - public boolean process(OptionHelper helper, String option) { + public void process(OptionHelper helper, String option) throws InvalidValueException { if (argKind == ArgKind.NONE) { - return process(helper, primaryName, option); + process(helper, primaryName, option); } else { int sep = findSeparator(option); - return process(helper, primaryName, option.substring(sep + 1)); + process(helper, primaryName, option.substring(sep + 1)); } } @@ -1085,9 +1082,8 @@ * @param option the option to be processed * @param arg the value to associate with the option, or a default value * to be used if the option does not otherwise take an argument. - * @return true if an error occurred */ - public boolean process(OptionHelper helper, String option, String arg) { + public void process(OptionHelper helper, String option, String arg) throws InvalidValueException { if (choices != null) { if (choiceKind == ChoiceKind.ONEOF) { // some clients like to see just one of option+choice set @@ -1110,7 +1106,6 @@ helper.put(primaryName, arg); if (group == OptionGroup.FILEMANAGER) helper.handleFileManagerOption(this, arg); - return false; } /** diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/OptionHelper.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/OptionHelper.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/OptionHelper.java Wed Jul 05 22:30:52 2017 +0200 @@ -43,29 +43,55 @@ public abstract class OptionHelper { - /** Get the current value of an option. */ + /** + * Get the current value of an option. + * @param option the option + * @return the value of the option + */ public abstract String get(Option option); - /** Set the value of an option. */ + /** + * Set the value of an option. + * @param name the primary name of the option + * @param value the value for the option + */ public abstract void put(String name, String value); - /** Remove any prior value for an option. */ + /** + * Remove any prior value for an option. + * @param name the primary name of the option + */ public abstract void remove(String name); - /** Handle a file manager option. */ + /** + * Handle a file manager option. + * @param option the option + * @param value the value for the option + * @return true if the option was handled successfully, and false otherwise + */ public abstract boolean handleFileManagerOption(Option option, String value); - /** Get access to the Log for the compilation. */ + /** + * Get access to the Log for the compilation. + * @return the log + */ public abstract Log getLog(); - /** Get the name of the tool, such as "javac", to be used in info like -help. */ + /** + * Get the name of the tool, such as "javac", to be used in info like -help. + * @return the name of the tool + */ public abstract String getOwnName(); - /** Report an error. */ - abstract void error(String key, Object... args); - - /** Report an error. */ - abstract void error(JCDiagnostic.Error error); + /** + * Returns a new InvalidValueException, with a localized detail message. + * @param key the resource key for the message + * @param args the arguments, if any, for the resource string + * @return the InvalidValueException + */ + Option.InvalidValueException newInvalidValueException(String key, Object... args) { + return new Option.InvalidValueException(getLog().localize(PrefixKind.JAVAC, key, args)); + } /** Record a file to be compiled. */ abstract void addFile(Path p); @@ -112,16 +138,6 @@ } @Override - void error(String key, Object... args) { - throw new IllegalArgumentException(log.localize(PrefixKind.JAVAC, key, args)); - } - - @Override - void error(JCDiagnostic.Error error) { - throw new IllegalArgumentException(log.localize(error)); - } - - @Override public void addFile(Path p) { throw new IllegalArgumentException(p.toString()); } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties Wed Jul 05 22:30:52 2017 +0200 @@ -2848,6 +2848,10 @@ compiler.warn.bad.name.for.option=\ bad name in value for {0} option: ''{1}'' +# 0: option name, 1: string +compiler.err.bad.name.for.option=\ + bad name in value for {0} option: ''{1}'' + # 0: option name, 1: symbol compiler.warn.module.for.option.not.found=\ module name in {0} option not found: {1} diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/SmartFileManager.java --- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/SmartFileManager.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/sjavac/comp/SmartFileManager.java Wed Jul 05 22:30:52 2017 +0200 @@ -204,8 +204,8 @@ } @Override @DefinedBy(Api.COMPILER) - public Location getModuleLocation(Location location, JavaFileObject fo, String pkgName) throws IOException { - return super.getModuleLocation(location, locUnwrap(fo), pkgName); + public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException { + return super.getLocationForModule(location, locUnwrap(fo), pkgName); } private static String packageNameFromFileName(String fn) { diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java --- a/langtools/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocFormatter.java Wed Jul 05 22:30:52 2017 +0200 @@ -246,7 +246,7 @@ @Override @DefinedBy(Api.COMPILER_TREE) public Object visitStartElement(StartElementTree node, Object p) { - switch (HtmlTag.get(node.getName())) { + switch (getHtmlTag(node.getName())) { case P: if (lastNode!= null && lastNode.getKind() == DocTree.Kind.START_ELEMENT && HtmlTag.get(((StartElementTree) lastNode).getName()) == HtmlTag.LI) { @@ -397,7 +397,7 @@ } private void handleEndElement(Name name) { - switch (HtmlTag.get(name)) { + switch (getHtmlTag(name)) { case BLOCKQUOTE: indent -= INDENT; break; @@ -629,6 +629,12 @@ } } + private static HtmlTag getHtmlTag(Name name) { + HtmlTag tag = HtmlTag.get(name); + + return tag != null ? tag : HtmlTag.HTML; //using HtmlTag.HTML as default no-op value + } + private static Map countTableColumns(DocCommentTree dct) { Map result = new IdentityHashMap<>(); @@ -639,7 +645,7 @@ @Override @DefinedBy(Api.COMPILER_TREE) public Void visitStartElement(StartElementTree node, Void p) { - switch (HtmlTag.get(node.getName())) { + switch (getHtmlTag(node.getName())) { case TABLE: currentTable = node; break; case TR: currentMaxColumns = Math.max(currentMaxColumns, currentRowColumns); diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/JavadocTool.java --- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/JavadocTool.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/JavadocTool.java Wed Jul 05 22:30:52 2017 +0200 @@ -393,7 +393,7 @@ for (ModuleSymbol msym : modules.allModules()) { PackageSymbol p = syms.getPackage(msym, pack); if (p != null && !p.members().isEmpty()) { - return fm.getModuleLocation(location, msym.name.toString()); + return fm.getLocationForModule(location, msym.name.toString()); } } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Start.java --- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Start.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/Start.java Wed Jul 05 22:30:52 2017 +0200 @@ -45,6 +45,7 @@ import com.sun.tools.javac.main.CommandLine; import com.sun.tools.javac.main.Option; import com.sun.tools.javac.file.BaseFileManager; +import com.sun.tools.javac.main.Arguments; import com.sun.tools.javac.main.OptionHelper; import com.sun.tools.javac.main.OptionHelper.GrumpyHelper; import com.sun.tools.javac.platform.PlatformDescription; @@ -309,12 +310,16 @@ if (o == ToolOption.LOCALE && i > 0) usageError("main.locale_first"); - if (o.hasArg) { - oneArg(argv, i++); - o.process(this, argv[i]); - } else { - setOption(arg); - o.process(this); + try { + if (o.hasArg) { + oneArg(argv, i++); + o.process(this, argv[i]); + } else { + setOption(arg); + o.process(this); + } + } catch (Option.InvalidValueException e) { + usageError("main.option.invalid.value", e.getMessage()); } } else if (arg.equals("-XDaccessInternalAPI")) { // pass this hidden option down to the doclet, if it wants it @@ -367,6 +372,11 @@ ((BaseFileManager) fileManager).handleOptions(fileManagerOpts); } + Arguments arguments = Arguments.instance(context); + arguments.init(messager.programName); + arguments.allowEmpty(); + arguments.validate(); + String platformString = compOpts.get("--release"); if (platformString != null) { @@ -560,7 +570,7 @@ @Override OptionHelper getOptionHelper() { - return new GrumpyHelper(null) { + return new GrumpyHelper(messager) { @Override public String get(com.sun.tools.javac.main.Option option) { return compOpts.get(option); diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ToolOption.java --- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ToolOption.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ToolOption.java Wed Jul 05 22:30:52 2017 +0200 @@ -31,6 +31,7 @@ import com.sun.tools.javac.code.Flags; import com.sun.tools.javac.main.Option; +import com.sun.tools.javac.main.Option.InvalidValueException; import com.sun.tools.javac.main.OptionHelper; import com.sun.tools.javac.util.ListBuffer; import com.sun.tools.javac.util.Options; @@ -141,14 +142,14 @@ ADD_MODULES("--add-modules", true) { @Override - public void process(Helper helper, String arg) { + public void process(Helper helper, String arg) throws InvalidValueException { Option.ADD_MODULES.process(helper.getOptionHelper(), opt, arg); } }, LIMIT_MODULES("--limit-modules", true) { @Override - public void process(Helper helper, String arg) { + public void process(Helper helper, String arg) throws InvalidValueException { Option.LIMIT_MODULES.process(helper.getOptionHelper(), opt, arg); } }, @@ -191,28 +192,28 @@ ADD_READS("--add-reads", true) { @Override - public void process(Helper helper, String arg) { + public void process(Helper helper, String arg) throws InvalidValueException { Option.ADD_READS.process(helper.getOptionHelper(), opt, arg); } }, ADD_EXPORTS("--add-exports", true) { @Override - public void process(Helper helper, String arg) { + public void process(Helper helper, String arg) throws InvalidValueException { Option.ADD_EXPORTS.process(helper.getOptionHelper(), opt, arg); } }, XMODULE("-Xmodule:", false) { @Override - public void process(Helper helper, String arg) { + public void process(Helper helper, String arg) throws InvalidValueException { Option.XMODULE.process(helper.getOptionHelper(), arg); } }, PATCH_MODULE("--patch-module", true) { @Override - public void process(Helper helper, String arg) { + public void process(Helper helper, String arg) throws InvalidValueException { Option.PATCH_MODULE.process(helper.getOptionHelper(), opt, arg); } }, @@ -356,7 +357,7 @@ this.hasArg = hasArg; } - void process(Helper helper, String arg) { } + void process(Helper helper, String arg) throws Option.InvalidValueException { } void process(Helper helper) { } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/resources/javadoc.properties --- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/resources/javadoc.properties Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/resources/javadoc.properties Wed Jul 05 22:30:52 2017 +0200 @@ -126,6 +126,7 @@ main.release.bootclasspath.conflict=option {0} cannot be used together with -release main.unsupported.release.version=release version {0} not supported main.release.not.standard.file.manager=-release option specified, but the provided JavaFileManager is not a StandardJavaFileManager. +main.option.invalid.value={0} tag.illegal_char_in_arr_dim=Tag {0}: Syntax Error in array dimension, method parameters: {1} tag.illegal_see_tag=Tag {0}: Syntax Error in method parameters: {1} tag.missing_comma_space=Tag {0}: Missing comma or space in method parameters: {1} diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/Doclet.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/Doclet.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/Doclet.java Wed Jul 05 22:30:52 2017 +0200 @@ -25,7 +25,7 @@ package jdk.javadoc.doclet; -import java.util.ListIterator; +import java.util.List; import java.util.Locale; import java.util.Set; @@ -67,7 +67,7 @@ * @param locale the locale to be used * @param reporter the reporter to be used */ - public void init(Locale locale, Reporter reporter); + void init(Locale locale, Reporter reporter); /** * Returns a name identifying the doclet. A name is a simple identifier @@ -76,14 +76,14 @@ * * @return name of the Doclet */ - public abstract String getName(); + String getName(); /** * Returns all the supported options. * * @return a set containing all the supported options, an empty set if none */ - public Set

      *    public boolean run(DocletEnvironment environment)
      * 
    - * The {@link jdk.javadoc.doclet.DocletEnvironment} instance holds the environment that the - * doclet will be initialized with. From this environment all other information can be - * extracted, in the form of {@link javax.lang.model} elements. One can further use the - * APIs and utilities described by {@link javax.lang.model} to query Elements and Types. + * The {@link jdk.javadoc.doclet.DocletEnvironment} instance holds the + * environment that the doclet will be initialized with. From this environment + * all other information can be extracted, in the form of + * {@link javax.lang.model.element.Element elements}. One can further use the APIs and utilities + * described by {@link javax.lang.model Language Model API} to query Elements and Types. *

    * * *

    Terminology

    * - * - * Module, package and source file names can be provided as parameters to the - * javadoc tool -- these are called the specified set containing - * module elements, package elements and type elements. + *
    + *
    Selected
    + *
    An element is considered to be selected, if the + * selection controls allow it + * to be documented. (Note that synthetic elements are never + * selected.) + *
    + * + *
    Specified
    + *
    The set of elements specified by the user are considered to be specified + * elements. Specified elements provide the starting points + * for determining the included elements to be documented. + *
    + * + *
    Included
    + *
    An element is considered to be included, if it is + * specified if it contains a specified element, + * or it is enclosed in a specified element, and is selected. + * Included elements will be documented. + *
    + * + *
    *

    - * Javadoc selection control can be specified with - * {@code --show-members:value}, {@code --showtypes:value}, where value can be one of - * the following: - *

      - *
    • public -- considers only public elements - *
    • protected -- considers public and protected elements - *
    • package -- considers public, protected and package private elements - *
    • private -- considers all elements - *
    - * - * The {@code --show-package:value} where a value of "exported" or "all" can be used to - * consider only exported packages or all packages within a module. - *

    - * The {@code --expand-requires:value}, expands the "requires" directives of a - * module declaration, to create a module set to considered for documentation + * + *

    Options

    + * Javadoc selection control can be specified with these options * as follows: *
      - *
    • public -- follows and expands all "requires public" edges in the module graph - *
    • all -- follows and expands all "requires" edges in the module graph. - * By default, only the specified modules will be considered, without expansion - * of the module dependencies. + *
    • {@code --show-members:value} and {@code --show-types:value} can + * be used to filter the members, with the following values: + *
        + *
      • public -- considers only public elements + *
      • protected -- considers public and protected elements + *
      • package -- considers public, protected and package private elements + *
      • private -- considers all elements + *
      + * + *
    • {@code --show-packages:value} "exported" or "all" can be used + * to consider only exported packages or all packages within a module. + * + *
    • {@code --show-module-contents:value} can be used to specify the level at + * module declarations could be documented. A value of "api" indicates API + * level documentation, and "all" indicates detailed documentation. *
    - * - * All of the above are used to select the elements, to produce the - * included or the selected set. - *

    - * {@code --show-module-contents:value} can be used to specify the level at - * module declarations could be documented, a value of "api" indicates API - * level documentation, and "all" indicates detailed documentation. + * The following options can be used to specify the elements to be documented: + *

      + *
    • {@code --module} documents the specified modules. + * + *
    • {@code --expand-requires:value} expand the set of modules to be documented + * by including some or all of the modules dependencies. The value may be + * one of: + *
        + *
      • public -- each module specified explicitly on the command line is + * expanded to include the closure of its transitive dependencies + *
      • all -- each module specified explicitly on the command line + * is expanded to include the closure of its transitive dependencies, + * and also all of its direct dependencies + *
      + * By default, only the specified modules will be considered, without expansion + * of the module dependencies. + * + *
    • {@code packagenames} can be used to specify packages. + *
    • {@code -subpackages} can be used to recursively load packages. + *
    • {@code -exclude} can be used exclude package directories. + *
    • {@code sourcefilenames} can be used to specify source file names. + *
    *

    * *

    Interactions with older options.

    * - * The new --show-* options provide a more detailed replacement for the older - * options -public, -protected, -package, -private. Alternatively, the older - * options can continue to be used as shorter forms for combinations of the - * new options, as described below: + * The new {@code --show-*} options provide a more detailed replacement + * for the older options -public, -protected, -package, -private. + * Alternatively, the older options can continue to be used as shorter + * forms for combinations of the new options, as described below:
    Short form options mapping
    Older optionEquivalent to these values with the new option -
    --show-members--show-types--show-packages--show-module-contents -
    -publicpublicpublicexportedapi -
    -protectedprotectedprotectedexportedapi -
    -packagepackagepackageallall -
    -privateprivateprivateallall +
    {@code --show-members}{@code --show-types}{@code --show-packages}{@code --show-module-contents} +
    {@code -public}publicpublicexportedapi +
    {@code -protected}protectedprotectedexportedapi +
    {@code -package}packagepackageallall +
    {@code -private}privateprivateallall
    *

    * @@ -119,127 +152,120 @@ *

    Example

    * * The following is an example doclet that displays information of a class - * and its members, supporting an option "someoption". + * and its members, supporting an option. *
    - * import com.sun.source.doctree.DocCommentTree;
    - * import com.sun.source.util.DocTrees;
    - * import java.io.IOException;
    - * import java.util.Collections;
    - * import java.util.Set;
    - * import javax.lang.model.SourceVersion;
    - * import javax.lang.model.element.Element;
    - * import javax.lang.model.element.TypeElement;
    - * import jdk.javadoc.doclet.*;
    + * // note imports deleted for clarity
    + * public class Example implements Doclet {
    + *    Reporter reporter;
    + *    @Override
    + *    public void init(Locale locale, Reporter reporter) {
    + *        reporter.print(Kind.NOTE, "Doclet using locale: " + locale);
    + *        this.reporter = reporter;
    + *    }
      *
    - * public class Example implements Doclet {
    - *
    - *     @Override
    - *     public void init(Locale locale, Reporter reporter) {
    - *        return;
    - *     }
    + *    public void printElement(DocTrees trees, Element e) {
    + *        DocCommentTree docCommentTree = trees.getDocCommentTree(e);
    + *        if (docCommentTree != null) {
    + *            System.out.println("Element (" + e.getKind() + ": "
    + *                    + e + ") has the following comments:");
    + *            System.out.println("Entire body: " + docCommentTree.getFullBody());
    + *            System.out.println("Block tags: " + docCommentTree.getBlockTags());
    + *        }
    + *    }
      *
    - *     @Override
    - *     public boolean run(DocletEnvironment docEnv) {
    - *         // cache the DocTrees utility class to access DocComments
    - *         DocTrees docTrees = docEnv.getDocTrees();
    + *    @Override
    + *    public boolean run(DocletEnvironment docEnv) {
    + *        reporter.print(Kind.NOTE, "overviewfile: " + overviewfile);
    + *        // get the DocTrees utility class to access document comments
    + *        DocTrees docTrees = docEnv.getDocTrees();
      *
    - *         // location of an element in the same directory as overview.html
    - *         try {
    - *             Element barElement = null;
    - *             for (Element e : docEnv.getIncludedClasses()) {
    - *                 if (e.getSimpleName().toString().equals("FooBar")) {
    - *                     barElement = e;
    - *                 }
    - *             }
    - *             DocCommentTree docCommentTree =
    - *                     docTrees.getDocCommentTree(barElement, "overview.html");
    - *             if (docCommentTree != null) {
    - *                 System.out.println("Overview html: " +
    - *                         docCommentTree.getFullBody());
    - *             }
    - *         } catch (IOException missing) {
    - *             System.err.println("No overview.html found.");
    - *         }
    + *        // location of an element in the same directory as overview.html
    + *        try {
    + *            Element e = ElementFilter.typesIn(docEnv.getSpecifiedElements()).iterator().next();
    + *            DocCommentTree docCommentTree
    + *                    = docTrees.getDocCommentTree(e, overviewfile);
    + *            if (docCommentTree != null) {
    + *                System.out.println("Overview html: " + docCommentTree.getFullBody());
    + *            }
    + *        } catch (IOException missing) {
    + *            reporter.print(Kind.ERROR, "No overview.html found.");
    + *        }
    + *
    + *        for (TypeElement t : ElementFilter.typesIn(docEnv.getIncludedElements())) {
    + *            System.out.println(t.getKind() + ":" + t);
    + *            for (Element e : t.getEnclosedElements()) {
    + *                printElement(docTrees, e);
    + *            }
    + *        }
    + *        return true;
    + *    }
    + *
    + *    @Override
    + *    public String getName() {
    + *        return "Example";
    + *    }
      *
    - *         for (TypeElement t : docEnv.getIncludedClasses()) {
    - *             System.out.println(t.getKind() + ":" + t);
    - *             for (Element e : t.getEnclosedElements()) {
    - *                 DocCommentTree docCommentTree = docTrees.getDocCommentTree(e);
    - *                 if (docCommentTree != null) {
    - *                     System.out.println("Element (" + e.getKind() + ": " +
    - *                             e + ") has the following comments:");
    - *                     System.out.println("Entire body: " + docCommentTree.getFullBody());
    - *                     System.out.println("Block tags: " + docCommentTree.getBlockTags());
    - *                 } else {
    - *                     System.out.println("no comment.");
    - *                 }
    - *             }
    - *         }
    - *         return true;
    - *     }
    + *    private String overviewfile;
      *
    - *     @Override
    - *     public String getName() {
    - *         return "Example";
    - *     }
    + *    @Override
    + *    public Set<? extends Option> getSupportedOptions() {
    + *        Option[] options = {
    + *            new Option() {
    + *                private final List<String> someOption = Arrays.asList(
    + *                        "-overviewfile",
    + *                        "--overview-file",
    + *                        "-o"
    + *                );
      *
    - *   private String someOption;
    + *                @Override
    + *                public int getArgumentCount() {
    + *                    return 1;
    + *                }
    + *
    + *                @Override
    + *                public String getDescription() {
    + *                    return "an option with aliases";
    + *                }
      *
    - *   @Override
    - *   public Set<Option> getSupportedOptions() {
    - *       Option[] options = {
    - *           new Option() {
    - *               public int getArgumentCount() {
    - *                   return 1;
    - *               }
    - *               public String getDescription() {
    - *                   return "someoption";
    - *               }
    - *               public Option.Kind getKind() {
    - *                   return Option.Kind.STANDARD;
    - *               }
    - *               public String getName() {
    - *                   return "someoption";
    - *               }
    - *               public String getParameters() {
    - *                   return "url";
    - *               }
    - *               public boolean matches(String option) {
    - *                  String opt = option.startsWith("-") ? option.substring(1) : option;
    - *                  return getName().equals(opt);
    - *               }
    - *               public boolean process(String option, ListIterator<String> arguments) {
    - *                  overviewpath = arguments.next();
    - *                  return true;
    - *               }
    - *          }
    - *      };
    - *      return new HashSet<Option>(Arrays.asList(options));
    - *     }
    + *                @Override
    + *                public Option.Kind getKind() {
    + *                    return Option.Kind.STANDARD;
    + *                }
    + *
    + *                @Override
    + *                public List<String> getNames() {
    + *                    return someOption;
    + *                }
    + *
    + *                @Override
    + *                public String getParameters() {
    + *                    return "file";
    + *                }
      *
    - *     @Override
    - *     public SourceVersion getSupportedSourceVersion() {
    - *         // support the latest release
    - *         return SourceVersion.latest();
    - *     }
    + *                @Override
    + *                public boolean process(String opt, List<String> arguments) {
    + *                    overviewfile = arguments.get(0);
    + *                    return true;
    + *                }
    + *            }
    + *        };
    + *        return new HashSet<>(Arrays.asList(options));
    + *    }
    + *
    + *    @Override
    + *    public SourceVersion getSupportedSourceVersion() {
    + *        // support the latest release
    + *        return SourceVersion.latest();
    + *    }
      * }
      * 
    *

    - * This doclet when invoked with a command line, such as: - *

    - *     javadoc -doclet Example -sourcepath <source-location>
    - * 
    - * will produce an output, such as: + * This doclet can be invoked with a command line, such as: *
    - *  Overview.html: overview comments
    - *  ...
    - *  ...
    - *  CLASS: SomeKlass
    - *  .....
    - *  Element (METHOD: main(java.lang.String...)) has the following comments:
    - *  Entire body: The main entry point.
    - *  Block tags: @param an array of Strings
    - *  ...
    + *     javadoc -doclet Example \
    + *       -overviewfile overview.html \
    + *       -sourcepath source-location \
    + *       source-location/Example.java
      * 
    * *

    Migration Guide

    diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/taglet/Taglet.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/taglet/Taglet.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/doclet/taglet/Taglet.java Wed Jul 05 22:30:52 2017 +0200 @@ -54,13 +54,13 @@ * @return true if this Taglet * is an inline tag, false otherwise. */ - public abstract boolean isInlineTag(); + boolean isInlineTag(); /** * Returns the name of the tag. * @return the name of this custom tag. */ - public abstract String getName(); + String getName(); /** * Given the {@link DocTree DocTree} representation of this custom @@ -69,7 +69,7 @@ * @param tag the Tag representation of this custom tag. * @return the string representation of this Tag. */ - public abstract String toString(DocTree tag); + String toString(DocTree tag); /** * Given a List of {@link DocTree DocTrees} representing this custom @@ -79,7 +79,7 @@ * @param tags the list of DocTrees representing this custom tag. * @return the string representation of this Tag. */ - public abstract String toString(List tags); + String toString(List tags); /** * The kind of location. diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ClassUseWriter.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ClassUseWriter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ClassUseWriter.java Wed Jul 05 22:30:52 2017 +0200 @@ -52,6 +52,7 @@ import jdk.javadoc.internal.doclets.toolkit.util.DocPath; import jdk.javadoc.internal.doclets.toolkit.util.DocPaths; + /** * Generate class usage information. * @@ -178,7 +179,7 @@ */ public static void generate(ConfigurationImpl configuration, ClassTree classtree) throws DocFileIOException { ClassUseMapper mapper = new ClassUseMapper(configuration, classtree); - for (TypeElement aClass : configuration.docEnv.getIncludedTypeElements()) { + for (TypeElement aClass : configuration.getIncludedTypeElements()) { // If -nodeprecated option is set and the containing package is marked // as deprecated, do not generate the class-use page. We will still generate // the class-use page if the class is marked as deprecated but the containing diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ConfigurationImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -288,83 +288,13 @@ if (!generalValidOptions()) { return false; } - boolean helpfileSeen = false; - // otherwise look at our options - for (Doclet.Option opt : optionsProcessed) { - if (opt.matches("-helpfile")) { - if (nohelp == true) { - reporter.print(ERROR, getText("doclet.Option_conflict", - "-helpfile", "-nohelp")); - return false; - } - if (helpfileSeen) { - reporter.print(ERROR, getText("doclet.Option_reuse", - "-helpfile")); - return false; - } - helpfileSeen = true; - DocFile help = DocFile.createFileForInput(this, helpfile); - if (!help.exists()) { - reporter.print(ERROR, getText("doclet.File_not_found", helpfile)); - return false; - } - } else if (opt.matches("-nohelp")) { - if (helpfileSeen) { - reporter.print(ERROR, getText("doclet.Option_conflict", - "-nohelp", "-helpfile")); - return false; - } - } else if (opt.matches("-xdocrootparent")) { - try { - URL ignored = new URL(docrootparent); - } catch (MalformedURLException e) { - reporter.print(ERROR, getText("doclet.MalformedURL", docrootparent)); - return false; - } - } else if (opt.matches("-overview")) { - if (nooverview == true) { - reporter.print(ERROR, getText("doclet.Option_conflict", - "-overview", "-nooverview")); - return false; - } - } else if (opt.matches("-nooverview")) { - if (overviewpath != null) { - reporter.print(ERROR, getText("doclet.Option_conflict", - "-nooverview", "-overview")); - return false; - } - } else if (opt.matches("-splitindex")) { - if (createindex == false) { - reporter.print(ERROR, getText("doclet.Option_conflict", - "-splitindex", "-noindex")); - return false; - } - } else if (opt.matches("-noindex")) { - if (splitindex == true) { - reporter.print(ERROR, getText("doclet.Option_conflict", - "-noindex", "-splitindex")); - return false; - } - } else if (opt.matches("-xdoclint:")) { - String dopt = doclintOpts.get(opt); - if (dopt == null) { - continue; - } - if (dopt.contains("/")) { - reporter.print(ERROR, getText("doclet.Option_doclint_no_qualifiers")); - return false; - } - if (!DocLint.isValidOption(dopt)) { - reporter.print(ERROR, getText("doclet.Option_doclint_invalid_arg")); - return false; - } - } else if (opt.matches("-xdoclint/package:")) { - String dopt = doclintOpts.get(opt); - if (!DocLint.isValidOption(dopt)) { - reporter.print(ERROR, getText("doclet.Option_doclint_package_invalid_arg")); - return false; - } - } + // check if helpfile exists + if (!helpfile.isEmpty()) { + DocFile help = DocFile.createFileForInput(this, helpfile); + if (!help.exists()) { + reporter.print(ERROR, getText("doclet.File_not_found", helpfile)); + return false; + } } return true; } @@ -374,11 +304,10 @@ if (!validateOptions()) { return false; } - if (!docEnv.getSpecifiedElements().isEmpty()) { + if (!getSpecifiedTypeElements().isEmpty()) { Map map = new HashMap<>(); PackageElement pkg; - List classes = new ArrayList<>(docEnv.getIncludedTypeElements()); - for (TypeElement aClass : classes) { + for (TypeElement aClass : getIncludedTypeElements()) { pkg = utils.containingPackage(aClass); if (!map.containsKey(utils.getPackageName(pkg))) { map.put(utils.getPackageName(pkg), pkg); @@ -426,7 +355,7 @@ if (showModules) { topFile = DocPath.empty.resolve(DocPaths.moduleSummary(modules.first())); } else if (packages.size() == 1 && packages.first().isUnnamed()) { - List classes = new ArrayList<>(docEnv.getIncludedTypeElements()); + List classes = new ArrayList<>(getIncludedTypeElements()); if (!classes.isEmpty()) { TypeElement te = getValidClass(classes); topFile = DocPath.forClass(utils, te); @@ -450,7 +379,7 @@ } protected boolean checkForDeprecation(DocletEnvironment docEnv) { - for (TypeElement te : docEnv.getIncludedTypeElements()) { + for (TypeElement te : getIncludedTypeElements()) { if (isGeneratedDoc(te)) { return true; } @@ -597,227 +526,245 @@ Doclet.Option[] options = { new Option(resources, "-bottom", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - bottom = args.next(); + public boolean process(String opt, List args) { + bottom = args.get(0); return true; } }, new Option(resources, "-charset", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - charset = args.next(); + public boolean process(String opt, List args) { + charset = args.get(0); return true; } }, new Option(resources, "-doctitle", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - doctitle = args.next(); + public boolean process(String opt, List args) { + doctitle = args.get(0); return true; } }, new Option(resources, "-footer", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - footer = args.next(); + public boolean process(String opt, List args) { + footer = args.get(0); return true; } }, new Option(resources, "-header", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - header = args.next(); + public boolean process(String opt, List args) { + header = args.get(0); return true; } }, new Option(resources, "-helpfile", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - helpfile = args.next(); + public boolean process(String opt, List args) { + if (nohelp == true) { + reporter.print(ERROR, getText("doclet.Option_conflict", + "-helpfile", "-nohelp")); + return false; + } + if (!helpfile.isEmpty()) { + reporter.print(ERROR, getText("doclet.Option_reuse", + "-helpfile")); + return false; + } + helpfile = args.get(0); return true; } }, new Option(resources, "-html4") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { htmlVersion = HtmlVersion.HTML4; return true; } }, new Option(resources, "-html5") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { htmlVersion = HtmlVersion.HTML5; return true; } }, new Option(resources, "-nohelp") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { nohelp = true; + if (!helpfile.isEmpty()) { + reporter.print(ERROR, getText("doclet.Option_conflict", + "-nohelp", "-helpfile")); + return false; + } return true; } }, new Option(resources, "-nodeprecatedlist") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { nodeprecatedlist = true; return true; } }, new Option(resources, "-noindex") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { createindex = false; + if (splitindex == true) { + reporter.print(ERROR, getText("doclet.Option_conflict", + "-noindex", "-splitindex")); + return false; + } return true; } }, new Option(resources, "-nonavbar") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { nonavbar = true; return true; } }, new Hidden(resources, "-nooverview") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { nooverview = true; + if (overviewpath != null) { + reporter.print(ERROR, getText("doclet.Option_conflict", + "-nooverview", "-overview")); + return false; + } return true; } }, new Option(resources, "-notree") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { createtree = false; return true; } }, new Option(resources, "-overview", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - overviewpath = args.next(); + public boolean process(String opt, List args) { + overviewpath = args.get(0); + if (nooverview == true) { + reporter.print(ERROR, getText("doclet.Option_conflict", + "-overview", "-nooverview")); + return false; + } return true; } }, new Option(resources, "--frames") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { frames = true; return true; } }, new Option(resources, "--no-frames") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { frames = false; return true; } }, new Hidden(resources, "-packagesheader", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - packagesheader = args.next(); + public boolean process(String opt, List args) { + packagesheader = args.get(0); return true; } }, new Option(resources, "-splitindex") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { splitindex = true; + if (createindex == false) { + reporter.print(ERROR, getText("doclet.Option_conflict", + "-splitindex", "-noindex")); + return false; + } return true; } }, new Option(resources, "-stylesheetfile", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - stylesheetfile = args.next(); + public boolean process(String opt, List args) { + stylesheetfile = args.get(0); return true; } }, new Option(resources, "-top", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - top = args.next(); + public boolean process(String opt, List args) { + top = args.get(0); return true; } }, new Option(resources, "-use") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { classuse = true; return true; } }, new Option(resources, "-windowtitle", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - windowtitle = args.next().replaceAll("\\<.*?>", ""); + public boolean process(String opt, List args) { + windowtitle = args.get(0).replaceAll("\\<.*?>", ""); return true; } }, new XOption(resources, "-Xdoclint") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { doclintOpts.put(this, DocLint.XMSGS_OPTION); return true; } }, new XOption(resources, "-Xdocrootparent", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - docrootparent = args.next(); + public boolean process(String opt, List args) { + docrootparent = args.get(0); + try { + URL ignored = new URL(docrootparent); + } catch (MalformedURLException e) { + reporter.print(ERROR, getText("doclet.MalformedURL", docrootparent)); + return false; + } return true; } }, new XOption(resources, "doclet.usage.xdoclint-extended", "-Xdoclint:", 0) { @Override - public boolean matches(String option) { - return option.toLowerCase().startsWith(getName().toLowerCase()); - } - - @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - doclintOpts.put(this, opt.replace("-Xdoclint:", DocLint.XMSGS_CUSTOM_PREFIX)); + public boolean process(String opt, List args) { + String dopt = opt.replace("-Xdoclint:", DocLint.XMSGS_CUSTOM_PREFIX); + doclintOpts.put(this, dopt); + if (dopt.contains("/")) { + reporter.print(ERROR, getText("doclet.Option_doclint_no_qualifiers")); + return false; + } + if (!DocLint.isValidOption(dopt)) { + reporter.print(ERROR, getText("doclet.Option_doclint_invalid_arg")); + return false; + } return true; } }, new XOption(resources, "doclet.usage.xdoclint-package", "-Xdoclint/package:", 0) { @Override - public boolean matches(String option) { - return option.toLowerCase().startsWith(getName().toLowerCase()); - } - - @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - doclintOpts.put(this, opt.replace("-Xdoclint/package:", DocLint.XCHECK_PACKAGE)); + public boolean process(String opt, List args) { + String dopt = opt.replace("-Xdoclint/package:", DocLint.XCHECK_PACKAGE); + doclintOpts.put(this, dopt); + if (!DocLint.isValidOption(dopt)) { + reporter.print(ERROR, getText("doclet.Option_doclint_package_invalid_arg")); + return false; + } return true; } } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDoclet.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDoclet.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDoclet.java Wed Jul 05 22:30:52 2017 +0200 @@ -91,10 +91,11 @@ * Create the configuration instance. * Override this method to use a different * configuration. - * @return the configuration for this doclet + * + * @return the configuration */ @Override // defined by AbstractDoclet - public ConfigurationImpl configuration() { + public ConfigurationImpl getConfiguration() { return configuration; } @@ -166,8 +167,7 @@ IndexRedirectWriter.generate(configuration); } - if (configuration.helpfile.length() == 0 && - !configuration.nohelp) { + if (configuration.helpfile.isEmpty() && !configuration.nohelp) { HelpWriter.generate(configuration); } // If a stylesheet file is not specified, copy the default stylesheet diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java Wed Jul 05 22:30:52 2017 +0200 @@ -826,8 +826,8 @@ * @return a content tree for the link */ protected Content getNavLinkTree() { - List packages = new ArrayList<>(configuration.getSpecifiedPackages()); - DocPath docPath = packages.size() == 1 && configuration.getSpecifiedClasses().isEmpty() + List packages = new ArrayList<>(configuration.getSpecifiedPackageElements()); + DocPath docPath = packages.size() == 1 && configuration.getSpecifiedTypeElements().isEmpty() ? pathString(packages.get(0), DocPaths.PACKAGE_TREE) : pathToRoot.resolve(DocPaths.OVERVIEW_TREE); return HtmlTree.LI(getHyperLink(docPath, contents.treeLabel, "", "")); diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ModuleFrameWriter.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ModuleFrameWriter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ModuleFrameWriter.java Wed Jul 05 22:30:52 2017 +0200 @@ -32,6 +32,7 @@ import javax.lang.model.element.TypeElement; import javax.lang.model.util.ElementFilter; +import jdk.javadoc.doclet.DocletEnvironment; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlConstants; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlStyle; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTag; @@ -41,7 +42,6 @@ import jdk.javadoc.internal.doclets.toolkit.util.DocFileIOException; import jdk.javadoc.internal.doclets.toolkit.util.DocPaths; - /** * Class to generate file for each module contents in the left-hand bottom * frame. This will list all the Class Kinds in the module. A click on any @@ -78,9 +78,9 @@ public ModuleFrameWriter(ConfigurationImpl configuration, ModuleElement moduleElement) { super(configuration, DocPaths.moduleTypeFrame(moduleElement)); this.mdle = moduleElement; - if (configuration.getSpecifiedPackages().isEmpty()) { + if (configuration.getSpecifiedPackageElements().isEmpty()) { documentedClasses = new TreeSet<>(utils.makeGeneralPurposeComparator()); - documentedClasses.addAll(configuration.docEnv.getIncludedTypeElements()); + documentedClasses.addAll(configuration.getIncludedTypeElements()); } } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/PackageFrameWriter.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/PackageFrameWriter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/PackageFrameWriter.java Wed Jul 05 22:30:52 2017 +0200 @@ -30,6 +30,7 @@ import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; +import jdk.javadoc.doclet.DocletEnvironment; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlConstants; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlStyle; import jdk.javadoc.internal.doclets.formats.html.markup.HtmlTag; @@ -41,7 +42,6 @@ import jdk.javadoc.internal.doclets.toolkit.util.DocPath; import jdk.javadoc.internal.doclets.toolkit.util.DocPaths; - /** * Class to generate file for each package contents in the left-hand bottom * frame. This will list all the Class Kinds in the package. A click on any @@ -82,9 +82,9 @@ public PackageFrameWriter(ConfigurationImpl configuration, PackageElement packageElement) { super(configuration, DocPath.forPackage(packageElement).resolve(DocPaths.PACKAGE_FRAME)); this.packageElement = packageElement; - if (configuration.getSpecifiedPackages().isEmpty()) { + if (configuration.getSpecifiedPackageElements().isEmpty()) { documentedClasses = new TreeSet<>(utils.makeGeneralPurposeComparator()); - documentedClasses.addAll(configuration.docEnv.getIncludedTypeElements()); + documentedClasses.addAll(configuration.getIncludedTypeElements()); } } diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SerializedFormWriterImpl.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SerializedFormWriterImpl.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SerializedFormWriterImpl.java Wed Jul 05 22:30:52 2017 +0200 @@ -66,7 +66,7 @@ */ public SerializedFormWriterImpl(ConfigurationImpl configuration) { super(configuration, DocPaths.SERIALIZED_FORM); - visibleClasses = configuration.docEnv.getIncludedTypeElements(); + visibleClasses = configuration.getIncludedTypeElements(); } /** diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/SourceToHTMLConverter.java Wed Jul 05 22:30:52 2017 +0200 @@ -115,13 +115,13 @@ if (docEnv == null || outputdir == null) { return; } - for (PackageElement pkg : configuration.getSpecifiedPackages()) { + for (PackageElement pkg : configuration.getSpecifiedPackageElements()) { // If -nodeprecated option is set and the package is marked as deprecated, // do not convert the package files to HTML. if (!(configuration.nodeprecated && utils.isDeprecated(pkg))) convertPackage(pkg, outputdir); } - for (TypeElement te : configuration.getSpecifiedClasses()) { + for (TypeElement te : configuration.getSpecifiedTypeElements()) { // If -nodeprecated option is set and the class is marked as deprecated // or the containing package is deprecated, do not convert the // package files to HTML. diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/AbstractDoclet.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/AbstractDoclet.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/AbstractDoclet.java Wed Jul 05 22:30:52 2017 +0200 @@ -99,8 +99,8 @@ */ @Override public boolean run(DocletEnvironment docEnv) { - configuration = configuration(); - configuration.docEnv = docEnv; + configuration = getConfiguration(); + configuration.initConfiguration(docEnv); configuration.cmtUtils = new CommentUtils(configuration); configuration.utils = new Utils(configuration); utils = configuration.utils; @@ -171,13 +171,12 @@ return SourceVersion.RELEASE_9; } - /** * Create the configuration instance and returns it. * * @return the configuration of the doclet. */ - public abstract Configuration configuration(); + public abstract Configuration getConfiguration(); /** * Start the generation of files. Call generate methods in the individual @@ -189,7 +188,7 @@ * @throws DocletException if there is a problem while generating the documentation */ private void startGeneration(DocletEnvironment docEnv) throws DocletException { - if (docEnv.getIncludedTypeElements().isEmpty()) { + if (configuration.getIncludedTypeElements().isEmpty()) { messages.error("doclet.No_Public_Classes_To_Document"); return; } @@ -263,7 +262,7 @@ throws DocletException { generateClassFiles(classtree); SortedSet packages = new TreeSet<>(utils.makePackageComparator()); - packages.addAll(configuration.getSpecifiedPackages()); + packages.addAll(configuration.getSpecifiedPackageElements()); configuration.modulePackages.values().stream().forEach(pset -> { packages.addAll(pset); }); diff -r 183ae2332dd9 -r f4e854a77aa3 langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Configuration.java --- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Configuration.java Wed Jul 05 22:29:12 2017 +0200 +++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Configuration.java Wed Jul 05 22:30:52 2017 +0200 @@ -33,10 +33,13 @@ import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.util.ElementFilter; +import javax.lang.model.util.SimpleElementVisitor9; import javax.tools.JavaFileManager; import javax.tools.JavaFileObject; import com.sun.source.util.DocTreePath; +import com.sun.tools.javac.util.DefinedBy; +import com.sun.tools.javac.util.DefinedBy.Api; import jdk.javadoc.doclet.Doclet; import jdk.javadoc.doclet.DocletEnvironment; import jdk.javadoc.doclet.Reporter; @@ -96,7 +99,7 @@ /** * The path to Taglets */ - public String tagletpath = ""; + public String tagletpath = null; /** * This is true if option "-serialwarn" is used. Defualt value is false to @@ -312,9 +315,7 @@ */ public SortedSet packages = null; - protected final List optionsProcessed; - - public final OverviewElement overviewElement; + public OverviewElement overviewElement; // The following three fields provide caches for use by all instances of VisibleMemberMap. public final Map> propertiesCache = new HashMap<>(); @@ -336,16 +337,34 @@ protected static final String sharedResourceBundleName = "jdk.javadoc.internal.doclets.toolkit.resources.doclets"; /** - * Constructor. Constructs the message retriever with resource file. + * Constructs the configurations needed by the doclet. */ public Configuration() { excludedDocFileDirs = new HashSet<>(); excludedQualifiers = new HashSet<>(); setTabWidth(DocletConstants.DEFAULT_TAB_STOP_LENGTH); metakeywords = new MetaKeywords(this); - optionsProcessed = new ArrayList<>(); groups = new ArrayList<>(0); + } + + private boolean initialized = false; + + protected void initConfiguration(DocletEnvironment docEnv) { + if (initialized) { + throw new IllegalStateException("configuration previously initialized"); + } + initialized = true; + this.docEnv = docEnv; overviewElement = new OverviewElement(docEnv); + Splitter specifiedSplitter = new Splitter(docEnv, false); + specifiedModuleElements = Collections.unmodifiableSet(specifiedSplitter.mset); + specifiedPackageElements = Collections.unmodifiableSet(specifiedSplitter.pset); + specifiedTypeElements = Collections.unmodifiableSet(specifiedSplitter.tset); + + Splitter includedSplitter = new Splitter(docEnv, true); + includedModuleElements = Collections.unmodifiableSet(includedSplitter.mset); + includedPackageElements = Collections.unmodifiableSet(includedSplitter.pset); + includedTypeElements = Collections.unmodifiableSet(includedSplitter.tset); } /** @@ -364,10 +383,40 @@ return this.reporter; } + private Set specifiedModuleElements; + public Set getSpecifiedModuleElements() { + return specifiedModuleElements; + } + + private Set specifiedPackageElements; + public Set getSpecifiedPackageElements() { + return specifiedPackageElements; + } + + private Set specifiedTypeElements; + public Set getSpecifiedTypeElements() { + return specifiedTypeElements; + } + + private Set includedModuleElements; + public Set getIncludedModuleElements() { + return includedModuleElements; + } + + private Set includedPackageElements; + public Set getIncludedPackageElements() { + return includedPackageElements; + } + + private Set includedTypeElements; + public Set getIncludedTypeElements() { + return includedTypeElements; + } + private void initModules() { // Build the modules structure used by the doclet modules = new TreeSet<>(utils.makeModuleComparator()); - modules.addAll(getSpecifiedModules()); + modules.addAll(getSpecifiedModuleElements()); modulePackages = new TreeMap<>(utils.makeModuleComparator()); for (PackageElement p: packages) { @@ -379,7 +428,7 @@ } } - for (PackageElement p: docEnv.getIncludedPackageElements()) { + for (PackageElement p: getIncludedPackageElements()) { ModuleElement mdle = docEnv.getElementUtils().getModuleOf(p); if (mdle != null && !mdle.isUnnamed()) { Set s = modulePackages @@ -398,7 +447,7 @@ private void initPackages() { packages = new TreeSet<>(utils.makePackageComparator()); // add all the included packages - packages.addAll(docEnv.getIncludedPackageElements()); + packages.addAll(includedPackageElements); } public Set getSupportedOptions() { @@ -406,165 +455,145 @@ Doclet.Option[] options = { new Option(resources, "-author") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { showauthor = true; return true; } }, new Option(resources, "-d", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - destDirName = addTrailingFileSep(args.next()); + public boolean process(String opt, List args) { + destDirName = addTrailingFileSep(args.get(0)); return true; } }, new Option(resources, "-docencoding", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - docencoding = args.next(); + public boolean process(String opt, List args) { + docencoding = args.get(0); return true; } }, new Option(resources, "-docfilessubdirs") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { copydocfilesubdirs = true; return true; } }, new Hidden(resources, "-encoding", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - encoding = args.next(); + public boolean process(String opt, List args) { + encoding = args.get(0); return true; } }, new Option(resources, "-excludedocfilessubdir", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - addToSet(excludedDocFileDirs, args.next()); + public boolean process(String opt, List args) { + addToSet(excludedDocFileDirs, args.get(0)); return true; } }, new Option(resources, "-group", 2) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - groups.add(new GroupContainer(args.next(), args.next())); + public boolean process(String opt, List args) { + groups.add(new GroupContainer(args.get(0), args.get(1))); return true; } }, new Hidden(resources, "-javafx") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { javafx = true; return true; } }, new Option(resources, "-keywords") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { keywords = true; return true; } }, new Option(resources, "-link", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - urlForLink = args.next(); + public boolean process(String opt, List args) { + urlForLink = args.get(0); pkglistUrlForLink = urlForLink; return true; } }, new Option(resources, "-linksource") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { linksource = true; return true; } }, new Option(resources, "-linkoffline", 2) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - urlForLinkOffline = args.next(); - pkglistUrlForLinkOffline = args.next(); + public boolean process(String opt, List args) { + urlForLinkOffline = args.get(0); + pkglistUrlForLinkOffline = args.get(1); return true; } }, new Option(resources, "-nocomment") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { nocomment = true; return true; } }, new Option(resources, "-nodeprecated") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { nodeprecated = true; return true; } }, new Option(resources, "-nosince") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { nosince = true; return true; } }, new Option(resources, "-notimestamp") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { notimestamp = true; return true; } }, new Option(resources, "-noqualifier", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - addToSet(excludedQualifiers, args.next()); + public boolean process(String opt, List args) { + addToSet(excludedQualifiers, args.get(0)); return true; } }, new Hidden(resources, "-quiet") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { quiet = true; return true; } }, new Option(resources, "-serialwarn") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { serialwarn = true; return true; } }, new Option(resources, "-sourcetab", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { linksource = true; try { - setTabWidth(Integer.parseInt(args.next())); + setTabWidth(Integer.parseInt(args.get(0))); } catch (NumberFormatException e) { //Set to -1 so that warning will be printed //to indicate what is valid argument. @@ -579,45 +608,41 @@ }, new Option(resources, "-tag", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { ArrayList list = new ArrayList<>(); list.add(opt); - list.add(args.next()); + list.add(args.get(0)); customTagStrs.add(list); return true; } }, new Option(resources, "-taglet", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { ArrayList list = new ArrayList<>(); list.add(opt); - list.add(args.next()); + list.add(args.get(0)); customTagStrs.add(list); return true; } }, new Option(resources, "-tagletpath", 1) { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); - tagletpath = args.next(); + public boolean process(String opt, List args) { + tagletpath = args.get(0); return true; } }, new Option(resources, "-version") { @Override - public boolean process(String opt, ListIterator args) { - optionsProcessed.add(this); + public boolean process(String opt, List args) { showversion = true; return true; } }, new Hidden(resources, "--dump-on-error") { @Override - public boolean process(String opt, ListIterator args) { + public boolean process(String opt, List args) { dumpOnError = true; return true; } @@ -643,7 +668,7 @@ if (docencoding == null) { docencoding = encoding; } - typeElementCatalog = new TypeElementCatalog(docEnv.getIncludedTypeElements(), this); + typeElementCatalog = new TypeElementCatalog(includedTypeElements, this); initTagletManager(customTagStrs); groups.stream().forEach((grp) -> { group.checkPackageGroups(grp.value1, grp.value2); @@ -798,25 +823,19 @@ } /** + * * This checks for the validity of the options used by the user. - * This works exactly like DocErrorReporter. This will validate the options which are shared - * by our doclets. For example, this method will flag an error using - * the DocErrorReporter if user has used "-nohelp" and "-helpfile" option - * together. + * As of this writing, this checks only docencoding. * * @return true if all the options are valid. */ public boolean generalValidOptions() { - boolean docencodingfound = false; - for (Doclet.Option opt : optionsProcessed) { - if (opt.matches("-docencoding")) { - docencodingfound = true; - if (!checkOutputFileEncoding(docencoding)) { - return false; - } + if (docencoding != null) { + if (!checkOutputFileEncoding(docencoding)) { + return false; } } - if (!docencodingfound && (encoding != null && !encoding.isEmpty())) { + if (docencoding == null && (encoding != null && !encoding.isEmpty())) { if (!checkOutputFileEncoding(encoding)) { return false; } @@ -897,35 +916,6 @@ : utils.getFullyQualifiedName(te); } - // cache these, as they are repeatedly called. - private Set specifiedClasses = null; - private Set specifiedPackages = null; - private Set specifiedModules = null; - - public Set getSpecifiedClasses() { - if (specifiedClasses == null) { - specifiedClasses = new LinkedHashSet<>( - ElementFilter.typesIn(docEnv.getSpecifiedElements())); - } - return specifiedClasses; - } - - public Set getSpecifiedPackages() { - if (specifiedPackages == null) { - specifiedPackages = new LinkedHashSet<>( - ElementFilter.packagesIn(docEnv.getSpecifiedElements())); - } - return specifiedPackages; - } - - public Set getSpecifiedModules() { - if (specifiedModules == null) { - specifiedModules = new LinkedHashSet<>( - ElementFilter.modulesIn(docEnv.getSpecifiedElements())); - } - return specifiedModules; - } - /** * Convenience method to obtain a resource from the doclet's * {@link Resources resources}. @@ -1058,7 +1048,7 @@ public abstract boolean showMessage(Element e, String key); public static abstract class Option implements Doclet.Option, Comparable