From af874b5889ad633f93b04d6b5e9eb2dbbb654831 Mon Sep 17 00:00:00 2001 From: Peter Brunet Date: Fri, 27 Mar 2015 15:48:08 -0500 Subject: [PATCH 01/70] 8076182: Open Source Java Access Bridge - Create Patch for JEP C127 8055831 Move files from open to closed Reviewed-by: prr, mchung, erikj, ihse, serb, bpatel --- make/Images.gmk | 6 +++- make/Javadoc.gmk | 56 ++++++++++++++++++++++++++++++++++- make/Main.gmk | 3 ++ make/common/NON_CORE_PKGS.gmk | 7 +++-- modules.xml | 9 ++++-- 5 files changed, 75 insertions(+), 6 deletions(-) diff --git a/make/Images.gmk b/make/Images.gmk index 3a8171416c7..c454b0e5a8a 100644 --- a/make/Images.gmk +++ b/make/Images.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2014, 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 @@ -57,6 +57,10 @@ ifeq ($(OPENJDK_TARGET_OS), solaris) PROVIDER_MODULES += jdk.crypto.ucrypto endif +ifeq ($(OPENJDK_TARGET_OS), windows) + MAIN_MODULES += jdk.accessibility +endif + ifeq ($(OPENJDK_TARGET_OS), macosx) MAIN_MODULES += jdk.deploy.osx endif diff --git a/make/Javadoc.gmk b/make/Javadoc.gmk index 2a7a59ea83e..4569ed84272 100644 --- a/make/Javadoc.gmk +++ b/make/Javadoc.gmk @@ -1,4 +1,4 @@ -# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 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 @@ -81,6 +81,8 @@ NASHORNAPI_FIRST_COPYRIGHT_YEAR = 2014 JNLP_FIRST_COPYRIGHT_YEAR = 1998 PLUGIN2_FIRST_COPYRIGHT_YEAR = 2007 JDKNET_FIRST_COPYRIGHT_YEAR = 2014 +JACCESSAPI_FIRST_COPYRIGHT_YEAR = 2002 + # Oracle name FULL_COMPANY_NAME = Oracle and/or its affiliates @@ -1231,6 +1233,58 @@ $(SCTPAPI_PACKAGES_FILE): $(call PackageDependencies,$(SCTPAPI_PKGS)) $(prep-target) $(call PackageFilter,$(SCTPAPI_PKGS)) +############################################################# +# +# jaccessdocs - Java Accessibility Utilities +# + +ALL_OTHER_TARGETS += jaccessdocs + +JACCESSAPI_DOCDIR := $(JRE_API_DOCSDIR)/accessibility/jaccess/spec +JACCESSAPI2COREAPI := ../../../$(JDKJRE2COREAPI) +JACCESSAPI_DOCTITLE := JACCESS API +JACCESSAPI_WINDOWTITLE := JACCESS API +JACCESSAPI_HEADER := JACCESS API +JACCESSAPI_BOTTOM := $(call CommonBottom,$(JACCESSAPI_FIRST_COPYRIGHT_YEAR)) +# JACCESSAPI_PKGS is located in NON_CORE_PKGS.gmk + +JACCESSAPI_INDEX_HTML = $(JACCESSAPI_DOCDIR)/index.html +JACCESSAPI_OPTIONS_FILE = $(DOCSTMPDIR)/jaccess.options +JACCESSAPI_PACKAGES_FILE = $(DOCSTMPDIR)/jaccess.packages + +jaccessdocs: $(JACCESSAPI_INDEX_HTML) + +# Set relative location to core api document root +$(JACCESSAPI_INDEX_HTML): GET2DOCSDIR=$(JACCESSAPI2COREAPI)/.. + +# Run javadoc if the index file is out of date or missing +$(JACCESSAPI_INDEX_HTML): $(JACCESSAPI_OPTIONS_FILE) $(JACCESSAPI_PACKAGES_FILE) $(COREAPI_INDEX_FILE) + $(prep-javadoc) + $(call JavadocSummary,$(JACCESSAPI_OPTIONS_FILE),$(JACCESSAPI_PACKAGES_FILE)) + $(JAVADOC_CMD) -d $(@D) \ + @$(JACCESSAPI_OPTIONS_FILE) @$(JACCESSAPI_PACKAGES_FILE) + +# Create file with javadoc options in it +$(JACCESSAPI_OPTIONS_FILE): + $(prep-target) + @($(call COMMON_JAVADOCFLAGS) ; \ + $(call COMMON_JAVADOCTAGS) ; \ + $(call OptionOnly,-Xdoclint:all) ; \ + $(call OptionPair,-sourcepath,$(RELEASEDOCS_SOURCEPATH)) ; \ + $(call OptionPair,-encoding,ascii) ; \ + $(call OptionOnly,-nodeprecatedlist) ; \ + $(call OptionPair,-doctitle,$(JACCESSAPI_DOCTITLE)) ; \ + $(call OptionPair,-windowtitle,$(JACCESSAPI_WINDOWTITLE) $(DRAFT_WINTITLE)); \ + $(call OptionPair,-header,$(JACCESSAPI_HEADER)$(DRAFT_HEADER)) ; \ + $(call OptionPair,-bottom,$(JACCESSAPI_BOTTOM)$(DRAFT_BOTTOM)) ; \ + $(call OptionTrip,-linkoffline,$(JACCESSAPI2COREAPI),$(COREAPI_DOCSDIR)/); \ + ) >> $@ + +# Create a file with the package names in it +$(JACCESSAPI_PACKAGES_FILE): $(call PackageDependencies,$(JACCESSAPI_PKGS)) + $(prep-target) + $(call PackageFilter,$(JACCESSAPI_PKGS)) + ############################################################# # # jdk.net docs diff --git a/make/Main.gmk b/make/Main.gmk index 5a4e0d5c23a..31e2fa69c3e 100644 --- a/make/Main.gmk +++ b/make/Main.gmk @@ -386,6 +386,9 @@ else # links against libosxapp. jdk.deploy.osx-libs: java.desktop-libs + # jdk.accessibility depends on java.desktop + jdk.accessibility-libs: java.desktop-libs + # This dependency needs to be explicitly declared. jdk.jdi-gensrc generates a # header file used by jdk.jdwp.agent-libs. The jdk.jdwp.agent-gensrc is a # virtual target. diff --git a/make/common/NON_CORE_PKGS.gmk b/make/common/NON_CORE_PKGS.gmk index cb3887a9d00..5127743ccf5 100644 --- a/make/common/NON_CORE_PKGS.gmk +++ b/make/common/NON_CORE_PKGS.gmk @@ -1,5 +1,5 @@ # -# Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2002, 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 @@ -99,6 +99,8 @@ JDK_PKGS = jdk \ jdk.net \ jdk.management.cmm +JACCESSAPI_PKGS = com.sun.java.accessibility.util + # non-core packages in rt.jar NON_CORE_PKGS = $(DOMAPI_PKGS) \ $(MGMT_PKGS) \ @@ -110,4 +112,5 @@ NON_CORE_PKGS = $(DOMAPI_PKGS) \ $(SMARTCARDIO_PKGS) \ $(SCTPAPI_PKGS) \ $(APPLE_EXT_PKGS) \ - $(JDK_PKGS) + $(JDK_PKGS) \ + $(JACCESSAPI_PKGS) diff --git a/modules.xml b/modules.xml index 389112a748c..a98218f1a2c 100644 --- a/modules.xml +++ b/modules.xml @@ -2,7 +2,7 @@ " + + "" + + "" + + "" + + ""; + + static final String documentTesteExpectedResult = "" + + "[Test:Doc][Test:External Doc]"; +} From 7ec9ed5041a7e86035ae8e438697152716b5dbe2 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Fri, 8 May 2015 10:37:13 +0200 Subject: [PATCH 08/70] 8074859: Turn on warnings as error Reviewed-by: erikj --- common/autoconf/flags.m4 | 19 +++++++++++++- common/autoconf/generated-configure.sh | 34 +++++++++++++++++++++++--- common/autoconf/spec.gmk.in | 6 ++--- make/Init.gmk | 4 ++- make/common/NativeCompilation.gmk | 15 ++++++++++++ 5 files changed, 70 insertions(+), 8 deletions(-) diff --git a/common/autoconf/flags.m4 b/common/autoconf/flags.m4 index 307fcfc0e1b..2c3a0489ef0 100644 --- a/common/autoconf/flags.m4 +++ b/common/autoconf/flags.m4 @@ -231,7 +231,6 @@ AC_DEFUN_ONCE([FLAGS_SETUP_COMPILER_FLAGS_FOR_LIBS], AC_SUBST(C_FLAG_REORDER) AC_SUBST(CXX_FLAG_REORDER) - AC_SUBST(SHARED_LIBRARY_FLAGS) AC_SUBST(SET_EXECUTABLE_ORIGIN) AC_SUBST(SET_SHARED_LIBRARY_ORIGIN) AC_SUBST(SET_SHARED_LIBRARY_NAME) @@ -900,6 +899,24 @@ AC_DEFUN_ONCE([FLAGS_SETUP_COMPILER_FLAGS_MISC], [COMPILER_SUPPORTS_TARGET_BITS_FLAG=false]) AC_SUBST(COMPILER_SUPPORTS_TARGET_BITS_FLAG) + AC_ARG_ENABLE([warnings-as-errors], [AS_HELP_STRING([--disable-warnings-as-errors], + [do not consider native warnings to be an error @<:@enabled@:>@])]) + + AC_MSG_CHECKING([if native warnings are errors]) + if test "x$enable_warnings_as_errors" = "xyes"; then + AC_MSG_RESULT([yes (explicitely set)]) + WARNINGS_AS_ERRORS=true + elif test "x$enable_warnings_as_errors" = "xno"; then + AC_MSG_RESULT([no]) + WARNINGS_AS_ERRORS=false + elif test "x$enable_warnings_as_errors" = "x"; then + AC_MSG_RESULT([yes (default)]) + WARNINGS_AS_ERRORS=true + else + AC_MSG_ERROR([--enable-warnings-as-errors accepts no argument]) + fi + AC_SUBST(WARNINGS_AS_ERRORS) + case "${TOOLCHAIN_TYPE}" in microsoft) DISABLE_WARNING_PREFIX="-wd" diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index dbe3f079f9a..429db34cc93 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -684,6 +684,7 @@ ZIP_DEBUGINFO_FILES ENABLE_DEBUG_SYMBOLS CFLAGS_WARNINGS_ARE_ERRORS DISABLE_WARNING_PREFIX +WARNINGS_AS_ERRORS COMPILER_SUPPORTS_TARGET_BITS_FLAG ZERO_ARCHFLAG LDFLAGS_TESTEXE_SUFFIX @@ -727,7 +728,6 @@ SET_SHARED_LIBRARY_MAPFILE SET_SHARED_LIBRARY_NAME SET_SHARED_LIBRARY_ORIGIN SET_EXECUTABLE_ORIGIN -SHARED_LIBRARY_FLAGS CXX_FLAG_REORDER C_FLAG_REORDER SYSROOT_LDFLAGS @@ -1086,6 +1086,7 @@ with_jtreg with_extra_cflags with_extra_cxxflags with_extra_ldflags +enable_warnings_as_errors enable_debug_symbols enable_zip_debug_info enable_native_coverage @@ -1852,6 +1853,9 @@ Optional Features: --enable-rmiconnector-iiop enable the JMX RMIConnector iiop transport [disabled] + --disable-warnings-as-errors + do not consider native warnings to be an error + [enabled] --disable-debug-symbols disable generation of debug symbols [enabled] --disable-zip-debug-info disable zipping of debug-info files [enabled] @@ -4359,7 +4363,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1430918902 +DATE_WHEN_GENERATED=1431074105 ############################################################################### # @@ -41761,7 +41765,6 @@ $as_echo "$ac_cv_c_bigendian" >&6; } - if test "x$OPENJDK_TARGET_OS" = xsolaris; then CFLAGS_JDK="${CFLAGS_JDK} -D__solaris__" CXXFLAGS_JDK="${CXXFLAGS_JDK} -D__solaris__" @@ -42471,6 +42474,31 @@ $as_echo "$supports" >&6; } + # Check whether --enable-warnings-as-errors was given. +if test "${enable_warnings_as_errors+set}" = set; then : + enableval=$enable_warnings_as_errors; +fi + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if native warnings are errors" >&5 +$as_echo_n "checking if native warnings are errors... " >&6; } + if test "x$enable_warnings_as_errors" = "xyes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes (explicitely set)" >&5 +$as_echo "yes (explicitely set)" >&6; } + WARNINGS_AS_ERRORS=true + elif test "x$enable_warnings_as_errors" = "xno"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + WARNINGS_AS_ERRORS=false + elif test "x$enable_warnings_as_errors" = "x"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes (default)" >&5 +$as_echo "yes (default)" >&6; } + WARNINGS_AS_ERRORS=true + else + as_fn_error $? "--enable-warnings-as-errors accepts no argument" "$LINENO" 5 + fi + + case "${TOOLCHAIN_TYPE}" in microsoft) DISABLE_WARNING_PREFIX="-wd" diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in index b603ae89cff..ae29731a4ae 100644 --- a/common/autoconf/spec.gmk.in +++ b/common/autoconf/spec.gmk.in @@ -321,6 +321,9 @@ CXX_FLAG_DEPS:=@CXX_FLAG_DEPS@ DISABLE_WARNING_PREFIX := @DISABLE_WARNING_PREFIX@ CFLAGS_WARNINGS_ARE_ERRORS:=@CFLAGS_WARNINGS_ARE_ERRORS@ +# A global flag (true or false) determining if native warnings are considered errors. +WARNINGS_AS_ERRORS := @WARNINGS_AS_ERRORS@ + CFLAGS_CCACHE:=@CFLAGS_CCACHE@ # Tools that potentially need to be cross compilation aware. @@ -394,9 +397,6 @@ STRIP:=@STRIP@ LIPO:=@LIPO@ -# Command to create a shared library -SHARED_LIBRARY_FLAGS:=@SHARED_LIBRARY_FLAGS@ - # Options to linker to specify a mapfile. # (Note absence of := assignment, because we do not want to evaluate the macro body here) SET_SHARED_LIBRARY_MAPFILE=@SET_SHARED_LIBRARY_MAPFILE@ diff --git a/make/Init.gmk b/make/Init.gmk index 431b3a7f7b5..50a91026920 100644 --- a/make/Init.gmk +++ b/make/Init.gmk @@ -267,7 +267,9 @@ else # HAS_SPEC=true ( cd $(TOPDIR) && \ $(BUILD_LOG_WRAPPER) $(MAKE) $(MAKE_ARGS) $(OUTPUT_SYNC_FLAG) \ -j $(JOBS) -f make/Main.gmk $(USER_MAKE_VARS) \ - $(PARALLEL_TARGETS) ) + $(PARALLEL_TARGETS) || \ + ( exitcode=$$? && $(BUILD_LOG_WRAPPER) $(PRINTF) "\nERROR: Build failed for $(TARGET_DESCRIPTION) (exit code $$exitcode) \n" && \ + $(PRINTF) "Hint: If caused by a warning, try configure --disable-warnings-as-errors \n\n" && exit $$exitcode ) ) $(call CleanupSmartJavac) $(call StopGlobalTimer) $(call ReportBuildTimes) diff --git a/make/common/NativeCompilation.gmk b/make/common/NativeCompilation.gmk index 8b9982428cf..171fcb0f15c 100644 --- a/make/common/NativeCompilation.gmk +++ b/make/common/NativeCompilation.gmk @@ -487,6 +487,21 @@ define SetupNativeCompilationBody $1_EXTRA_CXXFLAGS += $$(addprefix $(DISABLE_WARNING_PREFIX), $$($1_DISABLED_WARNINGS_$(TOOLCHAIN_TYPE))) endif + # Check if warnings should be considered errors. + # Pick first binary and toolchain specific, then binary specific, then general setting. + ifeq ($$($1_WARNINGS_AS_ERRORS_$(TOOLCHAIN_TYPE)),) + ifeq ($$($1_WARNINGS_AS_ERRORS),) + $1_WARNINGS_AS_ERRORS_$(TOOLCHAIN_TYPE) := $$(WARNINGS_AS_ERRORS) + else + $1_WARNINGS_AS_ERRORS_$(TOOLCHAIN_TYPE) := $$($1_WARNINGS_AS_ERRORS) + endif + endif + + ifeq ($$($1_WARNINGS_AS_ERRORS_$(TOOLCHAIN_TYPE)), true) + $1_EXTRA_CFLAGS += $(CFLAGS_WARNINGS_ARE_ERRORS) + $1_EXTRA_CXXFLAGS += $(CFLAGS_WARNINGS_ARE_ERRORS) + endif + ifeq (NONE, $$($1_OPTIMIZATION)) $1_EXTRA_CFLAGS += $(C_O_FLAG_NONE) $1_EXTRA_CXXFLAGS += $(CXX_O_FLAG_NONE) From 6ede1d2199db6a3fc21ae04cc4630e9d56959a23 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Mon, 11 May 2015 16:39:31 +0530 Subject: [PATCH 09/70] 8079900: javadoc is missing for jdk.nashorn.api.tree package Reviewed-by: lagergren, erikj --- make/Javadoc.gmk | 2 +- make/common/NON_CORE_PKGS.gmk | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/make/Javadoc.gmk b/make/Javadoc.gmk index 4569ed84272..f439ed013da 100644 --- a/make/Javadoc.gmk +++ b/make/Javadoc.gmk @@ -1141,7 +1141,7 @@ NASHORNAPI_WINDOWTITLE := Nashorn API NASHORNAPI_HEADER := Nashorn API NASHORNAPI_BOTTOM := $(call CommonBottom,$(NASHORNAPI_FIRST_COPYRIGHT_YEAR)) NASHORNAPI_GROUPNAME := Packages -NASHORNAPI_REGEXP := jdk.nashorn.api.scripting.* +NASHORNAPI_REGEXP := jdk.nashorn.api.* # NASHORNAPI_PKGS is located in NON_CORE_PKGS.gmk NASHORNAPI_INDEX_HTML = $(NASHORNAPI_DOCDIR)/index.html diff --git a/make/common/NON_CORE_PKGS.gmk b/make/common/NON_CORE_PKGS.gmk index 5127743ccf5..8d7f1a71efc 100644 --- a/make/common/NON_CORE_PKGS.gmk +++ b/make/common/NON_CORE_PKGS.gmk @@ -82,7 +82,8 @@ TREEAPI_PKGS = com.sun.source.doctree \ com.sun.source.util \ jdk -NASHORNAPI_PKGS = jdk.nashorn.api.scripting +NASHORNAPI_PKGS = jdk.nashorn.api.scripting \ + jdk.nashorn.api.tree SMARTCARDIO_PKGS = javax.smartcardio From 7fb09ab821555173e19dc17d70618eddf63df5b3 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Mon, 11 May 2015 13:45:39 +0200 Subject: [PATCH 10/70] 8079891: Store configure log in $BUILD/configure.log Reviewed-by: erikj --- common/autoconf/basics.m4 | 26 ++++++++++++ common/autoconf/configure | 11 ++--- common/autoconf/configure.ac | 11 ++--- common/autoconf/generated-configure.sh | 56 +++++++++++++++++++------- common/autoconf/help.m4 | 24 ++++++----- 5 files changed, 89 insertions(+), 39 deletions(-) diff --git a/common/autoconf/basics.m4 b/common/autoconf/basics.m4 index f78c2d88279..39313d3ce70 100644 --- a/common/autoconf/basics.m4 +++ b/common/autoconf/basics.m4 @@ -1054,3 +1054,29 @@ AC_DEFUN_ONCE([BASIC_CHECK_BASH_OPTIONS], AC_SUBST(BASH_ARGS) ]) + +# Code to run after AC_OUTPUT +AC_DEFUN_ONCE([BASIC_POST_CONFIG_OUTPUT], +[ + # Try to move config.log (generated by autoconf) to the configure-support directory. + if test -e ./config.log; then + $MV -f ./config.log "$CONFIGURESUPPORT_OUTPUTDIR/config.log" 2> /dev/null + fi + + # Rotate our log file (configure.log) + if test -e "$OUTPUT_ROOT/configure.log.old"; then + $RM -f "$OUTPUT_ROOT/configure.log.old" + fi + if test -e "$OUTPUT_ROOT/configure.log"; then + $MV -f "$OUTPUT_ROOT/configure.log" "$OUTPUT_ROOT/configure.log.old" 2> /dev/null + fi + + # Move configure.log from current directory to the build output root + if test -e ./configure.log; then + echo found it + $MV -f ./configure.log "$OUTPUT_ROOT/configure.log" 2> /dev/null + fi + + # Make the compare script executable + $CHMOD +x $OUTPUT_ROOT/compare.sh +]) diff --git a/common/autoconf/configure b/common/autoconf/configure index e786ff81916..4ac6fa1730b 100644 --- a/common/autoconf/configure +++ b/common/autoconf/configure @@ -255,13 +255,10 @@ if test "x$conf_debug_configure" != x; then set -x fi -if test "x$conf_debug_configure" = xtrue; then - # Turn on logging, but don't turn on twice when called recursive - conf_debug_logfile=./debug-configure.log - (exec 3>&1 ; (. $conf_script_to_run "${conf_processed_arguments[@]}" 2>&1 1>&3 ) | tee -a $conf_debug_logfile 1>&2 ; exec 3>&-) | tee -a $conf_debug_logfile -else - ( . $conf_script_to_run "${conf_processed_arguments[@]}" ) -fi +# Now transfer control to the script generated by autoconf. This is where the +# main work is done. +conf_logfile=./configure.log +(exec 3>&1 ; (. $conf_script_to_run "${conf_processed_arguments[@]}" 2>&1 1>&3 ) | tee -a $conf_logfile 1>&2 ; exec 3>&-) | tee -a $conf_logfile conf_result_code=$? ### diff --git a/common/autoconf/configure.ac b/common/autoconf/configure.ac index 560f4525b6a..ceaee324bea 100644 --- a/common/autoconf/configure.ac +++ b/common/autoconf/configure.ac @@ -265,15 +265,10 @@ CONFIG_STATUS="$CONFIGURESUPPORT_OUTPUTDIR/config.status" # Create the actual output files. Now the main work of configure is done. AC_OUTPUT + +# After AC_OUTPUT, we need to do final work CUSTOM_CONFIG_OUTPUT_GENERATED_HOOK - -# Try to move the config.log file to the output directory. -if test -e ./config.log; then - $MV -f ./config.log "$CONFIGURESUPPORT_OUTPUTDIR/config.log" 2> /dev/null -fi - -# Make the compare script executable -$CHMOD +x $OUTPUT_ROOT/compare.sh +BASIC_POST_CONFIG_OUTPUT # Finally output some useful information to the user HELP_PRINT_SUMMARY_AND_WARNINGS diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index 429db34cc93..4551cf55470 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -3500,6 +3500,9 @@ ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. # Check for support for specific options in bash +# Code to run after AC_OUTPUT + + # # Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved. # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. @@ -4363,7 +4366,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1431074105 +DATE_WHEN_GENERATED=1431344623 ############################################################################### # @@ -54207,14 +54210,31 @@ $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} fi +# After AC_OUTPUT, we need to do final work -# Try to move the config.log file to the output directory. -if test -e ./config.log; then - $MV -f ./config.log "$CONFIGURESUPPORT_OUTPUTDIR/config.log" 2> /dev/null -fi -# Make the compare script executable -$CHMOD +x $OUTPUT_ROOT/compare.sh + # Try to move config.log (generated by autoconf) to the configure-support directory. + if test -e ./config.log; then + $MV -f ./config.log "$CONFIGURESUPPORT_OUTPUTDIR/config.log" 2> /dev/null + fi + + # Rotate our log file (configure.log) + if test -e "$OUTPUT_ROOT/configure.log.old"; then + $RM -f "$OUTPUT_ROOT/configure.log.old" + fi + if test -e "$OUTPUT_ROOT/configure.log"; then + $MV -f "$OUTPUT_ROOT/configure.log" "$OUTPUT_ROOT/configure.log.old" 2> /dev/null + fi + + # Move configure.log from current directory to the build output root + if test -e ./configure.log; then + echo found it + $MV -f ./configure.log "$OUTPUT_ROOT/configure.log" 2> /dev/null + fi + + # Make the compare script executable + $CHMOD +x $OUTPUT_ROOT/compare.sh + # Finally output some useful information to the user @@ -54308,14 +54328,20 @@ $CHMOD +x $OUTPUT_ROOT/compare.sh -if test -e "$OUTPUT_ROOT/config.log"; then - $GREP '^configure:.*: WARNING:' "$OUTPUT_ROOT/config.log" > /dev/null 2>&1 - if test $? -eq 0; then - printf "The following warnings were produced. Repeated here for convenience:\n" - # We must quote sed expression (using []) to stop m4 from eating the []. - $GREP '^configure:.*: WARNING:' "$OUTPUT_ROOT/config.log" | $SED -e 's/^configure:[0-9]*: //' - printf "\n" + # Locate config.log. + if test -e "$CONFIGURESUPPORT_OUTPUTDIR/config.log"; then + CONFIG_LOG_PATH="$CONFIGURESUPPORT_OUTPUTDIR" + elif test -e "./config.log"; then + CONFIG_LOG_PATH="." fi -fi + if test -e "$CONFIG_LOG_PATH/config.log"; then + $GREP '^configure:.*: WARNING:' "$CONFIG_LOG_PATH/config.log" > /dev/null 2>&1 + if test $? -eq 0; then + printf "The following warnings were produced. Repeated here for convenience:\n" + # We must quote sed expression (using []) to stop m4 from eating the []. + $GREP '^configure:.*: WARNING:' "$CONFIG_LOG_PATH/config.log" | $SED -e 's/^configure:[0-9]*: //' + printf "\n" + fi + fi diff --git a/common/autoconf/help.m4 b/common/autoconf/help.m4 index 61f608389d5..3bdaf49852f 100644 --- a/common/autoconf/help.m4 +++ b/common/autoconf/help.m4 @@ -212,7 +212,7 @@ AC_DEFUN_ONCE([HELP_PRINT_SUMMARY_AND_WARNINGS], if test "x$TOOLCHAIN_VERSION" != "x"; then print_version=" $TOOLCHAIN_VERSION" fi - printf "* Toolchain: $TOOLCHAIN_TYPE ($TOOLCHAIN_DESCRIPTION$print_version)\n" + printf "* Toolchain: $TOOLCHAIN_TYPE ($TOOLCHAIN_DESCRIPTION$print_version)\n" printf "* C Compiler: Version $CC_VERSION_NUMBER (at $CC)\n" printf "* C++ Compiler: Version $CXX_VERSION_NUMBER (at $CXX)\n" @@ -263,14 +263,20 @@ AC_DEFUN_ONCE([HELP_PRINT_SUMMARY_AND_WARNINGS], AC_DEFUN_ONCE([HELP_REPEAT_WARNINGS], [ -if test -e "$OUTPUT_ROOT/config.log"; then - $GREP '^configure:.*: WARNING:' "$OUTPUT_ROOT/config.log" > /dev/null 2>&1 - if test $? -eq 0; then - printf "The following warnings were produced. Repeated here for convenience:\n" - # We must quote sed expression (using []) to stop m4 from eating the []. - $GREP '^configure:.*: WARNING:' "$OUTPUT_ROOT/config.log" | $SED -e [ 's/^configure:[0-9]*: //' ] - printf "\n" + # Locate config.log. + if test -e "$CONFIGURESUPPORT_OUTPUTDIR/config.log"; then + CONFIG_LOG_PATH="$CONFIGURESUPPORT_OUTPUTDIR" + elif test -e "./config.log"; then + CONFIG_LOG_PATH="." fi -fi + if test -e "$CONFIG_LOG_PATH/config.log"; then + $GREP '^configure:.*: WARNING:' "$CONFIG_LOG_PATH/config.log" > /dev/null 2>&1 + if test $? -eq 0; then + printf "The following warnings were produced. Repeated here for convenience:\n" + # We must quote sed expression (using []) to stop m4 from eating the []. + $GREP '^configure:.*: WARNING:' "$CONFIG_LOG_PATH/config.log" | $SED -e [ 's/^configure:[0-9]*: //' ] + printf "\n" + fi + fi ]) From fd0591c1056c0fd3364329bb4195b42a77477388 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Mon, 11 May 2015 22:57:24 +0530 Subject: [PATCH 11/70] 8080042: can't build nashorn.jar from jdk9-dev/nashorn using jdk8 installation as JAVA_HOME Reviewed-by: lagergren, jlaskey --- .../jdk/nashorn/internal/objects/NativeArrayBuffer.java | 5 +++-- .../jdk/nashorn/internal/objects/NativeFloat32Array.java | 2 +- .../jdk/nashorn/internal/objects/NativeFloat64Array.java | 2 +- .../jdk/nashorn/internal/objects/NativeInt16Array.java | 2 +- .../jdk/nashorn/internal/objects/NativeInt32Array.java | 2 +- .../jdk/nashorn/internal/objects/NativeInt8Array.java | 2 +- .../jdk/nashorn/internal/objects/NativeUint16Array.java | 2 +- .../jdk/nashorn/internal/objects/NativeUint32Array.java | 2 +- .../jdk/nashorn/internal/objects/NativeUint8Array.java | 2 +- .../nashorn/internal/objects/NativeUint8ClampedArray.java | 2 +- 10 files changed, 12 insertions(+), 11 deletions(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArrayBuffer.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArrayBuffer.java index 75a99b31da8..2464b844dcf 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArrayBuffer.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArrayBuffer.java @@ -28,6 +28,7 @@ package jdk.nashorn.internal.objects; import static jdk.nashorn.internal.runtime.ECMAErrors.typeError; import java.nio.ByteBuffer; + import jdk.nashorn.internal.objects.annotations.Attribute; import jdk.nashorn.internal.objects.annotations.Constructor; import jdk.nashorn.internal.objects.annotations.Function; @@ -226,10 +227,10 @@ public final class NativeArrayBuffer extends ScriptObject { } ByteBuffer getBuffer(final int offset) { - return nb.duplicate().position(offset); + return (ByteBuffer)nb.duplicate().position(offset); } ByteBuffer getBuffer(final int offset, final int length) { - return getBuffer(offset).limit(length); + return (ByteBuffer)getBuffer(offset).limit(length); } } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeFloat32Array.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeFloat32Array.java index 7d47887de52..b75d50690e2 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeFloat32Array.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeFloat32Array.java @@ -81,7 +81,7 @@ public final class NativeFloat32Array extends ArrayBufferView { private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Float32ArrayData.class, "setElem", void.class, int.class, double.class).methodHandle(); private Float32ArrayData(final FloatBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((FloatBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeFloat64Array.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeFloat64Array.java index 771a8ff73c2..9a2e319ba86 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeFloat64Array.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeFloat64Array.java @@ -81,7 +81,7 @@ public final class NativeFloat64Array extends ArrayBufferView { private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Float64ArrayData.class, "setElem", void.class, int.class, double.class).methodHandle(); private Float64ArrayData(final DoubleBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((DoubleBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt16Array.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt16Array.java index 706a9f154ab..c2eb5556251 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt16Array.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt16Array.java @@ -82,7 +82,7 @@ public final class NativeInt16Array extends ArrayBufferView { private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Int16ArrayData.class, "setElem", void.class, int.class, int.class).methodHandle(); private Int16ArrayData(final ShortBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((ShortBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt32Array.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt32Array.java index a1ac57eb7ee..a266fc519bd 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt32Array.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt32Array.java @@ -81,7 +81,7 @@ public final class NativeInt32Array extends ArrayBufferView { private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Int32ArrayData.class, "setElem", void.class, int.class, int.class).methodHandle(); private Int32ArrayData(final IntBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((IntBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt8Array.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt8Array.java index d709563cf32..be9bacf987c 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt8Array.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeInt8Array.java @@ -80,7 +80,7 @@ public final class NativeInt8Array extends ArrayBufferView { private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Int8ArrayData.class, "setElem", void.class, int.class, int.class).methodHandle(); private Int8ArrayData(final ByteBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((ByteBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint16Array.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint16Array.java index 1b20ee91aed..30dc68140f4 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint16Array.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint16Array.java @@ -81,7 +81,7 @@ public final class NativeUint16Array extends ArrayBufferView { private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Uint16ArrayData.class, "setElem", void.class, int.class, int.class).methodHandle(); private Uint16ArrayData(final CharBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((CharBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint32Array.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint32Array.java index b9f60ddb2e7..85035175696 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint32Array.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint32Array.java @@ -82,7 +82,7 @@ public final class NativeUint32Array extends ArrayBufferView { private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Uint32ArrayData.class, "setElem", void.class, int.class, int.class).methodHandle(); private Uint32ArrayData(final IntBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((IntBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint8Array.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint8Array.java index 54d3c3ed5a9..f5ccce64b6e 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint8Array.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint8Array.java @@ -81,7 +81,7 @@ public final class NativeUint8Array extends ArrayBufferView { private static final MethodHandle SET_ELEM = specialCall(MethodHandles.lookup(), Uint8ArrayData.class, "setElem", void.class, int.class, int.class).methodHandle(); private Uint8ArrayData(final ByteBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((ByteBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java index 25517e799e6..28d72d1701a 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeUint8ClampedArray.java @@ -85,7 +85,7 @@ public final class NativeUint8ClampedArray extends ArrayBufferView { private static final MethodHandle CLAMP_LONG = staticCall(MethodHandles.lookup(), Uint8ClampedArrayData.class, "clampLong", long.class, long.class).methodHandle(); private Uint8ClampedArrayData(final ByteBuffer nb, final int start, final int end) { - super(nb.position(start).limit(end).slice(), end - start); + super(((ByteBuffer)nb.position(start).limit(end)).slice(), end - start); } @Override From 02a2d027b7db903b4ebcd4a7b047d6c2b5a6d7b9 Mon Sep 17 00:00:00 2001 From: Erik Joelsson Date: Tue, 12 May 2015 09:08:03 +0200 Subject: [PATCH 12/70] 8039426: gcc can target wrong instruction set when building JDK native code Reviewed-by: ihse, dholmes --- common/autoconf/flags.m4 | 4 ++++ common/autoconf/generated-configure.sh | 6 +++++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/common/autoconf/flags.m4 b/common/autoconf/flags.m4 index 2c3a0489ef0..279ab861a71 100644 --- a/common/autoconf/flags.m4 +++ b/common/autoconf/flags.m4 @@ -523,6 +523,10 @@ AC_DEFUN_ONCE([FLAGS_SETUP_COMPILER_FLAGS_FOR_JDK], # CXXFLAGS_JDK - C++ Compiler flags # COMMON_CCXXFLAGS_JDK - common to C and C++ if test "x$TOOLCHAIN_TYPE" = xgcc; then + if test "x$OPENJDK_TARGET_CPU" = xx86; then + # Force compatibility with i586 on 32 bit intel platforms. + COMMON_CCXXFLAGS="${COMMON_CCXXFLAGS} -march=i586" + fi COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -Wall -Wextra -Wno-unused -Wno-unused-parameter -Wformat=2 \ -pipe -D_GNU_SOURCE -D_REENTRANT -D_LARGEFILE64_SOURCE" case $OPENJDK_TARGET_CPU_ARCH in diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index 4551cf55470..1c67fc9c413 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -4366,7 +4366,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1431344623 +DATE_WHEN_GENERATED=1431414369 ############################################################################### # @@ -42035,6 +42035,10 @@ fi # CXXFLAGS_JDK - C++ Compiler flags # COMMON_CCXXFLAGS_JDK - common to C and C++ if test "x$TOOLCHAIN_TYPE" = xgcc; then + if test "x$OPENJDK_TARGET_CPU" = xx86; then + # Force compatibility with i586 on 32 bit intel platforms. + COMMON_CCXXFLAGS="${COMMON_CCXXFLAGS} -march=i586" + fi COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -Wall -Wextra -Wno-unused -Wno-unused-parameter -Wformat=2 \ -pipe -D_GNU_SOURCE -D_REENTRANT -D_LARGEFILE64_SOURCE" case $OPENJDK_TARGET_CPU_ARCH in From ee03c0e102e5342b96e64c95a8aa673325a07af7 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Tue, 12 May 2015 12:40:33 +0530 Subject: [PATCH 13/70] 8080090: -d option should dump script source as well Reviewed-by: hannesw, lagergren --- .../jdk/nashorn/internal/runtime/Context.java | 4 ++ .../internal/runtime/ScriptEnvironment.java | 2 +- .../jdk/nashorn/internal/runtime/Source.java | 38 +++++++++++++++++++ .../runtime/resources/Options.properties | 2 +- 4 files changed, 44 insertions(+), 2 deletions(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java index 4e33f9e3bd2..7bc70b71c49 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java @@ -1239,6 +1239,10 @@ public final class Context { } if (storedScript == null) { + if (env._dest_dir != null) { + source.dump(env._dest_dir); + } + functionNode = new Parser(env, source, errMan, strict, getLogger(Parser.class)).parse(); if (errMan.hasErrors()) { diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptEnvironment.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptEnvironment.java index c7fd0190a6a..99cef1201ad 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptEnvironment.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptEnvironment.java @@ -73,7 +73,7 @@ public final class ScriptEnvironment { /** Generate line number table in class files */ public final boolean _debug_lines; - /** Package to which generated class files are added */ + /** Directory in which source files and generated class files are dumped */ public final String _dest_dir; /** Display stack trace upon error, default is false */ diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java index 502063b57db..06b77b9da3e 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Source.java @@ -28,9 +28,11 @@ package jdk.nashorn.internal.runtime; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; +import java.io.FileOutputStream; import java.io.IOError; import java.io.IOException; import java.io.InputStream; +import java.io.PrintWriter; import java.io.Reader; import java.lang.ref.WeakReference; import java.net.MalformedURLException; @@ -44,6 +46,7 @@ import java.nio.file.Path; import java.nio.file.Paths; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; +import java.time.LocalDateTime; import java.util.Arrays; import java.util.Base64; import java.util.Objects; @@ -989,4 +992,39 @@ public final class Source implements Loggable { public DebugLogger getLogger() { return initLogger(Context.getContextTrusted()); } + + private File dumpFile(final String dir) { + final URL u = getURL(); + final StringBuilder buf = new StringBuilder(); + // make it unique by prefixing current date & time + buf.append(LocalDateTime.now().toString()); + buf.append('_'); + if (u != null) { + // make it a safe file name + buf.append(u.toString() + .replace('/', '_') + .replace('\\', '_')); + } else { + buf.append(getName()); + } + + return new File(dir, buf.toString()); + } + + void dump(final String dir) { + final File file = dumpFile(dir); + try (final FileOutputStream fos = new FileOutputStream(file)) { + final PrintWriter pw = new PrintWriter(fos); + pw.print(data.toString()); + pw.flush(); + } catch (final IOException ioExp) { + debug("Skipping source dump for " + + name + + ": " + + ECMAErrors.getMessage( + "io.error.cant.write", + dir.toString() + + " : " + ioExp.toString())); + } + } } diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Options.properties b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Options.properties index 2f32079be58..2dbb14674a5 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Options.properties +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Options.properties @@ -114,7 +114,7 @@ nashorn.option.d = { \ short_name="-d", \ is_undocumented=true, \ params="", \ - desc="specify a destination directory to dump class files.", \ + desc="specify a destination directory to dump source and class files.", \ type=String \ } From 62836eec59455f55cfbf3ba541c4919cd01a68d8 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 12 May 2015 13:24:34 +0200 Subject: [PATCH 14/70] 8080082: configure fails if you create an empty directory and then run configure from it Reviewed-by: dholmes, erikj --- common/autoconf/basics.m4 | 6 +++--- common/autoconf/generated-configure.sh | 8 ++++---- 2 files changed, 7 insertions(+), 7 deletions(-) diff --git a/common/autoconf/basics.m4 b/common/autoconf/basics.m4 index 39313d3ce70..a9d1034eae0 100644 --- a/common/autoconf/basics.m4 +++ b/common/autoconf/basics.m4 @@ -705,9 +705,9 @@ AC_DEFUN_ONCE([BASIC_SETUP_OUTPUT_DIR], # is performed. filtered_files=`$ECHO "$files_present" \ | $SED -e 's/config.log//g' \ - -e 's/confdefs.h//g' \ - -e 's/fixpath.exe//g' \ - -e 's/ //g' \ + -e 's/configure.log//g' \ + -e 's/confdefs.h//g' \ + -e 's/ //g' \ | $TR -d '\n'` if test "x$filtered_files" != x; then AC_MSG_NOTICE([Current directory is $CURDIR.]) diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index 1c67fc9c413..ea324d03415 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -4366,7 +4366,7 @@ VS_SDK_PLATFORM_NAME_2013= #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1431414369 +DATE_WHEN_GENERATED=1431429776 ############################################################################### # @@ -15342,9 +15342,9 @@ $as_echo "in current directory" >&6; } # is performed. filtered_files=`$ECHO "$files_present" \ | $SED -e 's/config.log//g' \ - -e 's/confdefs.h//g' \ - -e 's/fixpath.exe//g' \ - -e 's/ //g' \ + -e 's/configure.log//g' \ + -e 's/confdefs.h//g' \ + -e 's/ //g' \ | $TR -d '\n'` if test "x$filtered_files" != x; then { $as_echo "$as_me:${as_lineno-$LINENO}: Current directory is $CURDIR." >&5 From a65f9f95894e22ce2fd160024ce46f6aaa6c8bd3 Mon Sep 17 00:00:00 2001 From: Ed Nevill Date: Tue, 12 May 2015 13:58:42 +0000 Subject: [PATCH 15/70] 8079203: AARCH64: Need to cater for different partner implementations Parse /proc/cpuinfo to derive implementation specific info Reviewed-by: kvn --- hotspot/src/cpu/aarch64/vm/aarch64.ad | 3 -- .../src/cpu/aarch64/vm/globals_aarch64.hpp | 8 ++-- .../cpu/aarch64/vm/interp_masm_aarch64.cpp | 2 +- .../cpu/aarch64/vm/macroAssembler_aarch64.cpp | 12 +---- .../cpu/aarch64/vm/macroAssembler_aarch64.hpp | 19 +++++--- .../src/cpu/aarch64/vm/vm_version_aarch64.cpp | 45 ++++++++++++++++++- .../src/cpu/aarch64/vm/vm_version_aarch64.hpp | 36 +++++++++++++++ 7 files changed, 98 insertions(+), 27 deletions(-) diff --git a/hotspot/src/cpu/aarch64/vm/aarch64.ad b/hotspot/src/cpu/aarch64/vm/aarch64.ad index 074e498936f..6e41838c786 100644 --- a/hotspot/src/cpu/aarch64/vm/aarch64.ad +++ b/hotspot/src/cpu/aarch64/vm/aarch64.ad @@ -810,9 +810,6 @@ class HandlerImpl { bool unnecessary_volatile(const Node *barrier); bool needs_releasing_store(const Node *store); - // Use barrier instructions rather than load acquire / store - // release. - const bool UseBarriersForVolatile = false; // Use barrier instructions for unsafe volatile gets rather than // trying to identify an exact signature for them const bool UseBarriersForUnsafeVolatileGet = false; diff --git a/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp index c073735a7e0..4c011a2e50b 100644 --- a/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/globals_aarch64.hpp @@ -98,8 +98,8 @@ define_pd_global(intx, InlineSmallCode, 1000); product(bool, NearCpool, true, \ "constant pool is close to instructions") \ \ - notproduct(bool, UseAcqRelForVolatileFields, false, \ - "Use acquire and release insns for volatile fields") \ + product(bool, UseBarriersForVolatile, false, \ + "Use memory barriers to implement volatile accesses") \ \ product(bool, UseCRC32, false, \ "Use CRC32 instructions for CRC32 computation") \ @@ -117,8 +117,8 @@ define_pd_global(intx, InlineSmallCode, 1000); product(bool, NearCpool, true, \ "constant pool is close to instructions") \ \ - notproduct(bool, UseAcqRelForVolatileFields, false, \ - "Use acquire and release insns for volatile fields") \ + product(bool, UseBarriersForVolatile, false, \ + "Use memory barriers to implement volatile accesses") \ product(bool, UseNeon, false, \ "Use Neon for CRC32 computation") \ product(bool, UseCRC32, false, \ diff --git a/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp index fa40f7fa449..90e281d3191 100644 --- a/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/interp_masm_aarch64.cpp @@ -1314,7 +1314,7 @@ void InterpreterMacroAssembler::profile_switch_case(Register index, // case_array_offset_in_bytes() movw(reg2, in_bytes(MultiBranchData::per_case_size())); movw(rscratch1, in_bytes(MultiBranchData::case_array_offset())); - maddw(index, index, reg2, rscratch1); + Assembler::maddw(index, index, reg2, rscratch1); // Update the case count increment_mdp_data_at(mdp, diff --git a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp index bf307e55932..cdd5de4d23a 100644 --- a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.cpp @@ -1625,7 +1625,7 @@ int MacroAssembler::corrected_idivl(Register result, Register ra, Register rb, sdivw(result, ra, rb); } else { sdivw(scratch, ra, rb); - msubw(result, scratch, rb, ra); + Assembler::msubw(result, scratch, rb, ra); } return idivl_offset; @@ -1655,7 +1655,7 @@ int MacroAssembler::corrected_idivq(Register result, Register ra, Register rb, sdiv(result, ra, rb); } else { sdiv(scratch, ra, rb); - msub(result, scratch, rb, ra); + Assembler::msub(result, scratch, rb, ra); } return idivq_offset; @@ -3787,14 +3787,6 @@ void MacroAssembler::adrp(Register reg1, const Address &dest, unsigned long &byt } } - bool MacroAssembler::use_acq_rel_for_volatile_fields() { -#ifdef PRODUCT - return false; -#else - return UseAcqRelForVolatileFields; -#endif - } - void MacroAssembler::build_frame(int framesize) { if (framesize == 0) { // Is this even possible? diff --git a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp index 21f89fa17c4..9378440d849 100644 --- a/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/macroAssembler_aarch64.hpp @@ -405,6 +405,18 @@ class MacroAssembler: public Assembler { umaddl(Rd, Rn, Rm, zr); } +#define WRAP(INSN) \ + void INSN(Register Rd, Register Rn, Register Rm, Register Ra) { \ + if ((VM_Version::cpu_cpuFeatures() & VM_Version::CPU_A53MAC) && Ra != zr) \ + nop(); \ + Assembler::INSN(Rd, Rn, Rm, Ra); \ + } + + WRAP(madd) WRAP(msub) WRAP(maddw) WRAP(msubw) + WRAP(smaddl) WRAP(smsubl) WRAP(umaddl) WRAP(umsubl) +#undef WRAP + + // macro assembly operations needed for aarch64 // first two private routines for loading 32 bit or 64 bit constants @@ -1094,9 +1106,6 @@ public: address read_polling_page(Register r, address page, relocInfo::relocType rtype); address read_polling_page(Register r, relocInfo::relocType rtype); - // Used by aarch64.ad to control code generation - static bool use_acq_rel_for_volatile_fields(); - // CRC32 code for java.util.zip.CRC32::updateBytes() instrinsic. void update_byte_crc32(Register crc, Register val, Register table); void update_word_crc32(Register crc, Register v, Register tmp, @@ -1150,10 +1159,6 @@ private: int offset, int size); }; -// Used by aarch64.ad to control code generation -#define treat_as_volatile(MEM_NODE) \ - (MacroAssembler::use_acq_rel_for_volatile_fields() ? (MEM_NODE)->is_volatile() : false) - #ifdef ASSERT inline bool AbstractAssembler::pd_check_instruction_mark() { return false; } #endif diff --git a/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp b/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp index eaee6ccd4f1..1b535aa0f9d 100644 --- a/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp +++ b/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.cpp @@ -59,6 +59,9 @@ int VM_Version::_cpu; int VM_Version::_model; +int VM_Version::_model2; +int VM_Version::_variant; +int VM_Version::_revision; int VM_Version::_stepping; int VM_Version::_cpuFeatures; const char* VM_Version::_features_str = ""; @@ -122,13 +125,47 @@ void VM_Version::get_processor_features() { char buf[512]; - strcpy(buf, "simd"); + _cpuFeatures = auxv; + + int cpu_lines = 0; + if (FILE *f = fopen("/proc/cpuinfo", "r")) { + char buf[128], *p; + while (fgets(buf, sizeof (buf), f) != NULL) { + if (p = strchr(buf, ':')) { + long v = strtol(p+1, NULL, 0); + if (strncmp(buf, "CPU implementer", sizeof "CPU implementer" - 1) == 0) { + _cpu = v; + cpu_lines++; + } else if (strncmp(buf, "CPU variant", sizeof "CPU variant" - 1) == 0) { + _variant = v; + } else if (strncmp(buf, "CPU part", sizeof "CPU part" - 1) == 0) { + if (_model != v) _model2 = _model; + _model = v; + } else if (strncmp(buf, "CPU revision", sizeof "CPU revision" - 1) == 0) { + _revision = v; + } + } + } + fclose(f); + } + + // Enable vendor specific features + if (_cpu == CPU_CAVIUM && _variant == 0) _cpuFeatures |= CPU_DMB_ATOMICS; + if (_cpu == CPU_ARM && (_model == 0xd03 || _model2 == 0xd03)) _cpuFeatures |= CPU_A53MAC; + // If an olde style /proc/cpuinfo (cpu_lines == 1) then if _model is an A57 (0xd07) + // we assume the worst and assume we could be on a big little system and have + // undisclosed A53 cores which we could be swapped to at any stage + if (_cpu == CPU_ARM && cpu_lines == 1 && _model == 0xd07) _cpuFeatures |= CPU_A53MAC; + + sprintf(buf, "0x%02x:0x%x:0x%03x:%d", _cpu, _variant, _model, _revision); + if (_model2) sprintf(buf+strlen(buf), "(0x%03x)", _model2); + if (auxv & HWCAP_ASIMD) strcat(buf, ", simd"); if (auxv & HWCAP_CRC32) strcat(buf, ", crc"); if (auxv & HWCAP_AES) strcat(buf, ", aes"); if (auxv & HWCAP_SHA1) strcat(buf, ", sha1"); if (auxv & HWCAP_SHA2) strcat(buf, ", sha256"); - _features_str = strdup(buf); + _features_str = os::strdup(buf); if (FLAG_IS_DEFAULT(UseCRC32)) { UseCRC32 = (auxv & HWCAP_CRC32) != 0; @@ -202,6 +239,10 @@ void VM_Version::get_processor_features() { UseMultiplyToLenIntrinsic = true; } + if (FLAG_IS_DEFAULT(UseBarriersForVolatile)) { + UseBarriersForVolatile = (_cpuFeatures & CPU_DMB_ATOMICS) != 0; + } + #ifdef COMPILER2 if (FLAG_IS_DEFAULT(OptoScheduling)) { OptoScheduling = true; diff --git a/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.hpp b/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.hpp index 5482812ecf1..f5dc414b694 100644 --- a/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.hpp +++ b/hotspot/src/cpu/aarch64/vm/vm_version_aarch64.hpp @@ -34,6 +34,9 @@ public: protected: static int _cpu; static int _model; + static int _model2; + static int _variant; + static int _revision; static int _stepping; static int _cpuFeatures; // features returned by the "cpuid" instruction // 0 if this instruction is not available @@ -49,7 +52,40 @@ public: static void assert_is_initialized() { } + enum { + CPU_ARM = 'A', + CPU_BROADCOM = 'B', + CPU_CAVIUM = 'C', + CPU_DEC = 'D', + CPU_INFINEON = 'I', + CPU_MOTOROLA = 'M', + CPU_NVIDIA = 'N', + CPU_AMCC = 'P', + CPU_QUALCOM = 'Q', + CPU_MARVELL = 'V', + CPU_INTEL = 'i', + } cpuFamily; + + enum { + CPU_FP = (1<<0), + CPU_ASIMD = (1<<1), + CPU_EVTSTRM = (1<<2), + CPU_AES = (1<<3), + CPU_PMULL = (1<<4), + CPU_SHA1 = (1<<5), + CPU_SHA2 = (1<<6), + CPU_CRC32 = (1<<7), + CPU_A53MAC = (1 << 30), + CPU_DMB_ATOMICS = (1 << 31), + } cpuFeatureFlags; + static const char* cpu_features() { return _features_str; } + static int cpu_family() { return _cpu; } + static int cpu_model() { return _model; } + static int cpu_model2() { return _model2; } + static int cpu_variant() { return _variant; } + static int cpu_revision() { return _revision; } + static int cpu_cpuFeatures() { return _cpuFeatures; } }; From a33f1ed55d8126d204159495be06ab7488e4498e Mon Sep 17 00:00:00 2001 From: Bhavesh Patel Date: Tue, 12 May 2015 12:02:48 -0700 Subject: [PATCH 16/70] 8065077: MethodTypes are not localized Reviewed-by: ksrini --- .../formats/html/SubWriterHolderWriter.java | 4 +-- .../formats/html/markup/HtmlWriter.java | 24 +++++++++++------ .../toolkit/resources/doclets.properties | 7 +++++ .../internal/toolkit/util/MethodTypes.java | 26 +++++++++---------- 4 files changed, 38 insertions(+), 23 deletions(-) diff --git a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java index 71eaf2dc9aa..7778a1898c2 100644 --- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java +++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/SubWriterHolderWriter.java @@ -119,7 +119,7 @@ public abstract class SubWriterHolderWriter extends HtmlDocletWriter { Content captionSpan; Content span; if (type.isDefaultTab()) { - captionSpan = HtmlTree.SPAN(new StringContent(type.text())); + captionSpan = HtmlTree.SPAN(configuration.getResource(type.resourceKey())); span = HtmlTree.SPAN(type.tabId(), HtmlStyle.activeTableTab, captionSpan); } else { @@ -142,7 +142,7 @@ public abstract class SubWriterHolderWriter extends HtmlDocletWriter { */ public Content getMethodTypeLinks(MethodTypes methodType) { String jsShow = "javascript:show(" + methodType.value() +");"; - HtmlTree link = HtmlTree.A(jsShow, new StringContent(methodType.text())); + HtmlTree link = HtmlTree.A(jsShow, configuration.getResource(methodType.resourceKey())); return link; } diff --git a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java index 8175393c804..34a4cef0bae 100644 --- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java +++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/markup/HtmlWriter.java @@ -465,10 +465,10 @@ public class HtmlWriter { for (Map.Entry entry : typeMap.entrySet()) { vars.append(sep); sep = ","; - vars.append("\""); - vars.append(entry.getKey()); - vars.append("\":"); - vars.append(entry.getValue()); + vars.append("\"") + .append(entry.getKey()) + .append("\":") + .append(entry.getValue()); } vars.append("};").append(DocletConstants.NL); sep = ""; @@ -476,11 +476,19 @@ public class HtmlWriter { for (MethodTypes entry : methodTypes) { vars.append(sep); sep = ","; - vars.append(entry.value()).append(":"); - vars.append("[").append("\"").append(entry.tabId()); - vars.append("\"").append(sep).append("\"").append(entry.text()).append("\"]"); + vars.append(entry.value()) + .append(":") + .append("[") + .append("\"") + .append(entry.tabId()) + .append("\"") + .append(sep) + .append("\"") + .append(configuration.getText(entry.resourceKey())) + .append("\"]"); } - vars.append("};").append(DocletConstants.NL); + vars.append("};") + .append(DocletConstants.NL); addStyles(HtmlStyle.altColor, vars); addStyles(HtmlStyle.rowColor, vars); addStyles(HtmlStyle.tableTab, vars); diff --git a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclets.properties b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclets.properties index cf21120f517..597dd35ebd1 100644 --- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclets.properties +++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/resources/doclets.properties @@ -150,6 +150,13 @@ doclet.constructors=constructors doclet.Constructors=Constructors doclet.methods=methods doclet.Methods=Methods +doclet.All_Methods=All Methods +doclet.Static_Methods=Static Methods +doclet.Instance_Methods=Instance Methods +doclet.Abstract_Methods=Abstract Methods +doclet.Concrete_Methods=Concrete Methods +doclet.Default_Methods=Default Methods +doclet.Deprecated_Methods=Deprecated Methods doclet.annotation_type_optional_members=optional elements doclet.Annotation_Type_Optional_Members=Optional Elements doclet.annotation_type_required_members=required elements diff --git a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/MethodTypes.java b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/MethodTypes.java index 7b31ad81f04..24254350a9e 100644 --- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/MethodTypes.java +++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/internal/toolkit/util/MethodTypes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -31,22 +31,22 @@ package com.sun.tools.doclets.internal.toolkit.util; * @author Bhavesh Patel */ public enum MethodTypes { - ALL(0xffff, "All Methods", "t0", true), - STATIC(0x1, "Static Methods", "t1", false), - INSTANCE(0x2, "Instance Methods", "t2", false), - ABSTRACT(0x4, "Abstract Methods", "t3", false), - CONCRETE(0x8, "Concrete Methods", "t4", false), - DEFAULT(0x10, "Default Methods", "t5", false), - DEPRECATED(0x20, "Deprecated Methods", "t6", false); + ALL(0xffff, "doclet.All_Methods", "t0", true), + STATIC(0x1, "doclet.Static_Methods", "t1", false), + INSTANCE(0x2, "doclet.Instance_Methods", "t2", false), + ABSTRACT(0x4, "doclet.Abstract_Methods", "t3", false), + CONCRETE(0x8, "doclet.Concrete_Methods", "t4", false), + DEFAULT(0x10, "doclet.Default_Methods", "t5", false), + DEPRECATED(0x20, "doclet.Deprecated_Methods", "t6", false); private final int value; - private final String text; + private final String resourceKey; private final String tabId; private final boolean isDefaultTab; - MethodTypes(int v, String t, String id, boolean dt) { + MethodTypes(int v, String k, String id, boolean dt) { this.value = v; - this.text = t; + this.resourceKey = k; this.tabId = id; this.isDefaultTab = dt; } @@ -55,8 +55,8 @@ public enum MethodTypes { return value; } - public String text() { - return text; + public String resourceKey() { + return resourceKey; } public String tabId() { From c8dc03d400f927ddf7916ad2d18729c5e4ff73dd Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 13 May 2015 12:45:14 +0530 Subject: [PATCH 17/70] 8080182: Array.prototype.sort throws IAE on inconsistent comparison Reviewed-by: lagergren, hannesw --- .../nashorn/internal/objects/NativeArray.java | 56 +++++++++++-------- nashorn/test/script/basic/JDK-8080182.js | 46 +++++++++++++++ 2 files changed, 79 insertions(+), 23 deletions(-) create mode 100644 nashorn/test/script/basic/JDK-8080182.js diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArray.java b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArray.java index f9ab01cc70f..9d9790e4cef 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArray.java +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/objects/NativeArray.java @@ -1228,31 +1228,41 @@ public final class NativeArray extends ScriptObject implements OptimisticBuiltin final List list = Arrays.asList(array); final Object cmpThis = cmp == null || cmp.isStrict() ? ScriptRuntime.UNDEFINED : Global.instance(); - Collections.sort(list, new Comparator() { - private final MethodHandle call_cmp = getCALL_CMP(); - @Override - public int compare(final Object x, final Object y) { - if (x == ScriptRuntime.UNDEFINED && y == ScriptRuntime.UNDEFINED) { - return 0; - } else if (x == ScriptRuntime.UNDEFINED) { - return 1; - } else if (y == ScriptRuntime.UNDEFINED) { - return -1; - } - - if (cmp != null) { - try { - return (int)Math.signum((double)call_cmp.invokeExact(cmp, cmpThis, x, y)); - } catch (final RuntimeException | Error e) { - throw e; - } catch (final Throwable t) { - throw new RuntimeException(t); + try { + Collections.sort(list, new Comparator() { + private final MethodHandle call_cmp = getCALL_CMP(); + @Override + public int compare(final Object x, final Object y) { + if (x == ScriptRuntime.UNDEFINED && y == ScriptRuntime.UNDEFINED) { + return 0; + } else if (x == ScriptRuntime.UNDEFINED) { + return 1; + } else if (y == ScriptRuntime.UNDEFINED) { + return -1; } - } - return JSType.toString(x).compareTo(JSType.toString(y)); - } - }); + if (cmp != null) { + try { + return (int)Math.signum((double)call_cmp.invokeExact(cmp, cmpThis, x, y)); + } catch (final RuntimeException | Error e) { + throw e; + } catch (final Throwable t) { + throw new RuntimeException(t); + } + } + + return JSType.toString(x).compareTo(JSType.toString(y)); + } + }); + } catch (final IllegalArgumentException iae) { + // Collections.sort throws IllegalArgumentException when + // Comparison method violates its general contract + + // See ECMA spec 15.4.4.11 Array.prototype.sort (comparefn). + // If "comparefn" is not undefined and is not a consistent + // comparison function for the elements of this array, the + // behaviour of sort is implementation-defined. + } return list.toArray(new Object[array.length]); } diff --git a/nashorn/test/script/basic/JDK-8080182.js b/nashorn/test/script/basic/JDK-8080182.js new file mode 100644 index 00000000000..17637330d0b --- /dev/null +++ b/nashorn/test/script/basic/JDK-8080182.js @@ -0,0 +1,46 @@ +/* + * Copyright (c) 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ + +/** + * JDK-8080182: Array.prototype.sort throws IAE on inconsistent comparison + * + * @test + * @run + */ + +function Random() { + this.toString = function() { + return (Math.random() * 100).toString(); + } +} + +for (var i = 0; i < 100; ++i) { + var arr = []; + + for (var j = 0; j < 64; ++j) { + arr[j] = new Random(); + } + + // no IllegalArgumentException expected! + arr.sort(); +} From 15fffb90d7af3ef665886c0fcc6f777004e91971 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Wed, 13 May 2015 10:17:38 +0200 Subject: [PATCH 18/70] 8046869: Several java/lang/instrument/PremainClass/* tests fail due to timeout Reviewed-by: sla --- .../java/lang/instrument/PremainClass/NoPremainAgentTest.java | 2 +- .../lang/instrument/PremainClass/ZeroArgPremainAgentTest.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/test/java/lang/instrument/PremainClass/NoPremainAgentTest.java b/jdk/test/java/lang/instrument/PremainClass/NoPremainAgentTest.java index 29bf5623352..bd64239320a 100644 --- a/jdk/test/java/lang/instrument/PremainClass/NoPremainAgentTest.java +++ b/jdk/test/java/lang/instrument/PremainClass/NoPremainAgentTest.java @@ -33,7 +33,7 @@ import jdk.testlibrary.Utils; * @modules java.management * @run build jdk.testlibrary.* DummyMain * @run shell ../MakeJAR3.sh NoPremainAgent - * @run main NoPremainAgentTest + * @run main/othervm -XX:-CreateCoredumpOnCrash NoPremainAgentTest */ public class NoPremainAgentTest { // Use a javaagent without the premain() function. diff --git a/jdk/test/java/lang/instrument/PremainClass/ZeroArgPremainAgentTest.java b/jdk/test/java/lang/instrument/PremainClass/ZeroArgPremainAgentTest.java index b879aa10f23..66633ea12d3 100644 --- a/jdk/test/java/lang/instrument/PremainClass/ZeroArgPremainAgentTest.java +++ b/jdk/test/java/lang/instrument/PremainClass/ZeroArgPremainAgentTest.java @@ -33,7 +33,7 @@ import jdk.testlibrary.Utils; * @modules java.management * @run build jdk.testlibrary.* DummyMain * @run shell ../MakeJAR3.sh ZeroArgPremainAgent - * @run main ZeroArgPremainAgentTest + * @run main/othervm -XX:-CreateCoredumpOnCrash ZeroArgPremainAgentTest */ public class ZeroArgPremainAgentTest { // Use a javaagent with a zero argument premain() function. From d7f44658949034f81aa01ab16c107be1a27be0ad Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Wed, 13 May 2015 10:17:49 +0200 Subject: [PATCH 19/70] 8029098: Exclude javax/management/remote/mandatory/notif/ListenerScaleTest.java from running on fastdebug builds Reviewed-by: sla, sjiang --- .../remote/mandatory/notif/ListenerScaleTest.java | 12 +++++++++++- 1 file changed, 11 insertions(+), 1 deletion(-) diff --git a/jdk/test/javax/management/remote/mandatory/notif/ListenerScaleTest.java b/jdk/test/javax/management/remote/mandatory/notif/ListenerScaleTest.java index efebce3b365..0d7080e6b7d 100644 --- a/jdk/test/javax/management/remote/mandatory/notif/ListenerScaleTest.java +++ b/jdk/test/javax/management/remote/mandatory/notif/ListenerScaleTest.java @@ -21,12 +21,16 @@ * questions. */ -/* +/** * @test * @bug 6338874 * @summary Check that notification dispatch is not linear in number of MBeans. * @author Eamonn McManus * @modules java.management + * + * @library /lib/testlibrary + * @run build jdk.testlibrary.* ListenerScaleTest + * @run main ListenerScaleTest */ /* @@ -67,6 +71,8 @@ import javax.management.remote.JMXConnectorServer; import javax.management.remote.JMXConnectorServerFactory; import javax.management.remote.JMXServiceURL; +import jdk.testlibrary.Platform; + public class ListenerScaleTest { private static final int WARMUP_WITH_ONE_MBEAN = 1000; private static final int NOTIFS_TO_TIME = 100; @@ -126,6 +132,10 @@ public class ListenerScaleTest { }; public static void main(String[] args) throws Exception { + if (Platform.isDebugBuild()) { + System.out.println("Running on a debug build. Performance test not applicable. Skipping."); + return; + } MBeanServer mbs = MBeanServerFactory.newMBeanServer(); Sender sender = new Sender(); mbs.registerMBean(sender, testObjectName); From 538f0b4f063f3e85f072223ec2676a48a195dafb Mon Sep 17 00:00:00 2001 From: Michael Haupt Date: Wed, 13 May 2015 15:41:46 +0200 Subject: [PATCH 20/70] 8080286: use path separator setting consistently in Nashorn project properties Replace uses of ":" with platform-independent path separator property Reviewed-by: hannesw, sundar --- nashorn/make/build.xml | 2 +- nashorn/make/project.properties | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/nashorn/make/build.xml b/nashorn/make/build.xml index df478ee1fb5..75d109addb3 100644 --- a/nashorn/make/build.xml +++ b/nashorn/make/build.xml @@ -188,7 +188,7 @@ diff --git a/nashorn/make/project.properties b/nashorn/make/project.properties index ccdead7dc30..35e1af9f146 100644 --- a/nashorn/make/project.properties +++ b/nashorn/make/project.properties @@ -105,8 +105,8 @@ javac.encoding=ascii javac.classpath=\ ${build.classes.dir} javac.test.classpath=\ - ${build.classes.dir}:\ - ${build.test.classes.dir}:\ + ${build.classes.dir}${path.separator}\ + ${build.test.classes.dir}${path.separator}\ ${file.reference.testng.jar} meta.inf.dir=${src.dir}/META-INF @@ -259,8 +259,8 @@ testjfx.run.test.classpath=\ testjfx-test-sys-prop.test.fork.jvm.options=${run.test.jvmargs.main} -Xmx${run.test.xmx} -cp ${testjfx.run.test.classpath} run.test.classpath=\ - ${file.reference.testng.jar}:\ - ${nashorn.internal.tests.jar}:\ + ${file.reference.testng.jar}${path.separator}\ + ${nashorn.internal.tests.jar}${path.separator}\ ${nashorn.api.tests.jar} src.dir=src/jdk.scripting.nashorn/share/classes From 0f400ba879a120210ac1f7a3ba8ac6d6ea9a6833 Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Wed, 13 May 2015 09:38:59 -0500 Subject: [PATCH 21/70] 8067931: Improve error message when with statement is passed a POJO Reviewed-by: lagergren, sundar --- .../jdk/nashorn/internal/runtime/resources/Messages.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties index dfd8f43cfb3..125e29d0f06 100644 --- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties +++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/resources/Messages.properties @@ -121,7 +121,7 @@ type.error.cannot.get.default.string=Cannot get default string value type.error.cannot.get.default.number=Cannot get default number value type.error.cant.apply.with.to.null=Cannot apply "with" to null type.error.cant.apply.with.to.undefined=Cannot apply "with" to undefined -type.error.cant.apply.with.to.non.scriptobject=Cannot apply "with" to non script object +type.error.cant.apply.with.to.non.scriptobject=Cannot apply "with" to non script object. Consider using "with(Object.bindProperties('{'}, nonScriptObject))". type.error.in.with.non.object=Right hand side of "in" cannot be non-Object, found {0} type.error.prototype.not.an.object="prototype" of {0} is not an Object, it is {1} type.error.cant.load.script=Cannot load script from {0} From 68085fd188183da081df6bd6dd3840b51a8f8edd Mon Sep 17 00:00:00 2001 From: Attila Szegedi Date: Wed, 13 May 2015 10:01:37 -0500 Subject: [PATCH 22/70] 8080295: Need to adjust test output for 8067931 Reviewed-by: jlaskey, sundar --- nashorn/test/script/basic/8024180/with_java_object.js.EXPECTED | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/nashorn/test/script/basic/8024180/with_java_object.js.EXPECTED b/nashorn/test/script/basic/8024180/with_java_object.js.EXPECTED index 3f0facfade1..c3922b066e5 100644 --- a/nashorn/test/script/basic/8024180/with_java_object.js.EXPECTED +++ b/nashorn/test/script/basic/8024180/with_java_object.js.EXPECTED @@ -1 +1 @@ -TypeError: Cannot apply "with" to non script object +TypeError: Cannot apply "with" to non script object. Consider using "with(Object.bindProperties({}, nonScriptObject))". From d95bfcad3eefa32a8bcef4c1da00549547a968a0 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Wed, 13 May 2015 15:48:24 -0700 Subject: [PATCH 23/70] 8075771: Enable "missing" doclint check in build of the java.desktop module Reviewed-by: ihse --- make/CompileJavaModules.gmk | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/make/CompileJavaModules.gmk b/make/CompileJavaModules.gmk index 96872e5028f..4f7e46e5871 100644 --- a/make/CompileJavaModules.gmk +++ b/make/CompileJavaModules.gmk @@ -89,7 +89,7 @@ java.datatransfer_COPY := flavormap.properties ################################################################################ -java.desktop_ADD_JAVAC_FLAGS := -Xdoclint:all/protected,-missing,-reference '-Xdoclint/package:java.*,javax.*' +java.desktop_ADD_JAVAC_FLAGS := -Xdoclint:all/protected,-reference '-Xdoclint/package:java.*,javax.*' java.desktop_COPY := .gif .png .wav .txt .xml .css .pf java.desktop_CLEAN := iio-plugin.properties cursors.properties From 3e2a1f00e54b94ee9ed515881dd772334fb230c5 Mon Sep 17 00:00:00 2001 From: Jaroslav Bachorik Date: Thu, 14 May 2015 11:41:11 +0200 Subject: [PATCH 24/70] 8078143: java/lang/management/ThreadMXBean/AllThreadIds.java fails intermittently Reviewed-by: dholmes, martin --- .../management/ThreadMXBean/AllThreadIds.java | 220 +++++++++++++----- 1 file changed, 160 insertions(+), 60 deletions(-) diff --git a/jdk/test/java/lang/management/ThreadMXBean/AllThreadIds.java b/jdk/test/java/lang/management/ThreadMXBean/AllThreadIds.java index 3ecacae2569..9de573c3851 100644 --- a/jdk/test/java/lang/management/ThreadMXBean/AllThreadIds.java +++ b/jdk/test/java/lang/management/ThreadMXBean/AllThreadIds.java @@ -32,9 +32,30 @@ */ import java.lang.management.*; +import java.time.Instant; import java.util.concurrent.Phaser; +import java.util.function.Supplier; public class AllThreadIds { + /** + * A supplier wrapper for the delayed format printing. + * The supplied value will have to be formatted as $s + * @param The wrapped type + */ + private static final class ArgWrapper { + private final Supplier val; + + public ArgWrapper(Supplier val) { + this.val = val; + } + + @Override + public String toString() { + T resolved = val.get(); + return resolved != null ? resolved.toString() : null; + } + } + final static int DAEMON_THREADS = 20; final static int USER_THREADS = 5; final static int ALL_THREADS = DAEMON_THREADS + USER_THREADS; @@ -47,15 +68,10 @@ public class AllThreadIds { private static long prevTotalThreadCount = 0; private static int prevLiveThreadCount = 0; private static int prevPeakThreadCount = 0; - private static long curTotalThreadCount = 0; - private static int curLiveThreadCount = 0; - private static int curPeakThreadCount = 0; private static final Phaser startupCheck = new Phaser(ALL_THREADS + 1); private static void printThreadList() { - if (!trace) return; - long[] list = mbean.getAllThreadIds(); for (int i = 1; i <= list.length; i++) { System.out.println(i + ": Thread id = " + list[i-1]); @@ -68,59 +84,13 @@ public class AllThreadIds { } } - private static void fail(String msg) { - trace = true; - printThreadList(); - throw new RuntimeException(msg); - } - - private static void checkThreadCount(int numNewThreads, - int numTerminatedThreads) - throws Exception { - prevTotalThreadCount = curTotalThreadCount; - prevLiveThreadCount = curLiveThreadCount; - prevPeakThreadCount = curPeakThreadCount; - curTotalThreadCount = mbean.getTotalStartedThreadCount(); - curLiveThreadCount = mbean.getThreadCount(); - curPeakThreadCount = mbean.getPeakThreadCount(); - - if ((curLiveThreadCount - prevLiveThreadCount) != - (numNewThreads - numTerminatedThreads)) { - fail("Unexpected number of live threads: " + - " Prev live = " + prevLiveThreadCount + - " Current live = " + curLiveThreadCount + - " Threads added = " + numNewThreads + - " Threads terminated = " + numTerminatedThreads); - } - if (curPeakThreadCount - prevPeakThreadCount != numNewThreads) { - fail("Unexpected number of peak threads: " + - " Prev peak = " + prevPeakThreadCount + - " Current peak = " + curPeakThreadCount + - " Threads added = " + numNewThreads); - } - if (curTotalThreadCount - prevTotalThreadCount != numNewThreads) { - fail("Unexpected number of total threads: " + - " Prev Total = " + prevTotalThreadCount + - " Current Total = " + curTotalThreadCount + - " Threads added = " + numNewThreads); - } - long[] list = mbean.getAllThreadIds(); - if (list.length != curLiveThreadCount) { - fail("Array length returned by " + - "getAllThreadIds() = " + list.length + - " not matched count = " + curLiveThreadCount); - } - } - - public static void main(String args[]) throws Exception { - if (args.length > 0 && args[0].equals("trace")) { - trace = true; - } - - curTotalThreadCount = mbean.getTotalStartedThreadCount(); - curLiveThreadCount = mbean.getThreadCount(); - curPeakThreadCount = mbean.getPeakThreadCount(); + private static void checkInitialState() throws Exception { + updateCounters(); checkThreadCount(0, 0); + } + + private static void checkAllThreadsAlive() throws Exception { + updateCounters(); // Start all threads and wait to be sure they all are alive for (int i = 0; i < ALL_THREADS; i++) { @@ -133,8 +103,9 @@ public class AllThreadIds { startupCheck.arriveAndAwaitAdvance(); checkThreadCount(ALL_THREADS, 0); - printThreadList(); - + if (trace) { + printThreadList(); + } // Check mbean now. All threads must appear in getAllThreadIds() list long[] list = mbean.getAllThreadIds(); @@ -165,6 +136,10 @@ public class AllThreadIds { if (trace) { System.out.println(); } + } + + private static void checkDaemonThreadsDead() throws Exception { + updateCounters(); // Stop daemon threads, wait to be sure they all are dead, and check // that they disappeared from getAllThreadIds() list @@ -179,7 +154,7 @@ public class AllThreadIds { checkThreadCount(0, DAEMON_THREADS); // Check mbean now - list = mbean.getAllThreadIds(); + long[] list = mbean.getAllThreadIds(); for (int i = 0; i < ALL_THREADS; i++) { long expectedId = allThreads[i].getId(); @@ -208,6 +183,10 @@ public class AllThreadIds { } } } + } + + private static void checkAllThreadsDead() throws Exception { + updateCounters(); // Stop all threads and wait to be sure they all are dead for (int i = DAEMON_THREADS; i < ALL_THREADS; i++) { @@ -219,6 +198,127 @@ public class AllThreadIds { // and check the thread count checkThreadCount(0, ALL_THREADS - DAEMON_THREADS); + } + + private static void checkThreadCount(int numNewThreads, + int numTerminatedThreads) + throws Exception { + + checkLiveThreads(numNewThreads, numTerminatedThreads); + checkPeakThreads(numNewThreads); + checkTotalThreads(numNewThreads); + checkThreadIds(); + } + + private static void checkLiveThreads(int numNewThreads, + int numTerminatedThreads) + throws InterruptedException { + int diff = numNewThreads - numTerminatedThreads; + + waitTillEquals( + diff + prevLiveThreadCount, + ()->(long)mbean.getThreadCount(), + "Unexpected number of live threads: " + + " Prev live = %1$d Current live = ${provided} Threads added = %2$d" + + " Threads terminated = %3$d", + ()->prevLiveThreadCount, + ()->numNewThreads, + ()->numTerminatedThreads + ); + } + + private static void checkPeakThreads(int numNewThreads) + throws InterruptedException { + + waitTillEquals(numNewThreads + prevPeakThreadCount, + ()->(long)mbean.getPeakThreadCount(), + "Unexpected number of peak threads: " + + " Prev peak = %1$d Current peak = ${provided} Threads added = %2$d", + ()->prevPeakThreadCount, + ()->numNewThreads + ); + } + + private static void checkTotalThreads(int numNewThreads) + throws InterruptedException { + + waitTillEquals(numNewThreads + prevTotalThreadCount, + ()->mbean.getTotalStartedThreadCount(), + "Unexpected number of total threads: " + + " Prev Total = %1$d Current Total = ${provided} Threads added = %2$d", + ()->prevTotalThreadCount, + ()->numNewThreads + ); + } + + private static void checkThreadIds() throws InterruptedException { + long[] list = mbean.getAllThreadIds(); + + waitTillEquals( + list.length, + ()->(long)mbean.getThreadCount(), + "Array length returned by " + + "getAllThreadIds() = %1$d not matched count = ${provided}", + ()->list.length + ); + } + + /** + * Waits till the expectedVal equals to the retrievedVal. + * It will report a status message on the first occasion of the value mismatch + * and then, subsequently, when the retrievedVal value changes. + * @param expectedVal The value to wait for + * @param retrievedVal The supplier of the value to check against the expectedVal + * @param msgFormat The formatted message to be printed in case of mismatch + * @param msgArgs The parameters to the formatted message + * @throws InterruptedException + */ + private static void waitTillEquals(long expectedVal, Supplier retrievedVal, + String msgFormat, Supplier ... msgArgs) + throws InterruptedException { + Object[] args = null; + + long countPrev = -1; + while (true) { + Long count = retrievedVal.get(); + if (count == expectedVal) break; + if (countPrev == -1 || countPrev != count) { + if (args == null) { + args = new Object[msgArgs.length]; + for(int i=0; i < msgArgs.length; i++) { + args[i] = new ArgWrapper<>((Supplier)msgArgs[i]); + } + } + System.err.format("TS: %s\n", Instant.now()); + System.err.format( + msgFormat + .replace("${provided}", String.valueOf(count)) + .replace("$d", "$s"), + args + ).flush(); + printThreadList(); + System.err.println("\nRetrying ...\n"); + } + countPrev = count; + Thread.sleep(1); + } + } + + private static void updateCounters() { + prevTotalThreadCount = mbean.getTotalStartedThreadCount(); + prevLiveThreadCount = mbean.getThreadCount(); + prevPeakThreadCount = mbean.getPeakThreadCount(); + } + + public static void main(String args[]) throws Exception { + if (args.length > 0 && args[0].equals("trace")) { + trace = true; + } + + checkInitialState(); + checkAllThreadsAlive(); + checkDaemonThreadsDead(); + checkAllThreadsDead(); if (testFailed) throw new RuntimeException("TEST FAILED."); From 6c916eb061327e187032797b7a5e7dd0d87b6a41 Mon Sep 17 00:00:00 2001 From: Joe Wang Date: Thu, 14 May 2015 09:38:53 -0700 Subject: [PATCH 25/70] 8080344: Incorrect GPL header causes RE script to miss swap to commercial header for licensee source bundle Reviewed-by: lancea --- .../sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java | 2 +- .../org/apache/xerces/internal/utils/XMLSecurityManager.java | 2 +- .../xerces/internal/utils/XMLSecurityPropertyManager.java | 2 +- .../share/classes/javax/xml/xpath/XPathEvaluationResult.java | 2 +- jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathNodes.java | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java index e8e723aa918..1a428e3e18e 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLLimitAnalyzer.java @@ -1,7 +1,7 @@ /* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java index 1b2911ff117..c8114e9830e 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLSecurityManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLSecurityPropertyManager.java b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLSecurityPropertyManager.java index 4286f043e50..43326e13157 100644 --- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLSecurityPropertyManager.java +++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/utils/XMLSecurityPropertyManager.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2013 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathEvaluationResult.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathEvaluationResult.java index 84d1f399e08..ebc21027d43 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathEvaluationResult.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathEvaluationResult.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 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 diff --git a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathNodes.java b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathNodes.java index 6f1db4e0d45..62778077f7e 100644 --- a/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathNodes.java +++ b/jaxp/src/java.xml/share/classes/javax/xml/xpath/XPathNodes.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2015 Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 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 From b1f245e3a3f6868fad4ef3bb08b3dd5454a1a7ac Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 14 May 2015 12:38:06 -0700 Subject: [PATCH 26/70] Added tag jdk9-b64 for changeset 16659396d71f --- .hgtags-top-repo | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags-top-repo b/.hgtags-top-repo index fe0f260a5a3..bfa2e564382 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -306,3 +306,4 @@ f25ee9f62427a9ba27418e5531a89754791a305b jdk9-b57 ea38728b4f4bdd8fd0d7a89b18069f521cf05013 jdk9-b61 105d045a69174d870b69bfe471b3f2d05a9f8ecc jdk9-b62 0b32ed628fa60e4ab99fb0b5866d648e16231f17 jdk9-b63 +82cf9aab9a83e41c8194ba01af9666afdb856cbe jdk9-b64 From 32c20c0bd690463d3a0475829a3038644c33ee59 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 14 May 2015 12:38:07 -0700 Subject: [PATCH 27/70] Added tag jdk9-b64 for changeset febd2373771c --- hotspot/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/hotspot/.hgtags b/hotspot/.hgtags index c52975971ac..def3dbf7702 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -466,3 +466,4 @@ ee878f3d6732856f7725c590312bfbe2ffa52cc7 jdk9-b58 715d2da5801c410746e92f08066d53bde1496286 jdk9-b61 1eab877142cce6ca06e556e2ad0af688f993f00b jdk9-b62 2ac9b6b36689b50d1562627067c92d51781b5684 jdk9-b63 +bf92b8db249cdfa5651ef954b6c0743a7e0ea4cd jdk9-b64 From bf1a7f53399d449d4cba62ec0f14d317dfa65057 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 14 May 2015 12:38:07 -0700 Subject: [PATCH 28/70] Added tag jdk9-b64 for changeset 1dbddb2a1971 --- corba/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/corba/.hgtags b/corba/.hgtags index ee596409fdf..8acbf91c3b9 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -306,3 +306,4 @@ caa330b275f39282793466529f6864766b31d9fd jdk9-b60 d690f489ca0bb95a6157d996da2fa72bcbcf02ea jdk9-b61 d27f7e0a7aca129969de23e9934408a31b4abf4c jdk9-b62 0acac6937de7a0868f8c6f88b7d036d780abeee6 jdk9-b63 +0a5e5a7c3539e8bde73d9fe55750e49a49cb8dac jdk9-b64 From 1bf9b9d315d4cecbd438de10755d8eeb2f1fca79 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 14 May 2015 12:38:09 -0700 Subject: [PATCH 29/70] Added tag jdk9-b64 for changeset 8a60622f2e7a --- jaxp/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxp/.hgtags b/jaxp/.hgtags index e747bb369a5..54df16471cc 100644 --- a/jaxp/.hgtags +++ b/jaxp/.hgtags @@ -306,3 +306,4 @@ c12db18748dacfccd6581ead29228c2cb6e51b34 jdk9-b60 f4a4a54620370f077c2e830a5561c8cfa811712b jdk9-b61 3bcf83c1bbc1b7663e930d72c133a9bd86c7618d jdk9-b62 4a8f895f0317dcc90479cb7cc97014312e69edf7 jdk9-b63 +6f91749b5aaef1a171ec2254163233438d1071d1 jdk9-b64 From 9143fb4ddbac231e56f0cc716982ac473e87f5a4 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 14 May 2015 12:38:10 -0700 Subject: [PATCH 30/70] Added tag jdk9-b64 for changeset 3901aa49fb70 --- jaxws/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jaxws/.hgtags b/jaxws/.hgtags index cc8261c4098..ab14d761a9e 100644 --- a/jaxws/.hgtags +++ b/jaxws/.hgtags @@ -309,3 +309,4 @@ f31835b59035377a220efc5a248b90f090ee1689 jdk9-b60 77f44848c44c003205490bf5ab88035233b65418 jdk9-b61 cd0cf72b2cbf4adb778a02505fb065bb2292688c jdk9-b62 b5c22d09b1c91dd49b006f38d8ba9c4397517ccc jdk9-b63 +df100399ed27d0eaa57c137ca99819a0fee66178 jdk9-b64 From 0e4d07e88b4db7d760974a27eaf6b14993752a71 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 14 May 2015 12:38:11 -0700 Subject: [PATCH 31/70] Added tag jdk9-b64 for changeset aca452591e50 --- jdk/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/jdk/.hgtags b/jdk/.hgtags index e75d6a7b447..4b90d3155bb 100644 --- a/jdk/.hgtags +++ b/jdk/.hgtags @@ -306,3 +306,4 @@ c76339e86ea7da5d9ac7856f3fae9ef73eef04a2 jdk9-b57 da84dcac1b0b12c5b836b05ac75ecbfadee0cd32 jdk9-b61 49118e68fbd4cc0044e718c47db681946d5efd69 jdk9-b62 fd3281c400347088b36aeb16273aa679d53a81a4 jdk9-b63 +7de8d036ad0980d988d1b9b4b4e6be555d9fbf98 jdk9-b64 From 84e174a9f620f9824235de14562307582422f2f6 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 14 May 2015 12:38:14 -0700 Subject: [PATCH 32/70] Added tag jdk9-b64 for changeset 47d774ef3c19 --- langtools/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/langtools/.hgtags b/langtools/.hgtags index d042ba10475..e1c571e2875 100644 --- a/langtools/.hgtags +++ b/langtools/.hgtags @@ -306,3 +306,4 @@ a598534d277e170a0bbf177bd54d9d179245532b jdk9-b59 0eb91327db5a840779cc5c35b9b858d6ef7959d1 jdk9-b61 40058141a4ec04a3d4cacdb693ad188a5ddf48ed jdk9-b62 a28b7f42dae9bd59513beaa5a2d6eb563dc09e08 jdk9-b63 +809d66512998789b620d08c335d7c31211a0cf29 jdk9-b64 From 24c78d855ccd49d2f22989a73fc89b02eab84346 Mon Sep 17 00:00:00 2001 From: David Katleman Date: Thu, 14 May 2015 12:38:15 -0700 Subject: [PATCH 33/70] Added tag jdk9-b64 for changeset 8b01824b0cbb --- nashorn/.hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/nashorn/.hgtags b/nashorn/.hgtags index 393af476e09..beee726ca26 100644 --- a/nashorn/.hgtags +++ b/nashorn/.hgtags @@ -297,3 +297,4 @@ c55ce3738888b6c7596780b7b2ad1aa0f9ebccd7 jdk9-b60 89937bee80bd28826de8cf60aa63a21edab63f79 jdk9-b61 1b5604bc81a6161b1c3c9dd654cd1399474ae9ee jdk9-b62 bc8e67bec2f92772c4a67e20e66a4f216207f0af jdk9-b63 +00df6e4fc75a83bdd958f9ef86d80e008c9ba967 jdk9-b64 From 9af3729cc73685c879e6c52fa6394963dfd75e4e Mon Sep 17 00:00:00 2001 From: Stuart Marks Date: Thu, 14 May 2015 13:52:05 -0700 Subject: [PATCH 34/70] 8078463: TEST_BUG: optimize java/util/Map/Collisions.java Reviewed-by: martin, chegar, dfuchs --- jdk/test/java/util/Map/Collisions.java | 124 +++++++++++++++---------- 1 file changed, 75 insertions(+), 49 deletions(-) diff --git a/jdk/test/java/util/Map/Collisions.java b/jdk/test/java/util/Map/Collisions.java index 1ec98fe7c8d..43ae17cd6a1 100644 --- a/jdk/test/java/util/Map/Collisions.java +++ b/jdk/test/java/util/Map/Collisions.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 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 @@ -198,138 +198,125 @@ public class Collisions { } private static void testInsertion(Map map, String keys_desc, T[] keys) { - check("map empty", (map.size() == 0) && map.isEmpty()); + check(map.size() == 0 && map.isEmpty(), "map empty"); for (int i = 0; i < keys.length; i++) { - check(String.format("insertion: map expected size m%d != i%d", map.size(), i), - map.size() == i); - check(String.format("insertion: put(%s[%d])", keys_desc, i), null == map.put(keys[i], keys[i])); - check(String.format("insertion: containsKey(%s[%d])", keys_desc, i), map.containsKey(keys[i])); - check(String.format("insertion: containsValue(%s[%d])", keys_desc, i), map.containsValue(keys[i])); + check(map.size() == i, "insertion: map expected size m%d != i%d", map.size(), i); + check(null == map.put(keys[i], keys[i]), "insertion: put(%s[%d])", keys_desc, i); + check(map.containsKey(keys[i]), "insertion: containsKey(%s[%d])", keys_desc, i); + check(map.containsValue(keys[i]), "insertion: containsValue(%s[%d])", keys_desc, i); } - check(String.format("map expected size m%d != k%d", map.size(), keys.length), - map.size() == keys.length); + check(map.size() == keys.length, "map expected size m%d != k%d", map.size(), keys.length); } private static void testIntegerIteration(Map map, HashableInteger[] keys) { - check(String.format("map expected size m%d != k%d", map.size(), keys.length), - map.size() == keys.length); + check(map.size() == keys.length, "map expected size m%d != k%d", map.size(), keys.length); BitSet all = new BitSet(keys.length); for (Map.Entry each : map.entrySet()) { - check("Iteration: key already seen", !all.get(each.getKey().value)); + check(!all.get(each.getKey().value), "Iteration: key already seen"); all.set(each.getKey().value); } all.flip(0, keys.length); - check("Iteration: some keys not visited", all.isEmpty()); + check(all.isEmpty(), "Iteration: some keys not visited"); for (HashableInteger each : map.keySet()) { - check("Iteration: key already seen", !all.get(each.value)); + check(!all.get(each.value), "Iteration: key already seen"); all.set(each.value); } all.flip(0, keys.length); - check("Iteration: some keys not visited", all.isEmpty()); + check(all.isEmpty(), "Iteration: some keys not visited"); int count = 0; for (HashableInteger each : map.values()) { count++; } - check(String.format("Iteration: value count matches size m%d != c%d", map.size(), count), - map.size() == count); + check(map.size() == count, "Iteration: value count matches size m%d != c%d", map.size(), count); } private static void testStringIteration(Map map, String[] keys) { - check(String.format("map expected size m%d != k%d", map.size(), keys.length), - map.size() == keys.length); + check(map.size() == keys.length, "map expected size m%d != k%d", map.size(), keys.length); BitSet all = new BitSet(keys.length); for (Map.Entry each : map.entrySet()) { String key = each.getKey(); boolean longKey = key.length() > 5; int index = key.hashCode() + (longKey ? keys.length / 2 : 0); - check("key already seen", !all.get(index)); + check(!all.get(index), "key already seen"); all.set(index); } all.flip(0, keys.length); - check("some keys not visited", all.isEmpty()); + check(all.isEmpty(), "some keys not visited"); for (String each : map.keySet()) { boolean longKey = each.length() > 5; int index = each.hashCode() + (longKey ? keys.length / 2 : 0); - check("key already seen", !all.get(index)); + check(!all.get(index), "key already seen"); all.set(index); } all.flip(0, keys.length); - check("some keys not visited", all.isEmpty()); + check(all.isEmpty(), "some keys not visited"); int count = 0; for (String each : map.values()) { count++; } - check(String.format("value count matches size m%d != k%d", map.size(), keys.length), - map.size() == keys.length); + check(map.size() == keys.length, "value count matches size m%d != k%d", map.size(), keys.length); } private static void testContainsKey(Map map, String keys_desc, T[] keys) { for (int i = 0; i < keys.length; i++) { T each = keys[i]; - check("containsKey: " + keys_desc + "[" + i + "]" + each, map.containsKey(each)); + check(map.containsKey(each), "containsKey: %s[%d]%s", keys_desc, i, each); } } private static void testRemove(Map map, String keys_desc, T[] keys) { - check(String.format("remove: map expected size m%d != k%d", map.size(), keys.length), - map.size() == keys.length); + check(map.size() == keys.length, "remove: map expected size m%d != k%d", map.size(), keys.length); for (int i = 0; i < keys.length; i++) { T each = keys[i]; - check("remove: " + keys_desc + "[" + i + "]" + each, null != map.remove(each)); + check(null != map.remove(each), "remove: %s[%d]%s", keys_desc, i, each); } - check(String.format("remove: map empty. size=%d", map.size()), - (map.size() == 0) && map.isEmpty()); + check(map.size() == 0 && map.isEmpty(), "remove: map empty. size=%d", map.size()); } private static void testKeysIteratorRemove(Map map, String keys_desc, T[] keys) { - check(String.format("remove: map expected size m%d != k%d", map.size(), keys.length), - map.size() == keys.length); + check(map.size() == keys.length, "remove: map expected size m%d != k%d", map.size(), keys.length); Iterator each = map.keySet().iterator(); while (each.hasNext()) { T t = each.next(); each.remove(); - check("not removed: " + each, !map.containsKey(t) ); + check(!map.containsKey(t), "not removed: %s", each); } - check(String.format("remove: map empty. size=%d", map.size()), - (map.size() == 0) && map.isEmpty()); + check(map.size() == 0 && map.isEmpty(), "remove: map empty. size=%d", map.size()); } private static void testValuesIteratorRemove(Map map, String keys_desc, T[] keys) { - check(String.format("remove: map expected size m%d != k%d", map.size(), keys.length), - map.size() == keys.length); + check(map.size() == keys.length, "remove: map expected size m%d != k%d", map.size(), keys.length); Iterator each = map.values().iterator(); while (each.hasNext()) { T t = each.next(); each.remove(); - check("not removed: " + each, !map.containsValue(t) ); + check(!map.containsValue(t), "not removed: %s", each); } - check(String.format("remove: map empty. size=%d", map.size()), - (map.size() == 0) && map.isEmpty()); + check(map.size() == 0 && map.isEmpty(), "remove: map empty. size=%d", map.size()); } private static void testEntriesIteratorRemove(Map map, String keys_desc, T[] keys) { - check(String.format("remove: map expected size m%d != k%d", map.size(), keys.length), - map.size() == keys.length); + check(map.size() == keys.length, "remove: map expected size m%d != k%d", map.size(), keys.length); Iterator> each = map.entrySet().iterator(); while (each.hasNext()) { @@ -337,13 +324,12 @@ public class Collisions { T key = t.getKey(); T value = t.getValue(); each.remove(); - check("not removed: " + each, (map instanceof IdentityHashMap) || !map.entrySet().contains(t) ); - check("not removed: " + each, !map.containsKey(key) ); - check("not removed: " + each, !map.containsValue(value)); + check((map instanceof IdentityHashMap) || !map.entrySet().contains(t), "not removed: %s", each); + check(!map.containsKey(key), "not removed: %s", each); + check(!map.containsValue(value), "not removed: %s", each); } - check(String.format("remove: map empty. size=%d", map.size()), - (map.size() == 0) && map.isEmpty()); + check(map.size() == 0 && map.isEmpty(), "remove: map empty. size=%d", map.size()); } //--------------------- Infrastructure --------------------------- @@ -391,7 +377,7 @@ public class Collisions { } } - static void check(String desc, boolean cond) { + static void check(boolean cond, String desc) { if (cond) { pass(); } else { @@ -399,6 +385,46 @@ public class Collisions { } } + static void check(boolean cond, String fmt, int i) { + if (cond) { + pass(); + } else { + fail(String.format(fmt, i)); + } + } + + static void check(boolean cond, String fmt, Object o) { + if (cond) { + pass(); + } else { + fail(String.format(fmt, o)); + } + } + + static void check(boolean cond, String fmt, int i1, int i2) { + if (cond) { + pass(); + } else { + fail(String.format(fmt, i1, i2)); + } + } + + static void check(boolean cond, String fmt, String s, int i) { + if (cond) { + pass(); + } else { + fail(String.format(fmt, s, i)); + } + } + + static void check(boolean cond, String fmt, String s, int i, Object o) { + if (cond) { + pass(); + } else { + fail(String.format(fmt, s, i, o)); + } + } + static void equal(Object x, Object y) { if (Objects.equals(x, y)) { pass(); From d296137c200b683e1033c163bd541b30702c2d41 Mon Sep 17 00:00:00 2001 From: Valerie Peng Date: Fri, 15 May 2015 01:14:25 +0000 Subject: [PATCH 35/70] 8038084: CertStore needs a way to add new CertStore types Removed internal helper classes and reflection usage for LDAP CertStore. Reviewed-by: mullan --- .../cert/LDAPCertStoreParameters.java | 9 +- .../security/cert/URICertStoreParameters.java | 149 +++ .../sun/security/provider/SunEntries.java | 8 - .../provider/certpath/CertStoreHelper.java | 148 --- .../provider/certpath/RevocationChecker.java | 33 +- .../provider/certpath/URICertStore.java | 37 +- .../certpath/ssl/SSLServerCertStore.java | 4 +- .../ssl/SSLServerCertStoreHelper.java | 76 -- .../sun/security/tools/keytool/Main.java | 23 +- .../share/conf/security/java.security | 1 + .../provider/certpath/ldap/JdkLDAP.java | 90 ++ .../provider/certpath/ldap/LDAPCertStore.java | 1030 ++--------------- .../certpath/ldap/LDAPCertStoreHelper.java | 81 -- .../certpath/ldap/LDAPCertStoreImpl.java | 772 ++++++++++++ .../CheckSecurityProvider.java | 3 +- .../URICertStoreParameters/TestBasic.java | 71 ++ 16 files changed, 1244 insertions(+), 1291 deletions(-) create mode 100644 jdk/src/java.base/share/classes/java/security/cert/URICertStoreParameters.java delete mode 100644 jdk/src/java.base/share/classes/sun/security/provider/certpath/CertStoreHelper.java delete mode 100644 jdk/src/java.base/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStoreHelper.java create mode 100644 jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/JdkLDAP.java delete mode 100644 jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreHelper.java create mode 100644 jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreImpl.java create mode 100644 jdk/test/java/security/cert/URICertStoreParameters/TestBasic.java diff --git a/jdk/src/java.base/share/classes/java/security/cert/LDAPCertStoreParameters.java b/jdk/src/java.base/share/classes/java/security/cert/LDAPCertStoreParameters.java index 2daef343d50..4ff590d3519 100644 --- a/jdk/src/java.base/share/classes/java/security/cert/LDAPCertStoreParameters.java +++ b/jdk/src/java.base/share/classes/java/security/cert/LDAPCertStoreParameters.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -30,7 +30,12 @@ package java.security.cert; *

* This class is used to provide necessary configuration parameters (server * name and port number) to implementations of the LDAP {@code CertStore} - * algorithm. + * algorithm. However, if you are retrieving certificates or CRLs from + * an ldap URI as specified by RFC 5280, use the + * {@link java.security.cert.URICertStoreParameters URICertStoreParameters} + * instead as the URI may contain additional information such as the + * distinguished name that will help the LDAP CertStore find the specific + * certificates and CRLs. *

* Concurrent Access *

diff --git a/jdk/src/java.base/share/classes/java/security/cert/URICertStoreParameters.java b/jdk/src/java.base/share/classes/java/security/cert/URICertStoreParameters.java new file mode 100644 index 00000000000..3b6418e4dc2 --- /dev/null +++ b/jdk/src/java.base/share/classes/java/security/cert/URICertStoreParameters.java @@ -0,0 +1,149 @@ +/* + * Copyright (c) 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. + */ + +package java.security.cert; + +import java.net.URI; + +/** + * Parameters used as input for {@code CertStore} algorithms which use + * information contained in a URI to retrieve certificates and CRLs. + *

+ * This class is used to provide necessary configuration parameters + * through a URI as defined in RFC 5280 to implementations of + * {@code CertStore} algorithms. + *

+ * Concurrent Access + *

+ * Unless otherwise specified, the methods defined in this class are not + * thread-safe. Multiple threads that need to access a single + * object concurrently should synchronize amongst themselves and + * provide the necessary locking. Multiple threads each manipulating + * separate objects need not synchronize. + * + * @since 1.9 + * @see CertStore + * @see java.net.URI + */ +public final class URICertStoreParameters implements CertStoreParameters { + + /** + * The uri, cannot be null + */ + private final URI uri; + + /* + * Hash code for this parameters. + */ + private int myhash = -1; + + /** + * Creates an instance of {@code URICertStoreParameters} with the + * specified URI. + * + * @param uri the URI which contains configuration information. + * @throws NullPointerException if {@code uri} is null + */ + public URICertStoreParameters(URI uri) { + if (uri == null) { + throw new NullPointerException(); + } + this.uri = uri; + } + + /** + * Returns the URI used to construct this + * {@code URICertStoreParameters} object. + * + * @return the URI. + */ + public URI getURI() { + return uri; + } + + /** + * Returns a copy of this object. Changes to the copy will not affect + * the original and vice versa. + * + * @return the copy + */ + @Override + public URICertStoreParameters clone() { + try { + return new URICertStoreParameters(uri); + } catch (NullPointerException e) { + /* Cannot happen */ + throw new InternalError(e.toString(), e); + } + } + + /** + * Returns a hash code value for this parameters object. + * The hash code is generated using the URI supplied at construction. + * + * @return a hash code value for this parameters. + */ + @Override + public int hashCode() { + if (myhash == -1) { + myhash = uri.hashCode()*7; + } + return myhash; + } + + /** + * Compares the specified object with this parameters object for equality. + * Two URICertStoreParameters are considered equal if the URIs used + * to construct them are equal. + * + * @param p the object to test for equality with this parameters. + * + * @return true if the specified object is equal to this parameters object. + */ + @Override + public boolean equals(Object p) { + if (p == null || (!(p instanceof URICertStoreParameters))) { + return false; + } + + if (p == this) { + return true; + } + + URICertStoreParameters other = (URICertStoreParameters)p; + return uri.equals(other.getURI()); + } + + /** + * Returns a formatted string describing the parameters + * including the URI used to construct this object. + * + * @return a formatted string describing the parameters + */ + @Override + public String toString() { + return "URICertStoreParameters: " + uri.toString(); + } +} diff --git a/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java b/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java index c496910f7c9..65e76f80be0 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/SunEntries.java @@ -67,10 +67,6 @@ import java.security.*; * in RFC 5280. The ValidationAlgorithm attribute notes the * specification that this provider implements. * - * - LDAP is the CertStore type for LDAP repositories. The - * LDAPSchema attribute notes the specification defining the - * schema that this provider uses to find certificates and CRLs. - * * - JavaPolicy is the default file-based Policy type. * * - JavaLoginConfig is the default file-based LoginModule Configuration type. @@ -275,9 +271,6 @@ final class SunEntries { /* * CertStores */ - map.put("CertStore.LDAP", - "sun.security.provider.certpath.ldap.LDAPCertStore"); - map.put("CertStore.LDAP LDAPSchema", "RFC2587"); map.put("CertStore.Collection", "sun.security.provider.certpath.CollectionCertStore"); map.put("CertStore.com.sun.security.IndexedCollection", @@ -310,7 +303,6 @@ final class SunEntries { map.put("KeyStore.JKS ImplementedIn", "Software"); map.put("CertPathValidator.PKIX ImplementedIn", "Software"); map.put("CertPathBuilder.PKIX ImplementedIn", "Software"); - map.put("CertStore.LDAP ImplementedIn", "Software"); map.put("CertStore.Collection ImplementedIn", "Software"); map.put("CertStore.com.sun.security.IndexedCollection ImplementedIn", "Software"); diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/CertStoreHelper.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/CertStoreHelper.java deleted file mode 100644 index b8b562ece05..00000000000 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/CertStoreHelper.java +++ /dev/null @@ -1,148 +0,0 @@ -/* - * Copyright (c) 2009, 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. - */ - -package sun.security.provider.certpath; - -import java.net.URI; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; -import java.security.AccessController; -import java.security.NoSuchAlgorithmException; -import java.security.InvalidAlgorithmParameterException; -import java.security.PrivilegedActionException; -import java.security.PrivilegedExceptionAction; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.X509CertSelector; -import java.security.cert.X509CRLSelector; -import javax.security.auth.x500.X500Principal; -import java.io.IOException; - -import sun.security.util.Cache; - -/** - * Helper used by URICertStore and others when delegating to another CertStore - * to fetch certs and CRLs. - */ - -public abstract class CertStoreHelper { - - private static final int NUM_TYPES = 2; - private final static Map classMap = new HashMap<>(NUM_TYPES); - static { - classMap.put( - "LDAP", - "sun.security.provider.certpath.ldap.LDAPCertStoreHelper"); - classMap.put( - "SSLServer", - "sun.security.provider.certpath.ssl.SSLServerCertStoreHelper"); - }; - private static Cache cache - = Cache.newSoftMemoryCache(NUM_TYPES); - - public static CertStoreHelper getInstance(final String type) - throws NoSuchAlgorithmException - { - CertStoreHelper helper = cache.get(type); - if (helper != null) { - return helper; - } - final String cl = classMap.get(type); - if (cl == null) { - throw new NoSuchAlgorithmException(type + " not available"); - } - try { - helper = AccessController.doPrivileged( - new PrivilegedExceptionAction() { - public CertStoreHelper run() throws ClassNotFoundException { - try { - Class c = Class.forName(cl, true, null); - CertStoreHelper csh - = (CertStoreHelper)c.newInstance(); - cache.put(type, csh); - return csh; - } catch (InstantiationException | - IllegalAccessException e) { - throw new AssertionError(e); - } - } - }); - return helper; - } catch (PrivilegedActionException e) { - throw new NoSuchAlgorithmException(type + " not available", - e.getException()); - } - } - - static boolean isCausedByNetworkIssue(String type, CertStoreException cse) { - switch (type) { - case "LDAP": - case "SSLServer": - try { - CertStoreHelper csh = CertStoreHelper.getInstance(type); - return csh.isCausedByNetworkIssue(cse); - } catch (NoSuchAlgorithmException nsae) { - return false; - } - case "URI": - Throwable t = cse.getCause(); - return (t != null && t instanceof IOException); - default: - // we don't know about any other remote CertStore types - return false; - } - } - - /** - * Returns a CertStore using the given URI as parameters. - */ - public abstract CertStore getCertStore(URI uri) - throws NoSuchAlgorithmException, InvalidAlgorithmParameterException; - - /** - * Wraps an existing X509CertSelector when needing to avoid DN matching - * issues. - */ - public abstract X509CertSelector wrap(X509CertSelector selector, - X500Principal certSubject, - String dn) - throws IOException; - - /** - * Wraps an existing X509CRLSelector when needing to avoid DN matching - * issues. - */ - public abstract X509CRLSelector wrap(X509CRLSelector selector, - Collection certIssuers, - String dn) - throws IOException; - - /** - * Returns true if the cause of the CertStoreException is a network - * related issue. - */ - public abstract boolean isCausedByNetworkIssue(CertStoreException e); -} diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java index c1c06ca2585..5294569c634 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java @@ -466,6 +466,34 @@ class RevocationChecker extends PKIXRevocationChecker { stackedCerts, params.trustAnchors()); } + static boolean isCausedByNetworkIssue(String type, CertStoreException cse) { + boolean result; + Throwable t = cse.getCause(); + + switch (type) { + case "LDAP": + if (t != null) { + // These two exception classes are inside java.naming module + String cn = t.getClass().getName(); + result = (cn.equals("javax.naming.ServiceUnavailableException") || + cn.equals("javax.naming.CommunicationException")); + } else { + result = false; + } + break; + case "SSLServer": + result = (t != null && t instanceof IOException); + break; + case "URI": + result = (t != null && t instanceof IOException); + break; + default: + // we don't know about any other remote CertStore types + return false; + } + return result; + } + private void checkCRLs(X509Certificate cert, PublicKey prevKey, X509Certificate prevCert, boolean signFlag, boolean allowSeparateKey, @@ -510,7 +538,7 @@ class RevocationChecker extends PKIXRevocationChecker { "CertStoreException: " + e.getMessage()); } if (networkFailureException == null && - CertStoreHelper.isCausedByNetworkIssue(store.getType(),e)) { + isCausedByNetworkIssue(store.getType(),e)) { // save this exception, we may need to throw it later networkFailureException = new CertPathValidatorException( "Unable to determine revocation status due to " + @@ -557,8 +585,7 @@ class RevocationChecker extends PKIXRevocationChecker { } catch (CertStoreException e) { if (e instanceof CertStoreTypeException) { CertStoreTypeException cste = (CertStoreTypeException)e; - if (CertStoreHelper.isCausedByNetworkIssue(cste.getType(), - e)) { + if (isCausedByNetworkIssue(cste.getType(), e)) { throw new CertPathValidatorException( "Unable to determine revocation status due to " + "network error", e, null, -1, diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java index 6ac455fd67e..0477b2b751e 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/URICertStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2006, 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 @@ -42,6 +42,7 @@ import java.security.cert.CertStoreParameters; import java.security.cert.CertStoreSpi; import java.security.cert.CRLException; import java.security.cert.CRLSelector; +import java.security.cert.URICertStoreParameters; import java.security.cert.X509Certificate; import java.security.cert.X509CertSelector; import java.security.cert.X509CRL; @@ -118,9 +119,7 @@ class URICertStore extends CertStoreSpi { // true if URI is ldap private boolean ldap = false; - private CertStoreHelper ldapHelper; private CertStore ldapCertStore; - private String ldapPath; // Default maximum connect timeout in milliseconds (15 seconds) // allowed when downloading CRLs @@ -165,13 +164,8 @@ class URICertStore extends CertStoreSpi { // if ldap URI, use an LDAPCertStore to fetch certs and CRLs if (uri.getScheme().toLowerCase(Locale.ENGLISH).equals("ldap")) { ldap = true; - ldapHelper = CertStoreHelper.getInstance("LDAP"); - ldapCertStore = ldapHelper.getCertStore(uri); - ldapPath = uri.getPath(); - // strip off leading '/' - if (ldapPath.charAt(0) == '/') { - ldapPath = ldapPath.substring(1); - } + URICertStoreParameters lparams = new URICertStoreParameters(uri); + ldapCertStore = CertStore.getInstance("LDAP", lparams); } try { factory = CertificateFactory.getInstance("X.509"); @@ -246,20 +240,10 @@ class URICertStore extends CertStoreSpi { public synchronized Collection engineGetCertificates (CertSelector selector) throws CertStoreException { - // if ldap URI we wrap the CertSelector in an LDAPCertSelector to - // avoid LDAP DN matching issues (see LDAPCertSelector for more info) if (ldap) { - X509CertSelector xsel = (X509CertSelector) selector; - try { - xsel = ldapHelper.wrap(xsel, xsel.getSubject(), ldapPath); - } catch (IOException ioe) { - throw new CertStoreException(ioe); - } - // Fetch the certificates via LDAP. LDAPCertStore has its own // caching mechanism, see the class description for more info. - // Safe cast since xsel is an X509 certificate selector. return (Collection) - ldapCertStore.getCertificates(xsel); + ldapCertStore.getCertificates(selector); } // Return the Certificates for this entry. It returns the cached value @@ -356,20 +340,11 @@ class URICertStore extends CertStoreSpi { public synchronized Collection engineGetCRLs(CRLSelector selector) throws CertStoreException { - // if ldap URI we wrap the CRLSelector in an LDAPCRLSelector to - // avoid LDAP DN matching issues (see LDAPCRLSelector for more info) if (ldap) { - X509CRLSelector xsel = (X509CRLSelector) selector; - try { - xsel = ldapHelper.wrap(xsel, null, ldapPath); - } catch (IOException ioe) { - throw new CertStoreException(ioe); - } // Fetch the CRLs via LDAP. LDAPCertStore has its own // caching mechanism, see the class description for more info. - // Safe cast since xsel is an X509 certificate selector. try { - return (Collection) ldapCertStore.getCRLs(xsel); + return (Collection) ldapCertStore.getCRLs(selector); } catch (CertStoreException cse) { throw new PKIX.CertStoreTypeException("LDAP", cse); } diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStore.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStore.java index f2a999f51de..f0dfc9225e9 100644 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStore.java +++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2011, 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 @@ -153,7 +153,7 @@ public final class SSLServerCertStore extends CertStoreSpi { throw new UnsupportedOperationException(); } - static CertStore getInstance(URI uri) + public static CertStore getInstance(URI uri) throws InvalidAlgorithmParameterException { return new CS(new SSLServerCertStore(uri), null, "SSLServer", null); diff --git a/jdk/src/java.base/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStoreHelper.java b/jdk/src/java.base/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStoreHelper.java deleted file mode 100644 index d19b56d9e63..00000000000 --- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/ssl/SSLServerCertStoreHelper.java +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright (c) 2011, 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. - */ - -package sun.security.provider.certpath.ssl; - -import java.io.IOException; -import java.net.URI; -import java.security.NoSuchAlgorithmException; -import java.security.InvalidAlgorithmParameterException; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.X509CertSelector; -import java.security.cert.X509CRLSelector; -import java.util.Collection; -import javax.security.auth.x500.X500Principal; - -import sun.security.provider.certpath.CertStoreHelper; - -/** - * SSL implementation of CertStoreHelper. - */ -public final class SSLServerCertStoreHelper extends CertStoreHelper { - - @Override - public CertStore getCertStore(URI uri) - throws NoSuchAlgorithmException, InvalidAlgorithmParameterException - { - return SSLServerCertStore.getInstance(uri); - } - - @Override - public X509CertSelector wrap(X509CertSelector selector, - X500Principal certSubject, - String ldapDN) - throws IOException - { - throw new UnsupportedOperationException(); - } - - @Override - public X509CRLSelector wrap(X509CRLSelector selector, - Collection certIssuers, - String ldapDN) - throws IOException - { - throw new UnsupportedOperationException(); - } - - @Override - public boolean isCausedByNetworkIssue(CertStoreException e) { - Throwable t = e.getCause(); - return (t != null && t instanceof IOException); - } -} diff --git a/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java b/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java index 37ed4105c9c..f8d6efc6f28 100644 --- a/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java +++ b/jdk/src/java.base/share/classes/sun/security/tools/keytool/Main.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -46,6 +46,9 @@ import java.security.cert.CertStoreException; import java.security.cert.CRL; import java.security.cert.X509Certificate; import java.security.cert.CertificateException; +import java.security.cert.URICertStoreParameters; + + import java.text.Collator; import java.text.MessageFormat; import java.util.*; @@ -69,7 +72,7 @@ import sun.security.util.ObjectIdentifier; import sun.security.pkcs10.PKCS10; import sun.security.pkcs10.PKCS10Attribute; import sun.security.provider.X509Factory; -import sun.security.provider.certpath.CertStoreHelper; +import sun.security.provider.certpath.ssl.SSLServerCertStore; import sun.security.util.Password; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; @@ -2208,14 +2211,10 @@ public final class Main { } } } else { // must be LDAP, and uri is not null - // Lazily load LDAPCertStoreHelper if present - CertStoreHelper helper = CertStoreHelper.getInstance("LDAP"); - String path = uri.getPath(); - if (path.charAt(0) == '/') path = path.substring(1); - CertStore s = helper.getCertStore(uri); - X509CRLSelector sel = - helper.wrap(new X509CRLSelector(), null, path); - return s.getCRLs(sel); + URICertStoreParameters params = + new URICertStoreParameters(uri); + CertStore s = CertStore.getInstance("LDAP", params); + return s.getCRLs(new X509CRLSelector()); } } @@ -2463,9 +2462,7 @@ public final class Main { out.println(rb.getString("Not.a.signed.jar.file")); } } else if (sslserver != null) { - // Lazily load SSLCertStoreHelper if present - CertStoreHelper helper = CertStoreHelper.getInstance("SSLServer"); - CertStore cs = helper.getCertStore(new URI("https://" + sslserver)); + CertStore cs = SSLServerCertStore.getInstance(new URI("https://" + sslserver)); Collection chain; try { chain = cs.getCertificates(null); diff --git a/jdk/src/java.base/share/conf/security/java.security b/jdk/src/java.base/share/conf/security/java.security index bcb073a49ef..be33f832a36 100644 --- a/jdk/src/java.base/share/conf/security/java.security +++ b/jdk/src/java.base/share/conf/security/java.security @@ -78,6 +78,7 @@ security.provider.tbd=sun.security.jgss.SunProvider security.provider.tbd=com.sun.security.sasl.Provider security.provider.tbd=org.jcp.xml.dsig.internal.dom.XMLDSigRI security.provider.tbd=sun.security.smartcardio.SunPCSC +security.provider.tbd=sun.security.provider.certpath.ldap.JdkLDAP #ifdef windows security.provider.tbd=sun.security.mscapi.SunMSCAPI #endif diff --git a/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/JdkLDAP.java b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/JdkLDAP.java new file mode 100644 index 00000000000..873757f81bf --- /dev/null +++ b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/JdkLDAP.java @@ -0,0 +1,90 @@ +/* + * Copyright (c) 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. + */ + +package sun.security.provider.certpath.ldap; + +import java.util.HashMap; +import java.util.List; +import java.security.Provider; +import java.security.NoSuchAlgorithmException; +import java.security.InvalidParameterException; +import java.security.InvalidAlgorithmParameterException; +import java.security.ProviderException; +import java.security.cert.CertStoreParameters; + +/** + * Provider class for the JdkLDAP provider. + * Supports LDAP cert store. + * + * @since 1.9 + */ +public final class JdkLDAP extends Provider { + + private static final long serialVersionUID = -2279741232933606418L; + + private static final class ProviderService extends Provider.Service { + ProviderService(Provider p, String type, String algo, String cn, + List aliases, HashMap attrs) { + super(p, type, algo, cn, aliases, attrs); + } + + @Override + public Object newInstance(Object ctrParamObj) + throws NoSuchAlgorithmException { + String type = getType(); + String algo = getAlgorithm(); + if (type.equals("CertStore") && algo.equals("LDAP")) { + if (ctrParamObj != null && + !(ctrParamObj instanceof CertStoreParameters)) { + throw new InvalidParameterException + ("constructorParameter must be instanceof CertStoreParameters"); + } + try { + return new LDAPCertStore((CertStoreParameters) ctrParamObj); + } catch (Exception ex) { + throw new NoSuchAlgorithmException("Error constructing " + + type + " for " + algo + " using JdkLDAP", ex); + } + } + throw new ProviderException("No impl for " + algo + " " + type); + } + } + + public JdkLDAP() { + super("JdkLDAP", 1.9d, "JdkLDAP Provider (implements LDAP CertStore)"); + + HashMap attrs = new HashMap<>(2); + attrs.put("LDAPSchema", "RFC2587"); + attrs.put("ImplementedIn", "Software"); + + /* + * CertStore + * attrs: LDAPSchema, ImplementedIn + */ + putService(new ProviderService(this, "CertStore", + "LDAP", "sun.security.provider.certpath.ldap.LDAPCertStore", + null, attrs)); + } +} diff --git a/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java index 3a050d6b55e..f8874812a84 100644 --- a/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java +++ b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -25,29 +25,15 @@ package sun.security.provider.certpath.ldap; -import java.io.ByteArrayInputStream; -import java.io.IOException; import java.math.BigInteger; import java.net.URI; import java.util.*; -import javax.naming.Context; -import javax.naming.NamingEnumeration; -import javax.naming.NamingException; -import javax.naming.NameNotFoundException; -import javax.naming.directory.Attribute; -import javax.naming.directory.Attributes; -import javax.naming.directory.BasicAttributes; import java.security.*; import java.security.cert.Certificate; import java.security.cert.*; -import javax.naming.CommunicationException; -import javax.naming.ldap.InitialLdapContext; -import javax.naming.ldap.LdapContext; import javax.security.auth.x500.X500Principal; -import sun.misc.HexDumpEncoder; -import sun.security.provider.certpath.X509CertificatePair; import sun.security.util.Cache; import sun.security.util.Debug; import sun.security.x509.X500Name; @@ -109,480 +95,124 @@ public final class LDAPCertStore extends CertStoreSpi { private final static boolean DEBUG = false; - /** - * LDAP attribute identifiers. - */ - private static final String USER_CERT = "userCertificate;binary"; - private static final String CA_CERT = "cACertificate;binary"; - private static final String CROSS_CERT = "crossCertificatePair;binary"; - private static final String CRL = "certificateRevocationList;binary"; - private static final String ARL = "authorityRevocationList;binary"; - private static final String DELTA_CRL = "deltaRevocationList;binary"; + private String ldapDN; - // Constants for various empty values - private final static String[] STRING0 = new String[0]; + private LDAPCertStoreImpl impl; - private final static byte[][] BB0 = new byte[0][]; - - private final static Attributes EMPTY_ATTRIBUTES = new BasicAttributes(); - - // cache related constants - private final static int DEFAULT_CACHE_SIZE = 750; - private final static int DEFAULT_CACHE_LIFETIME = 30; - - private final static int LIFETIME; - - private final static String PROP_LIFETIME = - "sun.security.certpath.ldap.cache.lifetime"; - - /* - * Internal system property, that when set to "true", disables the - * JNDI application resource files lookup to prevent recursion issues - * when validating signed JARs with LDAP URLs in certificates. - */ - private final static String PROP_DISABLE_APP_RESOURCE_FILES = - "sun.security.certpath.ldap.disable.app.resource.files"; - - static { - String s = AccessController.doPrivileged( - (PrivilegedAction) () -> System.getProperty(PROP_LIFETIME)); - if (s != null) { - LIFETIME = Integer.parseInt(s); // throws NumberFormatException - } else { - LIFETIME = DEFAULT_CACHE_LIFETIME; - } - } - - /** - * The CertificateFactory used to decode certificates from - * their binary stored form. - */ - private CertificateFactory cf; - /** - * The JNDI directory context. - */ - private LdapContext ctx; - - /** - * Flag indicating that communication error occurred. - */ - private boolean communicationError = false; - - /** - * Flag indicating whether we should prefetch CRLs. - */ - private boolean prefetchCRLs = false; - - private final Cache valueCache; - - private int cacheHits = 0; - private int cacheMisses = 0; - private int requests = 0; - - /** - * Creates a CertStore with the specified parameters. - * For this class, the parameters object must be an instance of - * LDAPCertStoreParameters. - * - * @param params the algorithm parameters - * @exception InvalidAlgorithmParameterException if params is not an - * instance of LDAPCertStoreParameters - */ public LDAPCertStore(CertStoreParameters params) - throws InvalidAlgorithmParameterException { + throws InvalidAlgorithmParameterException { super(params); - if (!(params instanceof LDAPCertStoreParameters)) - throw new InvalidAlgorithmParameterException( - "parameters must be LDAPCertStoreParameters"); - LDAPCertStoreParameters lparams = (LDAPCertStoreParameters) params; - - // Create InitialDirContext needed to communicate with the server - createInitialDirContext(lparams.getServerName(), lparams.getPort()); - - // Create CertificateFactory for use later on - try { - cf = CertificateFactory.getInstance("X.509"); - } catch (CertificateException e) { + String serverName; + int port; + String dn = null; + if (params == null) { throw new InvalidAlgorithmParameterException( - "unable to create CertificateFactory for X.509"); + "parameters required for LDAP Certore"); } - if (LIFETIME == 0) { - valueCache = Cache.newNullCache(); - } else if (LIFETIME < 0) { - valueCache = Cache.newSoftMemoryCache(DEFAULT_CACHE_SIZE); + if (params instanceof LDAPCertStoreParameters) { + LDAPCertStoreParameters p = (LDAPCertStoreParameters) params; + serverName = p.getServerName(); + port = p.getPort(); + } else if (params instanceof URICertStoreParameters) { + URICertStoreParameters p = (URICertStoreParameters) params; + URI u = p.getURI(); + if (!u.getScheme().equalsIgnoreCase("ldap")) { + throw new InvalidAlgorithmParameterException( + "Only LDAP URIs are supported for LDAP Certore"); + } + // Use the same default values as in LDAPCertStoreParameters + // if unspecified in URI + serverName = u.getHost(); + if (serverName == null) { + serverName = "localhost"; + } + port = u.getPort(); + if (port == -1) { + port = 389; + } + dn = u.getPath(); + if (dn != null && dn.charAt(0) == '/') { + dn = dn.substring(1); + } } else { - valueCache = Cache.newSoftMemoryCache(DEFAULT_CACHE_SIZE, LIFETIME); + throw new InvalidAlgorithmParameterException( + "parameters must be either LDAPCertStoreParameters or " + + "URICertStoreParameters"); + } + + Key k = new Key(serverName, port); + LDAPCertStoreImpl lci = certStoreCache.get(k); + if (lci == null) { + this.impl = new LDAPCertStoreImpl(serverName, port); + certStoreCache.put(k, impl); + } else { + this.impl = lci; + if (debug != null) { + debug.println("LDAPCertStore.getInstance: cache hit"); + } + } + this.ldapDN = dn; + } + + private static class Key { + volatile int hashCode; + + String serverName; + int port; + + Key(String serverName, int port) { + this.serverName = serverName; + this.port = port; + } + + @Override + public boolean equals(Object obj) { + if (!(obj instanceof Key)) { + return false; + } + Key key = (Key) obj; + return (port == key.port && + serverName.equalsIgnoreCase(key.serverName)); + } + + @Override + public int hashCode() { + if (hashCode == 0) { + int result = 17; + result = 37*result + port; + result = 37*result + + serverName.toLowerCase(Locale.ENGLISH).hashCode(); + hashCode = result; + } + return hashCode; } } /** - * Returns an LDAP CertStore. This method consults a cache of - * CertStores (shared per JVM) using the LDAP server/port as a key. + * Returns an LDAPCertStoreImpl object. This method consults a cache of + * LDAPCertStoreImpl objects (shared per JVM) using the corresponding + * LDAP server name and port info as a key. */ - private static final Cache + private static final Cache certStoreCache = Cache.newSoftMemoryCache(185); - static synchronized CertStore getInstance(LDAPCertStoreParameters params) + + // Exist solely for regression test for ensuring that caching is done + static synchronized LDAPCertStoreImpl getInstance(LDAPCertStoreParameters params) throws NoSuchAlgorithmException, InvalidAlgorithmParameterException { - // if necessary, convert params to SunLDAPCertStoreParameters because - // LDAPCertStoreParameters does not override equals() and hashCode() - if (! (params instanceof SunLDAPCertStoreParameters)) { - params = new SunLDAPCertStoreParameters(params.getServerName(), params.getPort()); - } - CertStore lcs = certStoreCache.get(params); - if (lcs == null) { - lcs = CertStore.getInstance("LDAP", params); - certStoreCache.put(params, lcs); + String serverName = params.getServerName(); + int port = params.getPort(); + Key k = new Key(serverName, port); + LDAPCertStoreImpl lci = certStoreCache.get(k); + if (lci == null) { + lci = new LDAPCertStoreImpl(serverName, port); + certStoreCache.put(k, lci); } else { if (debug != null) { debug.println("LDAPCertStore.getInstance: cache hit"); } } - return lcs; - } - - /** - * Create InitialDirContext. - * - * @param server Server DNS name hosting LDAP service - * @param port Port at which server listens for requests - * @throws InvalidAlgorithmParameterException if creation fails - */ - private void createInitialDirContext(String server, int port) - throws InvalidAlgorithmParameterException { - String url = "ldap://" + server + ":" + port; - Hashtable env = new Hashtable<>(); - env.put(Context.INITIAL_CONTEXT_FACTORY, - "com.sun.jndi.ldap.LdapCtxFactory"); - env.put(Context.PROVIDER_URL, url); - - // If property is set to true, disable application resource file lookup. - boolean disableAppResourceFiles = AccessController.doPrivileged( - (PrivilegedAction) () -> Boolean.getBoolean(PROP_DISABLE_APP_RESOURCE_FILES)); - if (disableAppResourceFiles) { - if (debug != null) { - debug.println("LDAPCertStore disabling app resource files"); - } - env.put("com.sun.naming.disable.app.resource.files", "true"); - } - - try { - ctx = new InitialLdapContext(env, null); - /* - * By default, follow referrals unless application has - * overridden property in an application resource file. - */ - Hashtable currentEnv = ctx.getEnvironment(); - if (currentEnv.get(Context.REFERRAL) == null) { - ctx.addToEnvironment(Context.REFERRAL, "follow"); - } - } catch (NamingException e) { - if (debug != null) { - debug.println("LDAPCertStore.engineInit about to throw " - + "InvalidAlgorithmParameterException"); - e.printStackTrace(); - } - Exception ee = new InvalidAlgorithmParameterException - ("unable to create InitialDirContext using supplied parameters"); - ee.initCause(e); - throw (InvalidAlgorithmParameterException)ee; - } - } - - /** - * Private class encapsulating the actual LDAP operations and cache - * handling. Use: - * - * LDAPRequest request = new LDAPRequest(dn); - * request.addRequestedAttribute(CROSS_CERT); - * request.addRequestedAttribute(CA_CERT); - * byte[][] crossValues = request.getValues(CROSS_CERT); - * byte[][] caValues = request.getValues(CA_CERT); - * - * At most one LDAP request is sent for each instance created. If all - * getValues() calls can be satisfied from the cache, no request - * is sent at all. If a request is sent, all requested attributes - * are always added to the cache irrespective of whether the getValues() - * method is called. - */ - private class LDAPRequest { - - private final String name; - private Map valueMap; - private final List requestedAttributes; - - LDAPRequest(String name) { - this.name = name; - requestedAttributes = new ArrayList<>(5); - } - - String getName() { - return name; - } - - void addRequestedAttribute(String attrId) { - if (valueMap != null) { - throw new IllegalStateException("Request already sent"); - } - requestedAttributes.add(attrId); - } - - /** - * Gets one or more binary values from an attribute. - * - * @param name the location holding the attribute - * @param attrId the attribute identifier - * @return an array of binary values (byte arrays) - * @throws NamingException if a naming exception occurs - */ - byte[][] getValues(String attrId) throws NamingException { - if (DEBUG && ((cacheHits + cacheMisses) % 50 == 0)) { - System.out.println("Cache hits: " + cacheHits + "; misses: " - + cacheMisses); - } - String cacheKey = name + "|" + attrId; - byte[][] values = valueCache.get(cacheKey); - if (values != null) { - cacheHits++; - return values; - } - cacheMisses++; - Map attrs = getValueMap(); - values = attrs.get(attrId); - return values; - } - - /** - * Get a map containing the values for this request. The first time - * this method is called on an object, the LDAP request is sent, - * the results parsed and added to a private map and also to the - * cache of this LDAPCertStore. Subsequent calls return the private - * map immediately. - * - * The map contains an entry for each requested attribute. The - * attribute name is the key, values are byte[][]. If there are no - * values for that attribute, values are byte[0][]. - * - * @return the value Map - * @throws NamingException if a naming exception occurs - */ - private Map getValueMap() throws NamingException { - if (valueMap != null) { - return valueMap; - } - if (DEBUG) { - System.out.println("Request: " + name + ":" + requestedAttributes); - requests++; - if (requests % 5 == 0) { - System.out.println("LDAP requests: " + requests); - } - } - valueMap = new HashMap<>(8); - String[] attrIds = requestedAttributes.toArray(STRING0); - Attributes attrs; - - if (communicationError) { - ctx.reconnect(null); - communicationError = false; - } - - try { - attrs = ctx.getAttributes(name, attrIds); - } catch (CommunicationException ce) { - communicationError = true; - throw ce; - } catch (NameNotFoundException e) { - // name does not exist on this LDAP server - // treat same as not attributes found - attrs = EMPTY_ATTRIBUTES; - } - for (String attrId : requestedAttributes) { - Attribute attr = attrs.get(attrId); - byte[][] values = getAttributeValues(attr); - cacheAttribute(attrId, values); - valueMap.put(attrId, values); - } - return valueMap; - } - - /** - * Add the values to the cache. - */ - private void cacheAttribute(String attrId, byte[][] values) { - String cacheKey = name + "|" + attrId; - valueCache.put(cacheKey, values); - } - - /** - * Get the values for the given attribute. If the attribute is null - * or does not contain any values, a zero length byte array is - * returned. NOTE that it is assumed that all values are byte arrays. - */ - private byte[][] getAttributeValues(Attribute attr) - throws NamingException { - byte[][] values; - if (attr == null) { - values = BB0; - } else { - values = new byte[attr.size()][]; - int i = 0; - NamingEnumeration enum_ = attr.getAll(); - while (enum_.hasMore()) { - Object obj = enum_.next(); - if (debug != null) { - if (obj instanceof String) { - debug.println("LDAPCertStore.getAttrValues() " - + "enum.next is a string!: " + obj); - } - } - byte[] value = (byte[])obj; - values[i++] = value; - } - } - return values; - } - - } - - /* - * Gets certificates from an attribute id and location in the LDAP - * directory. Returns a Collection containing only the Certificates that - * match the specified CertSelector. - * - * @param name the location holding the attribute - * @param id the attribute identifier - * @param sel a CertSelector that the Certificates must match - * @return a Collection of Certificates found - * @throws CertStoreException if an exception occurs - */ - private Collection getCertificates(LDAPRequest request, - String id, X509CertSelector sel) throws CertStoreException { - - /* fetch encoded certs from storage */ - byte[][] encodedCert; - try { - encodedCert = request.getValues(id); - } catch (NamingException namingEx) { - throw new CertStoreException(namingEx); - } - - int n = encodedCert.length; - if (n == 0) { - return Collections.emptySet(); - } - - List certs = new ArrayList<>(n); - /* decode certs and check if they satisfy selector */ - for (int i = 0; i < n; i++) { - ByteArrayInputStream bais = new ByteArrayInputStream(encodedCert[i]); - try { - Certificate cert = cf.generateCertificate(bais); - if (sel.match(cert)) { - certs.add((X509Certificate)cert); - } - } catch (CertificateException e) { - if (debug != null) { - debug.println("LDAPCertStore.getCertificates() encountered " - + "exception while parsing cert, skipping the bad data: "); - HexDumpEncoder encoder = new HexDumpEncoder(); - debug.println( - "[ " + encoder.encodeBuffer(encodedCert[i]) + " ]"); - } - } - } - - return certs; - } - - /* - * Gets certificate pairs from an attribute id and location in the LDAP - * directory. - * - * @param name the location holding the attribute - * @param id the attribute identifier - * @return a Collection of X509CertificatePairs found - * @throws CertStoreException if an exception occurs - */ - private Collection getCertPairs( - LDAPRequest request, String id) throws CertStoreException { - - /* fetch the encoded cert pairs from storage */ - byte[][] encodedCertPair; - try { - encodedCertPair = request.getValues(id); - } catch (NamingException namingEx) { - throw new CertStoreException(namingEx); - } - - int n = encodedCertPair.length; - if (n == 0) { - return Collections.emptySet(); - } - - List certPairs = new ArrayList<>(n); - /* decode each cert pair and add it to the Collection */ - for (int i = 0; i < n; i++) { - try { - X509CertificatePair certPair = - X509CertificatePair.generateCertificatePair(encodedCertPair[i]); - certPairs.add(certPair); - } catch (CertificateException e) { - if (debug != null) { - debug.println( - "LDAPCertStore.getCertPairs() encountered exception " - + "while parsing cert, skipping the bad data: "); - HexDumpEncoder encoder = new HexDumpEncoder(); - debug.println( - "[ " + encoder.encodeBuffer(encodedCertPair[i]) + " ]"); - } - } - } - - return certPairs; - } - - /* - * Looks at certificate pairs stored in the crossCertificatePair attribute - * at the specified location in the LDAP directory. Returns a Collection - * containing all Certificates stored in the forward component that match - * the forward CertSelector and all Certificates stored in the reverse - * component that match the reverse CertSelector. - *

- * If either forward or reverse is null, all certificates from the - * corresponding component will be rejected. - * - * @param name the location to look in - * @param forward the forward CertSelector (or null) - * @param reverse the reverse CertSelector (or null) - * @return a Collection of Certificates found - * @throws CertStoreException if an exception occurs - */ - private Collection getMatchingCrossCerts( - LDAPRequest request, X509CertSelector forward, - X509CertSelector reverse) - throws CertStoreException { - // Get the cert pairs - Collection certPairs = - getCertPairs(request, CROSS_CERT); - - // Find Certificates that match and put them in a list - ArrayList matchingCerts = new ArrayList<>(); - for (X509CertificatePair certPair : certPairs) { - X509Certificate cert; - if (forward != null) { - cert = certPair.getForward(); - if ((cert != null) && forward.match(cert)) { - matchingCerts.add(cert); - } - } - if (reverse != null) { - cert = certPair.getReverse(); - if ((cert != null) && reverse.match(cert)) { - matchingCerts.add(cert); - } - } - } - return matchingCerts; + return lci; } /** @@ -612,159 +242,12 @@ public final class LDAPCertStore extends CertStoreSpi { debug.println("LDAPCertStore.engineGetCertificates() selector: " + String.valueOf(selector)); } - if (selector == null) { selector = new X509CertSelector(); + } else if (!(selector instanceof X509CertSelector)) { + throw new CertStoreException("need X509CertSelector to find certs"); } - if (!(selector instanceof X509CertSelector)) { - throw new CertStoreException("LDAPCertStore needs an X509CertSelector " + - "to find certs"); - } - X509CertSelector xsel = (X509CertSelector) selector; - int basicConstraints = xsel.getBasicConstraints(); - String subject = xsel.getSubjectAsString(); - String issuer = xsel.getIssuerAsString(); - HashSet certs = new HashSet<>(); - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() basicConstraints: " - + basicConstraints); - } - - // basicConstraints: - // -2: only EE certs accepted - // -1: no check is done - // 0: any CA certificate accepted - // >1: certificate's basicConstraints extension pathlen must match - if (subject != null) { - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() " - + "subject is not null"); - } - LDAPRequest request = new LDAPRequest(subject); - if (basicConstraints > -2) { - request.addRequestedAttribute(CROSS_CERT); - request.addRequestedAttribute(CA_CERT); - request.addRequestedAttribute(ARL); - if (prefetchCRLs) { - request.addRequestedAttribute(CRL); - } - } - if (basicConstraints < 0) { - request.addRequestedAttribute(USER_CERT); - } - - if (basicConstraints > -2) { - certs.addAll(getMatchingCrossCerts(request, xsel, null)); - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() after " - + "getMatchingCrossCerts(subject,xsel,null),certs.size(): " - + certs.size()); - } - certs.addAll(getCertificates(request, CA_CERT, xsel)); - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() after " - + "getCertificates(subject,CA_CERT,xsel),certs.size(): " - + certs.size()); - } - } - if (basicConstraints < 0) { - certs.addAll(getCertificates(request, USER_CERT, xsel)); - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() after " - + "getCertificates(subject,USER_CERT, xsel),certs.size(): " - + certs.size()); - } - } - } else { - if (debug != null) { - debug.println - ("LDAPCertStore.engineGetCertificates() subject is null"); - } - if (basicConstraints == -2) { - throw new CertStoreException("need subject to find EE certs"); - } - if (issuer == null) { - throw new CertStoreException("need subject or issuer to find certs"); - } - } - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() about to " - + "getMatchingCrossCerts..."); - } - if ((issuer != null) && (basicConstraints > -2)) { - LDAPRequest request = new LDAPRequest(issuer); - request.addRequestedAttribute(CROSS_CERT); - request.addRequestedAttribute(CA_CERT); - request.addRequestedAttribute(ARL); - if (prefetchCRLs) { - request.addRequestedAttribute(CRL); - } - - certs.addAll(getMatchingCrossCerts(request, null, xsel)); - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() after " - + "getMatchingCrossCerts(issuer,null,xsel),certs.size(): " - + certs.size()); - } - certs.addAll(getCertificates(request, CA_CERT, xsel)); - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() after " - + "getCertificates(issuer,CA_CERT,xsel),certs.size(): " - + certs.size()); - } - } - if (debug != null) { - debug.println("LDAPCertStore.engineGetCertificates() returning certs"); - } - return certs; - } - - /* - * Gets CRLs from an attribute id and location in the LDAP directory. - * Returns a Collection containing only the CRLs that match the - * specified CRLSelector. - * - * @param name the location holding the attribute - * @param id the attribute identifier - * @param sel a CRLSelector that the CRLs must match - * @return a Collection of CRLs found - * @throws CertStoreException if an exception occurs - */ - private Collection getCRLs(LDAPRequest request, String id, - X509CRLSelector sel) throws CertStoreException { - - /* fetch the encoded crls from storage */ - byte[][] encodedCRL; - try { - encodedCRL = request.getValues(id); - } catch (NamingException namingEx) { - throw new CertStoreException(namingEx); - } - - int n = encodedCRL.length; - if (n == 0) { - return Collections.emptySet(); - } - - List crls = new ArrayList<>(n); - /* decode each crl and check if it matches selector */ - for (int i = 0; i < n; i++) { - try { - CRL crl = cf.generateCRL(new ByteArrayInputStream(encodedCRL[i])); - if (sel.match(crl)) { - crls.add((X509CRL)crl); - } - } catch (CRLException e) { - if (debug != null) { - debug.println("LDAPCertStore.getCRLs() encountered exception" - + " while parsing CRL, skipping the bad data: "); - HexDumpEncoder encoder = new HexDumpEncoder(); - debug.println("[ " + encoder.encodeBuffer(encodedCRL[i]) + " ]"); - } - } - } - - return crls; + return impl.getCertificates((X509CertSelector) selector, ldapDN); } /** @@ -797,314 +280,9 @@ public final class LDAPCertStore extends CertStoreSpi { // Set up selector and collection to hold CRLs if (selector == null) { selector = new X509CRLSelector(); - } - if (!(selector instanceof X509CRLSelector)) { + } else if (!(selector instanceof X509CRLSelector)) { throw new CertStoreException("need X509CRLSelector to find CRLs"); } - X509CRLSelector xsel = (X509CRLSelector) selector; - HashSet crls = new HashSet<>(); - - // Look in directory entry for issuer of cert we're checking. - Collection issuerNames; - X509Certificate certChecking = xsel.getCertificateChecking(); - if (certChecking != null) { - issuerNames = new HashSet<>(); - X500Principal issuer = certChecking.getIssuerX500Principal(); - issuerNames.add(issuer.getName(X500Principal.RFC2253)); - } else { - // But if we don't know which cert we're checking, try the directory - // entries of all acceptable CRL issuers - issuerNames = xsel.getIssuerNames(); - if (issuerNames == null) { - throw new CertStoreException("need issuerNames or certChecking to " - + "find CRLs"); - } - } - for (Object nameObject : issuerNames) { - String issuerName; - if (nameObject instanceof byte[]) { - try { - X500Principal issuer = new X500Principal((byte[])nameObject); - issuerName = issuer.getName(X500Principal.RFC2253); - } catch (IllegalArgumentException e) { - continue; - } - } else { - issuerName = (String)nameObject; - } - // If all we want is CA certs, try to get the (probably shorter) ARL - Collection entryCRLs = Collections.emptySet(); - if (certChecking == null || certChecking.getBasicConstraints() != -1) { - LDAPRequest request = new LDAPRequest(issuerName); - request.addRequestedAttribute(CROSS_CERT); - request.addRequestedAttribute(CA_CERT); - request.addRequestedAttribute(ARL); - if (prefetchCRLs) { - request.addRequestedAttribute(CRL); - } - try { - entryCRLs = getCRLs(request, ARL, xsel); - if (entryCRLs.isEmpty()) { - // no ARLs found. We assume that means that there are - // no ARLs on this server at all and prefetch the CRLs. - prefetchCRLs = true; - } else { - crls.addAll(entryCRLs); - } - } catch (CertStoreException e) { - if (debug != null) { - debug.println("LDAPCertStore.engineGetCRLs non-fatal error " - + "retrieving ARLs:" + e); - e.printStackTrace(); - } - } - } - // Otherwise, get the CRL - // if certChecking is null, we don't know if we should look in ARL or CRL - // attribute, so check both for matching CRLs. - if (entryCRLs.isEmpty() || certChecking == null) { - LDAPRequest request = new LDAPRequest(issuerName); - request.addRequestedAttribute(CRL); - entryCRLs = getCRLs(request, CRL, xsel); - crls.addAll(entryCRLs); - } - } - return crls; - } - - // converts an LDAP URI into LDAPCertStoreParameters - static LDAPCertStoreParameters getParameters(URI uri) { - String host = uri.getHost(); - if (host == null) { - return new SunLDAPCertStoreParameters(); - } else { - int port = uri.getPort(); - return (port == -1 - ? new SunLDAPCertStoreParameters(host) - : new SunLDAPCertStoreParameters(host, port)); - } - } - - /* - * Subclass of LDAPCertStoreParameters with overridden equals/hashCode - * methods. This is necessary because the parameters are used as - * keys in the LDAPCertStore cache. - */ - private static class SunLDAPCertStoreParameters - extends LDAPCertStoreParameters { - - private volatile int hashCode = 0; - - SunLDAPCertStoreParameters(String serverName, int port) { - super(serverName, port); - } - SunLDAPCertStoreParameters(String serverName) { - super(serverName); - } - SunLDAPCertStoreParameters() { - super(); - } - @Override - public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!(obj instanceof LDAPCertStoreParameters)) { - return false; - } - LDAPCertStoreParameters params = (LDAPCertStoreParameters) obj; - return (getPort() == params.getPort() && - getServerName().equalsIgnoreCase(params.getServerName())); - } - @Override - public int hashCode() { - if (hashCode == 0) { - int result = 17; - result = 37*result + getPort(); - result = 37*result + - getServerName().toLowerCase(Locale.ENGLISH).hashCode(); - hashCode = result; - } - return hashCode; - } - } - - /* - * This inner class wraps an existing X509CertSelector and adds - * additional criteria to match on when the certificate's subject is - * different than the LDAP Distinguished Name entry. The LDAPCertStore - * implementation uses the subject DN as the directory entry for - * looking up certificates. This can be problematic if the certificates - * that you want to fetch have a different subject DN than the entry - * where they are stored. You could set the selector's subject to the - * LDAP DN entry, but then the resulting match would fail to find the - * desired certificates because the subject DNs would not match. This - * class avoids that problem by introducing a certSubject which should - * be set to the certificate's subject DN when it is different than - * the LDAP DN. - */ - static class LDAPCertSelector extends X509CertSelector { - - private X500Principal certSubject; - private X509CertSelector selector; - private X500Principal subject; - - /** - * Creates an LDAPCertSelector. - * - * @param selector the X509CertSelector to wrap - * @param certSubject the subject DN of the certificate that you want - * to retrieve via LDAP - * @param ldapDN the LDAP DN where the certificate is stored - */ - LDAPCertSelector(X509CertSelector selector, X500Principal certSubject, - String ldapDN) throws IOException { - this.selector = selector == null ? new X509CertSelector() : selector; - this.certSubject = certSubject; - this.subject = new X500Name(ldapDN).asX500Principal(); - } - - // we only override the get (accessor methods) since the set methods - // will not be invoked by the code that uses this LDAPCertSelector. - public X509Certificate getCertificate() { - return selector.getCertificate(); - } - public BigInteger getSerialNumber() { - return selector.getSerialNumber(); - } - public X500Principal getIssuer() { - return selector.getIssuer(); - } - public String getIssuerAsString() { - return selector.getIssuerAsString(); - } - public byte[] getIssuerAsBytes() throws IOException { - return selector.getIssuerAsBytes(); - } - public X500Principal getSubject() { - // return the ldap DN - return subject; - } - public String getSubjectAsString() { - // return the ldap DN - return subject.getName(); - } - public byte[] getSubjectAsBytes() throws IOException { - // return the encoded ldap DN - return subject.getEncoded(); - } - public byte[] getSubjectKeyIdentifier() { - return selector.getSubjectKeyIdentifier(); - } - public byte[] getAuthorityKeyIdentifier() { - return selector.getAuthorityKeyIdentifier(); - } - public Date getCertificateValid() { - return selector.getCertificateValid(); - } - public Date getPrivateKeyValid() { - return selector.getPrivateKeyValid(); - } - public String getSubjectPublicKeyAlgID() { - return selector.getSubjectPublicKeyAlgID(); - } - public PublicKey getSubjectPublicKey() { - return selector.getSubjectPublicKey(); - } - public boolean[] getKeyUsage() { - return selector.getKeyUsage(); - } - public Set getExtendedKeyUsage() { - return selector.getExtendedKeyUsage(); - } - public boolean getMatchAllSubjectAltNames() { - return selector.getMatchAllSubjectAltNames(); - } - public Collection> getSubjectAlternativeNames() { - return selector.getSubjectAlternativeNames(); - } - public byte[] getNameConstraints() { - return selector.getNameConstraints(); - } - public int getBasicConstraints() { - return selector.getBasicConstraints(); - } - public Set getPolicy() { - return selector.getPolicy(); - } - public Collection> getPathToNames() { - return selector.getPathToNames(); - } - - public boolean match(Certificate cert) { - // temporarily set the subject criterion to the certSubject - // so that match will not reject the desired certificates - selector.setSubject(certSubject); - boolean match = selector.match(cert); - selector.setSubject(subject); - return match; - } - } - - /** - * This class has the same purpose as LDAPCertSelector except it is for - * X.509 CRLs. - */ - static class LDAPCRLSelector extends X509CRLSelector { - - private X509CRLSelector selector; - private Collection certIssuers; - private Collection issuers; - private HashSet issuerNames; - - /** - * Creates an LDAPCRLSelector. - * - * @param selector the X509CRLSelector to wrap - * @param certIssuers the issuer DNs of the CRLs that you want - * to retrieve via LDAP - * @param ldapDN the LDAP DN where the CRL is stored - */ - LDAPCRLSelector(X509CRLSelector selector, - Collection certIssuers, String ldapDN) - throws IOException { - this.selector = selector == null ? new X509CRLSelector() : selector; - this.certIssuers = certIssuers; - issuerNames = new HashSet<>(); - issuerNames.add(ldapDN); - issuers = new HashSet<>(); - issuers.add(new X500Name(ldapDN).asX500Principal()); - } - // we only override the get (accessor methods) since the set methods - // will not be invoked by the code that uses this LDAPCRLSelector. - public Collection getIssuers() { - // return the ldap DN - return Collections.unmodifiableCollection(issuers); - } - public Collection getIssuerNames() { - // return the ldap DN - return Collections.unmodifiableCollection(issuerNames); - } - public BigInteger getMinCRL() { - return selector.getMinCRL(); - } - public BigInteger getMaxCRL() { - return selector.getMaxCRL(); - } - public Date getDateAndTime() { - return selector.getDateAndTime(); - } - public X509Certificate getCertificateChecking() { - return selector.getCertificateChecking(); - } - public boolean match(CRL crl) { - // temporarily set the issuer criterion to the certIssuers - // so that match will not reject the desired CRL - selector.setIssuers(certIssuers); - boolean match = selector.match(crl); - selector.setIssuers(issuers); - return match; - } + return impl.getCRLs((X509CRLSelector) selector, ldapDN); } } diff --git a/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreHelper.java b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreHelper.java deleted file mode 100644 index 8e6899bc0c8..00000000000 --- a/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreHelper.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Copyright (c) 2009, 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. - */ - -package sun.security.provider.certpath.ldap; - -import java.io.IOException; -import java.net.URI; -import java.util.Collection; -import java.security.NoSuchAlgorithmException; -import java.security.InvalidAlgorithmParameterException; -import java.security.cert.CertStore; -import java.security.cert.CertStoreException; -import java.security.cert.X509CertSelector; -import java.security.cert.X509CRLSelector; -import javax.naming.CommunicationException; -import javax.naming.ServiceUnavailableException; -import javax.security.auth.x500.X500Principal; - -import sun.security.provider.certpath.CertStoreHelper; - -/** - * LDAP implementation of CertStoreHelper. - */ - -public final class LDAPCertStoreHelper - extends CertStoreHelper -{ - @Override - public CertStore getCertStore(URI uri) - throws NoSuchAlgorithmException, InvalidAlgorithmParameterException - { - return LDAPCertStore.getInstance(LDAPCertStore.getParameters(uri)); - } - - @Override - public X509CertSelector wrap(X509CertSelector selector, - X500Principal certSubject, - String ldapDN) - throws IOException - { - return new LDAPCertStore.LDAPCertSelector(selector, certSubject, ldapDN); - } - - @Override - public X509CRLSelector wrap(X509CRLSelector selector, - Collection certIssuers, - String ldapDN) - throws IOException - { - return new LDAPCertStore.LDAPCRLSelector(selector, certIssuers, ldapDN); - } - - @Override - public boolean isCausedByNetworkIssue(CertStoreException e) { - Throwable t = e.getCause(); - return (t != null && (t instanceof ServiceUnavailableException || - t instanceof CommunicationException)); - } -} diff --git a/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreImpl.java b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreImpl.java new file mode 100644 index 00000000000..319ad7cb43f --- /dev/null +++ b/jdk/src/java.naming/share/classes/sun/security/provider/certpath/ldap/LDAPCertStoreImpl.java @@ -0,0 +1,772 @@ +/* + * Copyright (c) 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. + */ + +package sun.security.provider.certpath.ldap; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.util.*; +import javax.naming.Context; +import javax.naming.NamingEnumeration; +import javax.naming.NamingException; +import javax.naming.NameNotFoundException; +import javax.naming.directory.Attribute; +import javax.naming.directory.Attributes; +import javax.naming.directory.BasicAttributes; + +import java.security.*; +import java.security.cert.Certificate; +import java.security.cert.*; +import javax.naming.CommunicationException; +import javax.naming.ldap.InitialLdapContext; +import javax.naming.ldap.LdapContext; +import javax.security.auth.x500.X500Principal; + +import sun.misc.HexDumpEncoder; +import sun.security.provider.certpath.X509CertificatePair; +import sun.security.util.Cache; +import sun.security.util.Debug; +import sun.security.x509.X500Name; + +/** + * Core implementation of a LDAP Cert Store. + * @see java.security.cert.CertStore + * + * @since 1.9 + */ +final class LDAPCertStoreImpl { + + private static final Debug debug = Debug.getInstance("certpath"); + + private final static boolean DEBUG = false; + + /** + * LDAP attribute identifiers. + */ + private static final String USER_CERT = "userCertificate;binary"; + private static final String CA_CERT = "cACertificate;binary"; + private static final String CROSS_CERT = "crossCertificatePair;binary"; + private static final String CRL = "certificateRevocationList;binary"; + private static final String ARL = "authorityRevocationList;binary"; + private static final String DELTA_CRL = "deltaRevocationList;binary"; + + // Constants for various empty values + private final static String[] STRING0 = new String[0]; + + private final static byte[][] BB0 = new byte[0][]; + + private final static Attributes EMPTY_ATTRIBUTES = new BasicAttributes(); + + // cache related constants + private final static int DEFAULT_CACHE_SIZE = 750; + private final static int DEFAULT_CACHE_LIFETIME = 30; + + private final static int LIFETIME; + + private final static String PROP_LIFETIME = + "sun.security.certpath.ldap.cache.lifetime"; + + /* + * Internal system property, that when set to "true", disables the + * JNDI application resource files lookup to prevent recursion issues + * when validating signed JARs with LDAP URLs in certificates. + */ + private final static String PROP_DISABLE_APP_RESOURCE_FILES = + "sun.security.certpath.ldap.disable.app.resource.files"; + + static { + String s = AccessController.doPrivileged( + (PrivilegedAction) () -> System.getProperty(PROP_LIFETIME)); + if (s != null) { + LIFETIME = Integer.parseInt(s); // throws NumberFormatException + } else { + LIFETIME = DEFAULT_CACHE_LIFETIME; + } + } + + /** + * The CertificateFactory used to decode certificates from + * their binary stored form. + */ + private CertificateFactory cf; + /** + * The JNDI directory context. + */ + private LdapContext ctx; + + /** + * Flag indicating that communication error occurred. + */ + private boolean communicationError = false; + + /** + * Flag indicating whether we should prefetch CRLs. + */ + private boolean prefetchCRLs = false; + + private final Cache valueCache; + + private int cacheHits = 0; + private int cacheMisses = 0; + private int requests = 0; + + /** + * Creates a CertStore with the specified parameters. + */ + LDAPCertStoreImpl(String serverName, int port) + throws InvalidAlgorithmParameterException { + createInitialDirContext(serverName, port); + // Create CertificateFactory for use later on + try { + cf = CertificateFactory.getInstance("X.509"); + } catch (CertificateException e) { + throw new InvalidAlgorithmParameterException( + "unable to create CertificateFactory for X.509"); + } + if (LIFETIME == 0) { + valueCache = Cache.newNullCache(); + } else if (LIFETIME < 0) { + valueCache = Cache.newSoftMemoryCache(DEFAULT_CACHE_SIZE); + } else { + valueCache = Cache.newSoftMemoryCache(DEFAULT_CACHE_SIZE, LIFETIME); + } + } + + /** + * Create InitialDirContext. + * + * @param server Server DNS name hosting LDAP service + * @param port Port at which server listens for requests + * @throws InvalidAlgorithmParameterException if creation fails + */ + private void createInitialDirContext(String server, int port) + throws InvalidAlgorithmParameterException { + String url = "ldap://" + server + ":" + port; + Hashtable env = new Hashtable<>(); + env.put(Context.INITIAL_CONTEXT_FACTORY, + "com.sun.jndi.ldap.LdapCtxFactory"); + env.put(Context.PROVIDER_URL, url); + + // If property is set to true, disable application resource file lookup. + boolean disableAppResourceFiles = AccessController.doPrivileged( + (PrivilegedAction) () -> Boolean.getBoolean(PROP_DISABLE_APP_RESOURCE_FILES)); + if (disableAppResourceFiles) { + if (debug != null) { + debug.println("LDAPCertStore disabling app resource files"); + } + env.put("com.sun.naming.disable.app.resource.files", "true"); + } + + try { + ctx = new InitialLdapContext(env, null); + /* + * By default, follow referrals unless application has + * overridden property in an application resource file. + */ + Hashtable currentEnv = ctx.getEnvironment(); + if (currentEnv.get(Context.REFERRAL) == null) { + ctx.addToEnvironment(Context.REFERRAL, "follow"); + } + } catch (NamingException e) { + if (debug != null) { + debug.println("LDAPCertStore.engineInit about to throw " + + "InvalidAlgorithmParameterException"); + e.printStackTrace(); + } + Exception ee = new InvalidAlgorithmParameterException + ("unable to create InitialDirContext using supplied parameters"); + ee.initCause(e); + throw (InvalidAlgorithmParameterException)ee; + } + } + + /** + * Private class encapsulating the actual LDAP operations and cache + * handling. Use: + * + * LDAPRequest request = new LDAPRequest(dn); + * request.addRequestedAttribute(CROSS_CERT); + * request.addRequestedAttribute(CA_CERT); + * byte[][] crossValues = request.getValues(CROSS_CERT); + * byte[][] caValues = request.getValues(CA_CERT); + * + * At most one LDAP request is sent for each instance created. If all + * getValues() calls can be satisfied from the cache, no request + * is sent at all. If a request is sent, all requested attributes + * are always added to the cache irrespective of whether the getValues() + * method is called. + */ + private class LDAPRequest { + + private final String name; + private Map valueMap; + private final List requestedAttributes; + + LDAPRequest(String name) { + this.name = name; + requestedAttributes = new ArrayList<>(5); + } + + String getName() { + return name; + } + + void addRequestedAttribute(String attrId) { + if (valueMap != null) { + throw new IllegalStateException("Request already sent"); + } + requestedAttributes.add(attrId); + } + + /** + * Gets one or more binary values from an attribute. + * + * @param name the location holding the attribute + * @param attrId the attribute identifier + * @return an array of binary values (byte arrays) + * @throws NamingException if a naming exception occurs + */ + byte[][] getValues(String attrId) throws NamingException { + if (DEBUG && ((cacheHits + cacheMisses) % 50 == 0)) { + System.out.println("Cache hits: " + cacheHits + "; misses: " + + cacheMisses); + } + String cacheKey = name + "|" + attrId; + byte[][] values = valueCache.get(cacheKey); + if (values != null) { + cacheHits++; + return values; + } + cacheMisses++; + Map attrs = getValueMap(); + values = attrs.get(attrId); + return values; + } + + /** + * Get a map containing the values for this request. The first time + * this method is called on an object, the LDAP request is sent, + * the results parsed and added to a private map and also to the + * cache of this LDAPCertStore. Subsequent calls return the private + * map immediately. + * + * The map contains an entry for each requested attribute. The + * attribute name is the key, values are byte[][]. If there are no + * values for that attribute, values are byte[0][]. + * + * @return the value Map + * @throws NamingException if a naming exception occurs + */ + private Map getValueMap() throws NamingException { + if (valueMap != null) { + return valueMap; + } + if (DEBUG) { + System.out.println("Request: " + name + ":" + requestedAttributes); + requests++; + if (requests % 5 == 0) { + System.out.println("LDAP requests: " + requests); + } + } + valueMap = new HashMap<>(8); + String[] attrIds = requestedAttributes.toArray(STRING0); + Attributes attrs; + + if (communicationError) { + ctx.reconnect(null); + communicationError = false; + } + + try { + attrs = ctx.getAttributes(name, attrIds); + } catch (CommunicationException ce) { + communicationError = true; + throw ce; + } catch (NameNotFoundException e) { + // name does not exist on this LDAP server + // treat same as not attributes found + attrs = EMPTY_ATTRIBUTES; + } + for (String attrId : requestedAttributes) { + Attribute attr = attrs.get(attrId); + byte[][] values = getAttributeValues(attr); + cacheAttribute(attrId, values); + valueMap.put(attrId, values); + } + return valueMap; + } + + /** + * Add the values to the cache. + */ + private void cacheAttribute(String attrId, byte[][] values) { + String cacheKey = name + "|" + attrId; + valueCache.put(cacheKey, values); + } + + /** + * Get the values for the given attribute. If the attribute is null + * or does not contain any values, a zero length byte array is + * returned. NOTE that it is assumed that all values are byte arrays. + */ + private byte[][] getAttributeValues(Attribute attr) + throws NamingException { + byte[][] values; + if (attr == null) { + values = BB0; + } else { + values = new byte[attr.size()][]; + int i = 0; + NamingEnumeration enum_ = attr.getAll(); + while (enum_.hasMore()) { + Object obj = enum_.next(); + if (debug != null) { + if (obj instanceof String) { + debug.println("LDAPCertStore.getAttrValues() " + + "enum.next is a string!: " + obj); + } + } + byte[] value = (byte[])obj; + values[i++] = value; + } + } + return values; + } + + } + + /* + * Gets certificates from an attribute id and location in the LDAP + * directory. Returns a Collection containing only the Certificates that + * match the specified CertSelector. + * + * @param name the location holding the attribute + * @param id the attribute identifier + * @param sel a CertSelector that the Certificates must match + * @return a Collection of Certificates found + * @throws CertStoreException if an exception occurs + */ + private Collection getCertificates(LDAPRequest request, + String id, X509CertSelector sel) throws CertStoreException { + + /* fetch encoded certs from storage */ + byte[][] encodedCert; + try { + encodedCert = request.getValues(id); + } catch (NamingException namingEx) { + throw new CertStoreException(namingEx); + } + + int n = encodedCert.length; + if (n == 0) { + return Collections.emptySet(); + } + + List certs = new ArrayList<>(n); + /* decode certs and check if they satisfy selector */ + for (int i = 0; i < n; i++) { + ByteArrayInputStream bais = new ByteArrayInputStream(encodedCert[i]); + try { + Certificate cert = cf.generateCertificate(bais); + if (sel.match(cert)) { + certs.add((X509Certificate)cert); + } + } catch (CertificateException e) { + if (debug != null) { + debug.println("LDAPCertStore.getCertificates() encountered " + + "exception while parsing cert, skipping the bad data: "); + HexDumpEncoder encoder = new HexDumpEncoder(); + debug.println( + "[ " + encoder.encodeBuffer(encodedCert[i]) + " ]"); + } + } + } + + return certs; + } + + /* + * Gets certificate pairs from an attribute id and location in the LDAP + * directory. + * + * @param name the location holding the attribute + * @param id the attribute identifier + * @return a Collection of X509CertificatePairs found + * @throws CertStoreException if an exception occurs + */ + private Collection getCertPairs( + LDAPRequest request, String id) throws CertStoreException { + + /* fetch the encoded cert pairs from storage */ + byte[][] encodedCertPair; + try { + encodedCertPair = request.getValues(id); + } catch (NamingException namingEx) { + throw new CertStoreException(namingEx); + } + + int n = encodedCertPair.length; + if (n == 0) { + return Collections.emptySet(); + } + + List certPairs = new ArrayList<>(n); + /* decode each cert pair and add it to the Collection */ + for (int i = 0; i < n; i++) { + try { + X509CertificatePair certPair = + X509CertificatePair.generateCertificatePair(encodedCertPair[i]); + certPairs.add(certPair); + } catch (CertificateException e) { + if (debug != null) { + debug.println( + "LDAPCertStore.getCertPairs() encountered exception " + + "while parsing cert, skipping the bad data: "); + HexDumpEncoder encoder = new HexDumpEncoder(); + debug.println( + "[ " + encoder.encodeBuffer(encodedCertPair[i]) + " ]"); + } + } + } + + return certPairs; + } + + /* + * Looks at certificate pairs stored in the crossCertificatePair attribute + * at the specified location in the LDAP directory. Returns a Collection + * containing all X509Certificates stored in the forward component that match + * the forward X509CertSelector and all Certificates stored in the reverse + * component that match the reverse X509CertSelector. + *

+ * If either forward or reverse is null, all certificates from the + * corresponding component will be rejected. + * + * @param name the location to look in + * @param forward the forward X509CertSelector (or null) + * @param reverse the reverse X509CertSelector (or null) + * @return a Collection of X509Certificates found + * @throws CertStoreException if an exception occurs + */ + private Collection getMatchingCrossCerts( + LDAPRequest request, X509CertSelector forward, + X509CertSelector reverse) + throws CertStoreException { + // Get the cert pairs + Collection certPairs = + getCertPairs(request, CROSS_CERT); + + // Find Certificates that match and put them in a list + ArrayList matchingCerts = new ArrayList<>(); + for (X509CertificatePair certPair : certPairs) { + X509Certificate cert; + if (forward != null) { + cert = certPair.getForward(); + if ((cert != null) && forward.match(cert)) { + matchingCerts.add(cert); + } + } + if (reverse != null) { + cert = certPair.getReverse(); + if ((cert != null) && reverse.match(cert)) { + matchingCerts.add(cert); + } + } + } + return matchingCerts; + } + + /** + * Returns a Collection of X509Certificates that + * match the specified selector. If no X509Certificates + * match the selector, an empty Collection will be returned. + *

+ * It is not practical to search every entry in the LDAP database for + * matching X509Certificates. Instead, the + * X509CertSelector is examined in order to determine where + * matching Certificates are likely to be found (according + * to the PKIX LDAPv2 schema, RFC 2587). + * If the subject is specified, its directory entry is searched. If the + * issuer is specified, its directory entry is searched. If neither the + * subject nor the issuer are specified (or the selector is not an + * X509CertSelector), a CertStoreException is + * thrown. + * + * @param selector a X509CertSelector used to select which + * Certificates should be returned. + * @return a Collection of X509Certificates that + * match the specified selector + * @throws CertStoreException if an exception occurs + */ + synchronized Collection getCertificates + (X509CertSelector xsel, String ldapDN) throws CertStoreException { + + if (ldapDN == null) { + ldapDN = xsel.getSubjectAsString(); + } + int basicConstraints = xsel.getBasicConstraints(); + String issuer = xsel.getIssuerAsString(); + HashSet certs = new HashSet<>(); + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() basicConstraints: " + + basicConstraints); + } + + // basicConstraints: + // -2: only EE certs accepted + // -1: no check is done + // 0: any CA certificate accepted + // >1: certificate's basicConstraints extension pathlen must match + if (ldapDN != null) { + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() " + + " subject is not null"); + } + LDAPRequest request = new LDAPRequest(ldapDN); + if (basicConstraints > -2) { + request.addRequestedAttribute(CROSS_CERT); + request.addRequestedAttribute(CA_CERT); + request.addRequestedAttribute(ARL); + if (prefetchCRLs) { + request.addRequestedAttribute(CRL); + } + } + if (basicConstraints < 0) { + request.addRequestedAttribute(USER_CERT); + } + + if (basicConstraints > -2) { + certs.addAll(getMatchingCrossCerts(request, xsel, null)); + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() after " + + "getMatchingCrossCerts(subject,xsel,null),certs.size(): " + + certs.size()); + } + certs.addAll(getCertificates(request, CA_CERT, xsel)); + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() after " + + "getCertificates(subject,CA_CERT,xsel),certs.size(): " + + certs.size()); + } + } + if (basicConstraints < 0) { + certs.addAll(getCertificates(request, USER_CERT, xsel)); + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() after " + + "getCertificates(subject,USER_CERT, xsel),certs.size(): " + + certs.size()); + } + } + } else { + if (debug != null) { + debug.println + ("LDAPCertStore.engineGetCertificates() subject is null"); + } + if (basicConstraints == -2) { + throw new CertStoreException("need subject to find EE certs"); + } + if (issuer == null) { + throw new CertStoreException("need subject or issuer to find certs"); + } + } + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() about to " + + "getMatchingCrossCerts..."); + } + if ((issuer != null) && (basicConstraints > -2)) { + LDAPRequest request = new LDAPRequest(issuer); + request.addRequestedAttribute(CROSS_CERT); + request.addRequestedAttribute(CA_CERT); + request.addRequestedAttribute(ARL); + if (prefetchCRLs) { + request.addRequestedAttribute(CRL); + } + + certs.addAll(getMatchingCrossCerts(request, null, xsel)); + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() after " + + "getMatchingCrossCerts(issuer,null,xsel),certs.size(): " + + certs.size()); + } + certs.addAll(getCertificates(request, CA_CERT, xsel)); + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() after " + + "getCertificates(issuer,CA_CERT,xsel),certs.size(): " + + certs.size()); + } + } + if (debug != null) { + debug.println("LDAPCertStore.engineGetCertificates() returning certs"); + } + return certs; + } + + /* + * Gets CRLs from an attribute id and location in the LDAP directory. + * Returns a Collection containing only the CRLs that match the + * specified X509CRLSelector. + * + * @param name the location holding the attribute + * @param id the attribute identifier + * @param sel a X509CRLSelector that the CRLs must match + * @return a Collection of CRLs found + * @throws CertStoreException if an exception occurs + */ + private Collection getCRLs(LDAPRequest request, String id, + X509CRLSelector sel) throws CertStoreException { + + /* fetch the encoded crls from storage */ + byte[][] encodedCRL; + try { + encodedCRL = request.getValues(id); + } catch (NamingException namingEx) { + throw new CertStoreException(namingEx); + } + + int n = encodedCRL.length; + if (n == 0) { + return Collections.emptySet(); + } + + List crls = new ArrayList<>(n); + /* decode each crl and check if it matches selector */ + for (int i = 0; i < n; i++) { + try { + CRL crl = cf.generateCRL(new ByteArrayInputStream(encodedCRL[i])); + if (sel.match(crl)) { + crls.add((X509CRL)crl); + } + } catch (CRLException e) { + if (debug != null) { + debug.println("LDAPCertStore.getCRLs() encountered exception" + + " while parsing CRL, skipping the bad data: "); + HexDumpEncoder encoder = new HexDumpEncoder(); + debug.println("[ " + encoder.encodeBuffer(encodedCRL[i]) + " ]"); + } + } + } + + return crls; + } + + /** + * Returns a Collection of X509CRLs that + * match the specified selector. If no X509CRLs + * match the selector, an empty Collection will be returned. + *

+ * It is not practical to search every entry in the LDAP database for + * matching X509CRLs. Instead, the X509CRLSelector + * is examined in order to determine where matching X509CRLs + * are likely to be found (according to the PKIX LDAPv2 schema, RFC 2587). + * If issuerNames or certChecking are specified, the issuer's directory + * entry is searched. If neither issuerNames or certChecking are specified + * (or the selector is not an X509CRLSelector), a + * CertStoreException is thrown. + * + * @param selector A X509CRLSelector used to select which + * CRLs should be returned. Specify null + * to return all CRLs. + * @return A Collection of X509CRLs that + * match the specified selector + * @throws CertStoreException if an exception occurs + */ + synchronized Collection getCRLs(X509CRLSelector xsel, + String ldapDN) throws CertStoreException { + + HashSet crls = new HashSet<>(); + + // Look in directory entry for issuer of cert we're checking. + Collection issuerNames; + X509Certificate certChecking = xsel.getCertificateChecking(); + if (certChecking != null) { + issuerNames = new HashSet<>(); + X500Principal issuer = certChecking.getIssuerX500Principal(); + issuerNames.add(issuer.getName(X500Principal.RFC2253)); + } else { + // But if we don't know which cert we're checking, try the directory + // entries of all acceptable CRL issuers + if (ldapDN != null) { + issuerNames = new HashSet<>(); + issuerNames.add(ldapDN); + } else { + issuerNames = xsel.getIssuerNames(); + if (issuerNames == null) { + throw new CertStoreException("need issuerNames or" + + " certChecking to find CRLs"); + } + } + } + for (Object nameObject : issuerNames) { + String issuerName; + if (nameObject instanceof byte[]) { + try { + X500Principal issuer = new X500Principal((byte[])nameObject); + issuerName = issuer.getName(X500Principal.RFC2253); + } catch (IllegalArgumentException e) { + continue; + } + } else { + issuerName = (String)nameObject; + } + // If all we want is CA certs, try to get the (probably shorter) ARL + Collection entryCRLs = Collections.emptySet(); + if (certChecking == null || certChecking.getBasicConstraints() != -1) { + LDAPRequest request = new LDAPRequest(issuerName); + request.addRequestedAttribute(CROSS_CERT); + request.addRequestedAttribute(CA_CERT); + request.addRequestedAttribute(ARL); + if (prefetchCRLs) { + request.addRequestedAttribute(CRL); + } + try { + entryCRLs = getCRLs(request, ARL, xsel); + if (entryCRLs.isEmpty()) { + // no ARLs found. We assume that means that there are + // no ARLs on this server at all and prefetch the CRLs. + prefetchCRLs = true; + } else { + crls.addAll(entryCRLs); + } + } catch (CertStoreException e) { + if (debug != null) { + debug.println("LDAPCertStore.engineGetCRLs non-fatal error " + + "retrieving ARLs:" + e); + e.printStackTrace(); + } + } + } + // Otherwise, get the CRL + // if certChecking is null, we don't know if we should look in ARL or CRL + // attribute, so check both for matching CRLs. + if (entryCRLs.isEmpty() || certChecking == null) { + LDAPRequest request = new LDAPRequest(issuerName); + request.addRequestedAttribute(CRL); + entryCRLs = getCRLs(request, CRL, xsel); + crls.addAll(entryCRLs); + } + } + return crls; + } +} diff --git a/jdk/test/java/lang/SecurityManager/CheckSecurityProvider.java b/jdk/test/java/lang/SecurityManager/CheckSecurityProvider.java index 0e64edc4ead..00dbcabe372 100644 --- a/jdk/test/java/lang/SecurityManager/CheckSecurityProvider.java +++ b/jdk/test/java/lang/SecurityManager/CheckSecurityProvider.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -67,6 +67,7 @@ public class CheckSecurityProvider { expected.add("com.sun.security.sasl.Provider"); expected.add("org.jcp.xml.dsig.internal.dom.XMLDSigRI"); expected.add("sun.security.smartcardio.SunPCSC"); + expected.add("sun.security.provider.certpath.ldap.JdkLDAP"); if (os.startsWith("Windows")) { expected.add("sun.security.mscapi.SunMSCAPI"); } diff --git a/jdk/test/java/security/cert/URICertStoreParameters/TestBasic.java b/jdk/test/java/security/cert/URICertStoreParameters/TestBasic.java new file mode 100644 index 00000000000..ed96d32a5c7 --- /dev/null +++ b/jdk/test/java/security/cert/URICertStoreParameters/TestBasic.java @@ -0,0 +1,71 @@ +/* + * Copyright (c) 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.cert.CertStore; +import java.security.cert.URICertStoreParameters; +import java.net.URI; + +/* + * @test + * @bug 8038084 + * @summary Basic testing for URICertStoreParameters + * @run main TestBasic + */ +public class TestBasic { + + public static void main(String[] args) throws Exception { + String str1 = "ldap://myownhost:5000/"; + String str2 = "ldap://myownhost:5000/cn=foo"; + test(str1, str2); + System.out.println("Test passed"); + } + + private static void test(String str1, String str2) throws Exception { + System.out.println("Testing clone"); + URICertStoreParameters p1 = new URICertStoreParameters(new URI(str1)); + URICertStoreParameters p1Too = p1.clone(); + if (!(p1.getURI().equals(p1Too.getURI())) || + !(p1.equals(p1Too))) { + throw new Exception("Error: problem with clone"); + } + System.out.println("Testing equal and hashCode"); + p1Too = new URICertStoreParameters(new URI(str1)); + URICertStoreParameters p2 = new URICertStoreParameters(new URI(str2)); + + if (p1.equals(null)) { + throw new Exception("Error: p1 should NOT equal null"); + } + if ((!p1.equals(p1)) || (p1.hashCode() != p1.hashCode())) { + throw new Exception("Error: p1 should equal p1"); + } + if ((!p1.equals(p1Too)) || (p1.hashCode() != p1Too.hashCode())) { + throw new Exception("Error: p1 should equal p1Too"); + } + if ((!p1Too.equals(p1)) || (p1Too.hashCode() != p1.hashCode())) { + throw new Exception("Error: p1Too should equal p1"); + } + if (p1.equals(p2) || p1Too.equals(p2)) { + throw new Exception("Error: p1/p1Too should NOT equal p2"); + } + } +} From 77a753da21c80a0a267de597c28bf1f25f32be33 Mon Sep 17 00:00:00 2001 From: "J. Duke" Date: Wed, 5 Jul 2017 20:32:49 +0200 Subject: [PATCH 36/70] Added tag jdk9-b64 for changeset 8ffdeabc7c2b --- .hgtags | 1 + 1 file changed, 1 insertion(+) diff --git a/.hgtags b/.hgtags index 71adccced6a..b21995364ae 100644 --- a/.hgtags +++ b/.hgtags @@ -306,3 +306,4 @@ da950f343762a856d69751570a4c07cfa68a415b jdk9-b59 ac3f5a39d4ff14d70c365e12cf5ec8f2abd52a04 jdk9-b61 e7dbbef69d12b6a74dfad331b7188e7f893e8d29 jdk9-b62 989253a902c34dcb7564695161c9200a5fbb7412 jdk9-b63 +8ffdeabc7c2b9a8280bf46cae026ac46b4d31c26 jdk9-b64 From 608c2ef4961cb561fb9b21b8122a13b1f126d11c Mon Sep 17 00:00:00 2001 From: Claes Redestad Date: Fri, 15 May 2015 16:09:55 +0200 Subject: [PATCH 37/70] 8061254: SPECjvm2008-XML performance regressions in 9-b33 Reviewed-by: alanb, shade --- jdk/src/java.base/share/classes/java/lang/String.java | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/jdk/src/java.base/share/classes/java/lang/String.java b/jdk/src/java.base/share/classes/java/lang/String.java index bd39fa60f94..f11292f2cda 100644 --- a/jdk/src/java.base/share/classes/java/lang/String.java +++ b/jdk/src/java.base/share/classes/java/lang/String.java @@ -1473,7 +1473,9 @@ public final class String for (char v : value) { h = 31 * h + v; } - hash = h; + if (h != 0) { + hash = h; + } } return h; } From ff06dffa94f5227eeca391b9d25ec6199626274c Mon Sep 17 00:00:00 2001 From: Ivan Gerasimov Date: Fri, 15 May 2015 22:09:49 +0300 Subject: [PATCH 38/70] 8074657: Missing space on a boundary of concatenated strings Added missing spaces, fixed indentation, replaced StringBuffer with StringBuilder Reviewed-by: martin, rriggs --- .../java/util/prefs/WindowsPreferences.java | 415 +++++++++--------- .../javax/sql/rowset/serial/SerialBlob.java | 77 ++-- 2 files changed, 257 insertions(+), 235 deletions(-) diff --git a/jdk/src/java.prefs/windows/classes/java/util/prefs/WindowsPreferences.java b/jdk/src/java.prefs/windows/classes/java/util/prefs/WindowsPreferences.java index ec5b492ba9d..63dfcfb166e 100644 --- a/jdk/src/java.prefs/windows/classes/java/util/prefs/WindowsPreferences.java +++ b/jdk/src/java.prefs/windows/classes/java/util/prefs/WindowsPreferences.java @@ -62,8 +62,8 @@ class WindowsPreferences extends AbstractPreferences { /** * Windows registry path to Preferences's root nodes. */ - private static final byte[] WINDOWS_ROOT_PATH - = stringToByteArray("Software\\JavaSoft\\Prefs"); + private static final byte[] WINDOWS_ROOT_PATH = + stringToByteArray("Software\\JavaSoft\\Prefs"); /** * Windows handles to HKEY_CURRENT_USER and @@ -147,12 +147,12 @@ class WindowsPreferences extends AbstractPreferences { * Java wrapper for Windows registry API RegOpenKey() */ private static native int[] WindowsRegOpenKey(int hKey, byte[] subKey, - int securityMask); + int securityMask); /** * Retries RegOpenKey() MAX_ATTEMPTS times before giving up. */ private static int[] WindowsRegOpenKey1(int hKey, byte[] subKey, - int securityMask) { + int securityMask) { int[] result = WindowsRegOpenKey(hKey, subKey, securityMask); if (result[ERROR_CODE] == ERROR_SUCCESS) { return result; @@ -167,16 +167,16 @@ class WindowsPreferences extends AbstractPreferences { } else if (result[ERROR_CODE] != ERROR_ACCESS_DENIED) { long sleepTime = INIT_SLEEP_TIME; for (int i = 0; i < MAX_ATTEMPTS; i++) { - try { - Thread.sleep(sleepTime); - } catch(InterruptedException e) { - return result; - } - sleepTime *= 2; - result = WindowsRegOpenKey(hKey, subKey, securityMask); - if (result[ERROR_CODE] == ERROR_SUCCESS) { - return result; - } + try { + Thread.sleep(sleepTime); + } catch(InterruptedException e) { + return result; + } + sleepTime *= 2; + result = WindowsRegOpenKey(hKey, subKey, securityMask); + if (result[ERROR_CODE] == ERROR_SUCCESS) { + return result; + } } } return result; @@ -198,10 +198,10 @@ class WindowsPreferences extends AbstractPreferences { private static int[] WindowsRegCreateKeyEx1(int hKey, byte[] subKey) { int[] result = WindowsRegCreateKeyEx(hKey, subKey); if (result[ERROR_CODE] == ERROR_SUCCESS) { - return result; - } else { - long sleepTime = INIT_SLEEP_TIME; - for (int i = 0; i < MAX_ATTEMPTS; i++) { + return result; + } else { + long sleepTime = INIT_SLEEP_TIME; + for (int i = 0; i < MAX_ATTEMPTS; i++) { try { Thread.sleep(sleepTime); } catch(InterruptedException e) { @@ -210,7 +210,7 @@ class WindowsPreferences extends AbstractPreferences { sleepTime *= 2; result = WindowsRegCreateKeyEx(hKey, subKey); if (result[ERROR_CODE] == ERROR_SUCCESS) { - return result; + return result; } } } @@ -232,10 +232,10 @@ class WindowsPreferences extends AbstractPreferences { private static int WindowsRegFlushKey1(int hKey) { int result = WindowsRegFlushKey(hKey); if (result == ERROR_SUCCESS) { - return result; - } else { - long sleepTime = INIT_SLEEP_TIME; - for (int i = 0; i < MAX_ATTEMPTS; i++) { + return result; + } else { + long sleepTime = INIT_SLEEP_TIME; + for (int i = 0; i < MAX_ATTEMPTS; i++) { try { Thread.sleep(sleepTime); } catch(InterruptedException e) { @@ -244,7 +244,7 @@ class WindowsPreferences extends AbstractPreferences { sleepTime *= 2; result = WindowsRegFlushKey(hKey); if (result == ERROR_SUCCESS) { - return result; + return result; } } } @@ -255,23 +255,23 @@ class WindowsPreferences extends AbstractPreferences { * Java wrapper for Windows registry API RegQueryValueEx() */ private static native byte[] WindowsRegQueryValueEx(int hKey, - byte[] valueName); + byte[] valueName); /** * Java wrapper for Windows registry API RegSetValueEx() */ private static native int WindowsRegSetValueEx(int hKey, byte[] valueName, - byte[] value); + byte[] value); /** * Retries RegSetValueEx() MAX_ATTEMPTS times before giving up. */ private static int WindowsRegSetValueEx1(int hKey, byte[] valueName, - byte[] value) { + byte[] value) { int result = WindowsRegSetValueEx(hKey, valueName, value); if (result == ERROR_SUCCESS) { - return result; - } else { - long sleepTime = INIT_SLEEP_TIME; - for (int i = 0; i < MAX_ATTEMPTS; i++) { + return result; + } else { + long sleepTime = INIT_SLEEP_TIME; + for (int i = 0; i < MAX_ATTEMPTS; i++) { try { Thread.sleep(sleepTime); } catch(InterruptedException e) { @@ -280,7 +280,7 @@ class WindowsPreferences extends AbstractPreferences { sleepTime *= 2; result = WindowsRegSetValueEx(hKey, valueName, value); if (result == ERROR_SUCCESS) { - return result; + return result; } } } @@ -303,10 +303,10 @@ class WindowsPreferences extends AbstractPreferences { private static int[] WindowsRegQueryInfoKey1(int hKey) { int[] result = WindowsRegQueryInfoKey(hKey); if (result[ERROR_CODE] == ERROR_SUCCESS) { - return result; - } else { - long sleepTime = INIT_SLEEP_TIME; - for (int i = 0; i < MAX_ATTEMPTS; i++) { + return result; + } else { + long sleepTime = INIT_SLEEP_TIME; + for (int i = 0; i < MAX_ATTEMPTS; i++) { try { Thread.sleep(sleepTime); } catch(InterruptedException e) { @@ -315,7 +315,7 @@ class WindowsPreferences extends AbstractPreferences { sleepTime *= 2; result = WindowsRegQueryInfoKey(hKey); if (result[ERROR_CODE] == ERROR_SUCCESS) { - return result; + return result; } } } @@ -326,19 +326,19 @@ class WindowsPreferences extends AbstractPreferences { * Java wrapper for Windows registry API RegEnumKeyEx() */ private static native byte[] WindowsRegEnumKeyEx(int hKey, int subKeyIndex, - int maxKeyLength); + int maxKeyLength); /** * Retries RegEnumKeyEx() MAX_ATTEMPTS times before giving up. */ private static byte[] WindowsRegEnumKeyEx1(int hKey, int subKeyIndex, - int maxKeyLength) { + int maxKeyLength) { byte[] result = WindowsRegEnumKeyEx(hKey, subKeyIndex, maxKeyLength); if (result != null) { - return result; - } else { - long sleepTime = INIT_SLEEP_TIME; - for (int i = 0; i < MAX_ATTEMPTS; i++) { + return result; + } else { + long sleepTime = INIT_SLEEP_TIME; + for (int i = 0; i < MAX_ATTEMPTS; i++) { try { Thread.sleep(sleepTime); } catch(InterruptedException e) { @@ -347,7 +347,7 @@ class WindowsPreferences extends AbstractPreferences { sleepTime *= 2; result = WindowsRegEnumKeyEx(hKey, subKeyIndex, maxKeyLength); if (result != null) { - return result; + return result; } } } @@ -358,19 +358,19 @@ class WindowsPreferences extends AbstractPreferences { * Java wrapper for Windows registry API RegEnumValue() */ private static native byte[] WindowsRegEnumValue(int hKey, int valueIndex, - int maxValueNameLength); + int maxValueNameLength); /** * Retries RegEnumValueEx() MAX_ATTEMPTS times before giving up. */ private static byte[] WindowsRegEnumValue1(int hKey, int valueIndex, - int maxValueNameLength) { + int maxValueNameLength) { byte[] result = WindowsRegEnumValue(hKey, valueIndex, - maxValueNameLength); + maxValueNameLength); if (result != null) { - return result; - } else { - long sleepTime = INIT_SLEEP_TIME; - for (int i = 0; i < MAX_ATTEMPTS; i++) { + return result; + } else { + long sleepTime = INIT_SLEEP_TIME; + for (int i = 0; i < MAX_ATTEMPTS; i++) { try { Thread.sleep(sleepTime); } catch(InterruptedException e) { @@ -378,9 +378,9 @@ class WindowsPreferences extends AbstractPreferences { } sleepTime *= 2; result = WindowsRegEnumValue(hKey, valueIndex, - maxValueNameLength); + maxValueNameLength); if (result != null) { - return result; + return result; } } } @@ -404,11 +404,11 @@ class WindowsPreferences extends AbstractPreferences { int[] result = WindowsRegCreateKeyEx1(parentNativeHandle, toWindowsName(name)); if (result[ERROR_CODE] != ERROR_SUCCESS) { - logger().warning("Could not create windows registry " - + "node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + - ". Windows RegCreateKeyEx(...) returned error code " + - result[ERROR_CODE] + "."); + logger().warning("Could not create windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + Integer.toHexString(rootNativeHandle()) + + ". Windows RegCreateKeyEx(...) returned error code " + + result[ERROR_CODE] + "."); isBackingStoreAvailable = false; return; } @@ -426,15 +426,15 @@ class WindowsPreferences extends AbstractPreferences { * @param rootDirectory Path to root directory, as a byte-encoded string. */ private WindowsPreferences(int rootNativeHandle, byte[] rootDirectory) { - super(null,""); + super(null, ""); int[] result = WindowsRegCreateKeyEx1(rootNativeHandle, rootDirectory); if (result[ERROR_CODE] != ERROR_SUCCESS) { logger().warning("Could not open/create prefs root node " + - byteArrayToString(windowsAbsolutePath()) + " at root 0x" + - Integer.toHexString(rootNativeHandle()) + - ". Windows RegCreateKeyEx(...) returned error code " + - result[ERROR_CODE] + "."); + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + Integer.toHexString(rootNativeHandle()) + + ". Windows RegCreateKeyEx(...) returned error code " + + result[ERROR_CODE] + "."); isBackingStoreAvailable = false; return; } @@ -451,7 +451,7 @@ class WindowsPreferences extends AbstractPreferences { private byte[] windowsAbsolutePath() { ByteArrayOutputStream bstream = new ByteArrayOutputStream(); bstream.write(WINDOWS_ROOT_PATH, 0, WINDOWS_ROOT_PATH.length-1); - StringTokenizer tokenizer = new StringTokenizer(absolutePath(),"/"); + StringTokenizer tokenizer = new StringTokenizer(absolutePath(), "/"); while (tokenizer.hasMoreTokens()) { bstream.write((byte)'\\'); String nextName = tokenizer.nextToken(); @@ -505,27 +505,30 @@ class WindowsPreferences extends AbstractPreferences { /* Check if key's path is short enough be opened at once otherwise use a path-splitting procedure */ if (windowsAbsolutePath.length <= MAX_WINDOWS_PATH_LENGTH + 1) { - int[] result = WindowsRegOpenKey1(rootNativeHandle(), - windowsAbsolutePath, mask1); - if (result[ERROR_CODE] == ERROR_ACCESS_DENIED && mask2 != mask1) - result = WindowsRegOpenKey1(rootNativeHandle(), - windowsAbsolutePath, mask2); + int[] result = WindowsRegOpenKey1(rootNativeHandle(), + windowsAbsolutePath, mask1); + if (result[ERROR_CODE] == ERROR_ACCESS_DENIED && mask2 != mask1) + result = WindowsRegOpenKey1(rootNativeHandle(), + windowsAbsolutePath, mask2); - if (result[ERROR_CODE] != ERROR_SUCCESS) { - logger().warning("Could not open windows " - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + - ". Windows RegOpenKey(...) returned error code " + - result[ERROR_CODE] + "."); + if (result[ERROR_CODE] != ERROR_SUCCESS) { + logger().warning("Could not open windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + + ". Windows RegOpenKey(...) returned error code " + + result[ERROR_CODE] + "."); result[NATIVE_HANDLE] = NULL_NATIVE_HANDLE; if (result[ERROR_CODE] == ERROR_ACCESS_DENIED) { - throw new SecurityException("Could not open windows " - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + - ": Access denied"); + throw new SecurityException( + "Could not open windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + + ": Access denied"); } - } - return result[NATIVE_HANDLE]; + } + return result[NATIVE_HANDLE]; } else { return openKey(rootNativeHandle(), windowsAbsolutePath, mask1, mask2); } @@ -548,21 +551,21 @@ class WindowsPreferences extends AbstractPreferences { int mask1, int mask2) { /* If the path is short enough open at once. Otherwise split the path */ if (windowsRelativePath.length <= MAX_WINDOWS_PATH_LENGTH + 1 ) { - int[] result = WindowsRegOpenKey1(nativeHandle, - windowsRelativePath, mask1); - if (result[ERROR_CODE] == ERROR_ACCESS_DENIED && mask2 != mask1) - result = WindowsRegOpenKey1(nativeHandle, - windowsRelativePath, mask2); + int[] result = WindowsRegOpenKey1(nativeHandle, + windowsRelativePath, mask1); + if (result[ERROR_CODE] == ERROR_ACCESS_DENIED && mask2 != mask1) + result = WindowsRegOpenKey1(nativeHandle, + windowsRelativePath, mask2); - if (result[ERROR_CODE] != ERROR_SUCCESS) { - logger().warning("Could not open windows " - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(nativeHandle) + - ". Windows RegOpenKey(...) returned error code " + - result[ERROR_CODE] + "."); + if (result[ERROR_CODE] != ERROR_SUCCESS) { + logger().warning("Could not open windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + Integer.toHexString(nativeHandle) + + ". Windows RegOpenKey(...) returned error code " + + result[ERROR_CODE] + "."); result[NATIVE_HANDLE] = NULL_NATIVE_HANDLE; - } - return result[NATIVE_HANDLE]; + } + return result[NATIVE_HANDLE]; } else { int separatorPosition = -1; // Be greedy - open the longest possible path @@ -604,10 +607,12 @@ class WindowsPreferences extends AbstractPreferences { private void closeKey(int nativeHandle) { int result = WindowsRegCloseKey(nativeHandle); if (result != ERROR_SUCCESS) { - logger().warning("Could not close windows " - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + - ". Windows RegCloseKey(...) returned error code " + result + "."); + logger().warning("Could not close windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + + ". Windows RegCloseKey(...) returned error code " + + result + "."); } } @@ -627,10 +632,13 @@ class WindowsPreferences extends AbstractPreferences { toWindowsName(javaName), toWindowsValueString(value)); if (result != ERROR_SUCCESS) { logger().warning("Could not assign value to key " + - byteArrayToString(toWindowsName(javaName))+ " at Windows registry node " - + byteArrayToString(windowsAbsolutePath()) + " at root 0x" - + Integer.toHexString(rootNativeHandle()) + - ". Windows RegSetValueEx(...) returned error code " + result + "."); + byteArrayToString(toWindowsName(javaName)) + + " at Windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + + ". Windows RegSetValueEx(...) returned error code " + + result + "."); isBackingStoreAvailable = false; } closeKey(nativeHandle); @@ -672,12 +680,12 @@ class WindowsPreferences extends AbstractPreferences { int result = WindowsRegDeleteValue(nativeHandle, toWindowsName(key)); if (result != ERROR_SUCCESS && result != ERROR_FILE_NOT_FOUND) { - logger().warning("Could not delete windows registry " - + "value " + byteArrayToString(windowsAbsolutePath())+ "\\" + - toWindowsName(key) + " at root 0x" + - Integer.toHexString(rootNativeHandle()) + - ". Windows RegDeleteValue(...) returned error code " + - result + "."); + logger().warning("Could not delete windows registry value " + + byteArrayToString(windowsAbsolutePath()) + "\\" + + toWindowsName(key) + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + + ". Windows RegDeleteValue(...) returned error code " + + result + "."); isBackingStoreAvailable = false; } closeKey(nativeHandle); @@ -693,17 +701,20 @@ class WindowsPreferences extends AbstractPreferences { // Find out the number of values int nativeHandle = openKey(KEY_QUERY_VALUE); if (nativeHandle == NULL_NATIVE_HANDLE) { - throw new BackingStoreException("Could not open windows" - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + "."); + throw new BackingStoreException( + "Could not open windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + "."); } int[] result = WindowsRegQueryInfoKey1(nativeHandle); if (result[ERROR_CODE] != ERROR_SUCCESS) { - String info = "Could not query windows" - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + - ". Windows RegQueryInfoKeyEx(...) returned error code " + - result[ERROR_CODE] + "."; + String info = "Could not query windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + + ". Windows RegQueryInfoKeyEx(...) returned error code " + + result[ERROR_CODE] + "."; logger().warning(info); throw new BackingStoreException(info); } @@ -712,17 +723,17 @@ class WindowsPreferences extends AbstractPreferences { if (valuesNumber == 0) { closeKey(nativeHandle); return new String[0]; - } - // Get the values - String[] valueNames = new String[valuesNumber]; - for (int i = 0; i < valuesNumber; i++) { + } + // Get the values + String[] valueNames = new String[valuesNumber]; + for (int i = 0; i < valuesNumber; i++) { byte[] windowsName = WindowsRegEnumValue1(nativeHandle, i, - maxValueNameLength+1); + maxValueNameLength+1); if (windowsName == null) { String info = - "Could not enumerate value #" + i + " of windows node " + - byteArrayToString(windowsAbsolutePath()) + " at root 0x" + - Integer.toHexString(rootNativeHandle()) + "."; + "Could not enumerate value #" + i + " of windows node " + + byteArrayToString(windowsAbsolutePath()) + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + "."; logger().warning(info); throw new BackingStoreException(info); } @@ -740,20 +751,22 @@ class WindowsPreferences extends AbstractPreferences { */ protected String[] childrenNamesSpi() throws BackingStoreException { // Open key - int nativeHandle = openKey(KEY_ENUMERATE_SUB_KEYS| KEY_QUERY_VALUE); + int nativeHandle = openKey(KEY_ENUMERATE_SUB_KEYS | KEY_QUERY_VALUE); if (nativeHandle == NULL_NATIVE_HANDLE) { - throw new BackingStoreException("Could not open windows" - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + "."); + throw new BackingStoreException( + "Could not open windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + "."); } // Get number of children int[] result = WindowsRegQueryInfoKey1(nativeHandle); if (result[ERROR_CODE] != ERROR_SUCCESS) { - String info = "Could not query windows" - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + - ". Windows RegQueryInfoKeyEx(...) returned error code " + - result[ERROR_CODE] + "."; + String info = "Could not query windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + Integer.toHexString(rootNativeHandle()) + + ". Windows RegQueryInfoKeyEx(...) returned error code " + + result[ERROR_CODE] + "."; logger().warning(info); throw new BackingStoreException(info); } @@ -768,12 +781,12 @@ class WindowsPreferences extends AbstractPreferences { // Get children for (int i = 0; i < subKeysNumber; i++) { byte[] windowsName = WindowsRegEnumKeyEx1(nativeHandle, i, - maxKeyLength+1); + maxKeyLength+1); if (windowsName == null) { String info = - "Could not enumerate key #" + i + " of windows node " + - byteArrayToString(windowsAbsolutePath()) + " at root 0x" + - Integer.toHexString(rootNativeHandle()) + ". "; + "Could not enumerate key #" + i + " of windows node " + + byteArrayToString(windowsAbsolutePath()) + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + ". "; logger().warning(info); throw new BackingStoreException(info); } @@ -798,20 +811,24 @@ class WindowsPreferences extends AbstractPreferences { } if (!isBackingStoreAvailable) { throw new BackingStoreException( - "flush(): Backing store not available."); + "flush(): Backing store not available."); } int nativeHandle = openKey(KEY_READ); if (nativeHandle == NULL_NATIVE_HANDLE) { - throw new BackingStoreException("Could not open windows" - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + "."); + throw new BackingStoreException( + "Could not open windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + "."); } int result = WindowsRegFlushKey1(nativeHandle); if (result != ERROR_SUCCESS) { - String info = "Could not flush windows " - + "registry node " + byteArrayToString(windowsAbsolutePath()) - + " at root 0x" + Integer.toHexString(rootNativeHandle()) + - ". Windows RegFlushKey(...) returned error code " + result + "."; + String info = "Could not flush windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + + ". Windows RegFlushKey(...) returned error code " + + result + "."; logger().warning(info); throw new BackingStoreException(info); } @@ -838,7 +855,7 @@ class WindowsPreferences extends AbstractPreferences { * Logs a warning message, if Windows Registry is unavailable. */ protected AbstractPreferences childSpi(String name) { - return new WindowsPreferences(this, name); + return new WindowsPreferences(this, name); } /** @@ -849,20 +866,22 @@ class WindowsPreferences extends AbstractPreferences { */ public void removeNodeSpi() throws BackingStoreException { int parentNativeHandle = - ((WindowsPreferences)parent()).openKey(DELETE); + ((WindowsPreferences)parent()).openKey(DELETE); if (parentNativeHandle == NULL_NATIVE_HANDLE) { - throw new BackingStoreException("Could not open parent windows" - + "registry node of " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + "."); + throw new BackingStoreException( + "Could not open parent windows registry node of " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + + Integer.toHexString(rootNativeHandle()) + "."); } int result = WindowsRegDeleteKey(parentNativeHandle, toWindowsName(name())); if (result != ERROR_SUCCESS) { - String info = "Could not delete windows " - + "registry node " + byteArrayToString(windowsAbsolutePath()) + - " at root 0x" + Integer.toHexString(rootNativeHandle()) + - ". Windows RegDeleteKeyEx(...) returned error code " + - result + "."; + String info = "Could not delete windows registry node " + + byteArrayToString(windowsAbsolutePath()) + + " at root 0x" + Integer.toHexString(rootNativeHandle()) + + ". Windows RegDeleteKeyEx(...) returned error code " + + result + "."; logger().warning(info); throw new BackingStoreException(info); } @@ -879,23 +898,25 @@ class WindowsPreferences extends AbstractPreferences { private static String toJavaName(byte[] windowsNameArray) { String windowsName = byteArrayToString(windowsNameArray); // check if Alt64 - if ((windowsName.length()>1) && - (windowsName.substring(0,2).equals("/!"))) { + if ((windowsName.length() > 1) && + (windowsName.substring(0, 2).equals("/!"))) { return toJavaAlt64Name(windowsName); } - StringBuffer javaName = new StringBuffer(); + StringBuilder javaName = new StringBuilder(); char ch; // Decode from simple encoding - for (int i = 0; i < windowsName.length(); i++){ + for (int i = 0; i < windowsName.length(); i++) { if ((ch = windowsName.charAt(i)) == '/') { char next = ' '; if ((windowsName.length() > i + 1) && - ((next = windowsName.charAt(i+1)) >= 'A') && (next <= 'Z')) { - ch = next; - i++; - } else if ((windowsName.length() > i + 1) && (next == '/')) { - ch = '\\'; - i++; + ((next = windowsName.charAt(i+1)) >= 'A') && + (next <= 'Z')) { + ch = next; + i++; + } else if ((windowsName.length() > i + 1) && + (next == '/')) { + ch = '\\'; + i++; } } else if (ch == '\\') { ch = '/'; @@ -914,8 +935,8 @@ class WindowsPreferences extends AbstractPreferences { private static String toJavaAlt64Name(String windowsName) { byte[] byteBuffer = - Base64.altBase64ToByteArray(windowsName.substring(2)); - StringBuffer result = new StringBuffer(); + Base64.altBase64ToByteArray(windowsName.substring(2)); + StringBuilder result = new StringBuilder(); for (int i = 0; i < byteBuffer.length; i++) { int firstbyte = (byteBuffer[i++] & 0xff); int secondbyte = (byteBuffer[i] & 0xff); @@ -945,10 +966,10 @@ class WindowsPreferences extends AbstractPreferences { * Base64 class. */ private static byte[] toWindowsName(String javaName) { - StringBuffer windowsName = new StringBuffer(); + StringBuilder windowsName = new StringBuilder(); for (int i = 0; i < javaName.length(); i++) { - char ch =javaName.charAt(i); - if ((ch < 0x0020)||(ch > 0x007f)) { + char ch = javaName.charAt(i); + if ((ch < 0x0020) || (ch > 0x007f)) { // If a non-trivial character encountered, use altBase64 return toWindowsAlt64Name(javaName); } @@ -957,7 +978,7 @@ class WindowsPreferences extends AbstractPreferences { } else if (ch == '/') { windowsName.append('\\'); } else if ((ch >= 'A') && (ch <='Z')) { - windowsName.append("/" + ch); + windowsName.append('/').append(ch); } else { windowsName.append(ch); } @@ -976,13 +997,13 @@ class WindowsPreferences extends AbstractPreferences { // Convert to byte pairs int counter = 0; for (int i = 0; i < javaName.length();i++) { - int ch = javaName.charAt(i); - javaNameArray[counter++] = (byte)(ch >>> 8); - javaNameArray[counter++] = (byte)ch; + int ch = javaName.charAt(i); + javaNameArray[counter++] = (byte)(ch >>> 8); + javaNameArray[counter++] = (byte)ch; } - return stringToByteArray( - "/!" + Base64.byteArrayToAltBase64(javaNameArray)); + return stringToByteArray("/!" + + Base64.byteArrayToAltBase64(javaNameArray)); } /** @@ -994,30 +1015,31 @@ class WindowsPreferences extends AbstractPreferences { private static String toJavaValueString(byte[] windowsNameArray) { // Use modified native2ascii algorithm String windowsName = byteArrayToString(windowsNameArray); - StringBuffer javaName = new StringBuffer(); + StringBuilder javaName = new StringBuilder(); char ch; for (int i = 0; i < windowsName.length(); i++){ if ((ch = windowsName.charAt(i)) == '/') { char next = ' '; if (windowsName.length() > i + 1 && - (next = windowsName.charAt(i + 1)) == 'u') { - if (windowsName.length() < i + 6){ + (next = windowsName.charAt(i + 1)) == 'u') { + if (windowsName.length() < i + 6) { break; } else { - ch = (char)Integer.parseInt - (windowsName.substring(i + 2, i + 6), 16); + ch = (char)Integer.parseInt( + windowsName.substring(i + 2, i + 6), 16); i += 5; } } else if ((windowsName.length() > i + 1) && - ((windowsName.charAt(i+1)) >= 'A') && (next <= 'Z')) { - ch = next; - i++; - } else if ((windowsName.length() > i + 1) && - (next == '/')) { - ch = '\\'; - i++; + ((windowsName.charAt(i+1)) >= 'A') && + (next <= 'Z')) { + ch = next; + i++; + } else if ((windowsName.length() > i + 1) && + (next == '/')) { + ch = '\\'; + i++; } } else if (ch == '\\') { ch = '/'; @@ -1037,14 +1059,14 @@ class WindowsPreferences extends AbstractPreferences { * to convert java string to a byte array of ASCII characters. */ private static byte[] toWindowsValueString(String javaName) { - StringBuffer windowsName = new StringBuffer(); + StringBuilder windowsName = new StringBuilder(); for (int i = 0; i < javaName.length(); i++) { - char ch =javaName.charAt(i); - if ((ch < 0x0020)||(ch > 0x007f)){ + char ch = javaName.charAt(i); + if ((ch < 0x0020) || (ch > 0x007f)){ // write \udddd windowsName.append("/u"); String hex = Integer.toHexString(javaName.charAt(i)); - StringBuffer hex4 = new StringBuffer(hex); + StringBuilder hex4 = new StringBuilder(hex); hex4.reverse(); int len = 4 - hex4.length(); for (int j = 0; j < len; j++){ @@ -1058,7 +1080,7 @@ class WindowsPreferences extends AbstractPreferences { } else if (ch == '/') { windowsName.append('\\'); } else if ((ch >= 'A') && (ch <='Z')) { - windowsName.append("/" + ch); + windowsName.append('/').append(ch); } else { windowsName.append(ch); } @@ -1070,8 +1092,9 @@ class WindowsPreferences extends AbstractPreferences { * Returns native handle for the top Windows node for this node. */ private int rootNativeHandle() { - return (isUserNode()? USER_ROOT_NATIVE_HANDLE : - SYSTEM_ROOT_NATIVE_HANDLE); + return (isUserNode() + ? USER_ROOT_NATIVE_HANDLE + : SYSTEM_ROOT_NATIVE_HANDLE); } /** @@ -1090,7 +1113,7 @@ class WindowsPreferences extends AbstractPreferences { * Converts a null-terminated byte array to java string */ private static String byteArrayToString(byte[] array) { - StringBuffer result = new StringBuffer(); + StringBuilder result = new StringBuilder(); for (int i = 0; i < array.length - 1; i++) { result.append((char)array[i]); } diff --git a/jdk/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java b/jdk/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java index abdfc58d880..dfdd48ce55d 100644 --- a/jdk/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java +++ b/jdk/src/java.sql.rowset/share/classes/javax/sql/rowset/serial/SerialBlob.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -67,7 +67,7 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * value of this SerialBlob object. * @serial */ - private byte buf[]; + private byte[] buf; /** * The internal representation of the Blob object on which this @@ -103,12 +103,13 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * @throws SerialException if an error occurs during serialization * @throws SQLException if a SQL errors occurs */ - public SerialBlob(byte[] b) throws SerialException, SQLException { + public SerialBlob(byte[] b) + throws SerialException, SQLException { len = b.length; buf = new byte[(int)len]; for(int i = 0; i < len; i++) { - buf[i] = b[i]; + buf[i] = b[i]; } origLen = len; } @@ -133,19 +134,17 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * to this constructor is a null. * @see java.sql.Blob */ - public SerialBlob (Blob blob) throws SerialException, SQLException { + public SerialBlob (Blob blob) + throws SerialException, SQLException { if (blob == null) { - throw new SQLException("Cannot instantiate a SerialBlob " + - "object with a null Blob object"); + throw new SQLException( + "Cannot instantiate a SerialBlob object with a null Blob object"); } len = blob.length(); buf = blob.getBytes(1, (int)len ); this.blob = blob; - - //if ( len < 10240000) - // len = 10240000; origLen = len; } @@ -246,7 +245,8 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * value from the database */ public long position(byte[] pattern, long start) - throws SerialException, SQLException { + throws SerialException, SQLException { + isValid(); if (start < 1 || start > len) { return -1; @@ -291,7 +291,7 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * value from the database */ public long position(Blob pattern, long start) - throws SerialException, SQLException { + throws SerialException, SQLException { isValid(); return position(pattern.getBytes(1, (int)(pattern.length())), start); } @@ -317,8 +317,8 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * @see #getBytes */ public int setBytes(long pos, byte[] bytes) - throws SerialException, SQLException { - return (setBytes(pos, bytes, 0, bytes.length)); + throws SerialException, SQLException { + return setBytes(pos, bytes, 0, bytes.length); } /** @@ -353,7 +353,7 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * @see #getBytes */ public int setBytes(long pos, byte[] bytes, int offset, int length) - throws SerialException, SQLException { + throws SerialException, SQLException { isValid(); if (offset < 0 || offset > bytes.length) { @@ -370,7 +370,7 @@ public class SerialBlob implements Blob, Serializable, Cloneable { if ((length + offset) > bytes.length) { throw new SerialException("Invalid OffSet. Cannot have combined offset " + - "and length that is greater that the Blob buffer"); + "and length that is greater that the Blob buffer"); } int i = 0; @@ -403,7 +403,8 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * @see #getBinaryStream */ public java.io.OutputStream setBinaryStream(long pos) - throws SerialException, SQLException { + throws SerialException, SQLException { + isValid(); if (this.blob != null) { return this.blob.setBinaryStream(pos); @@ -426,17 +427,16 @@ public class SerialBlob implements Blob, Serializable, Cloneable { * if {@code free} had previously been called on this object */ public void truncate(long length) throws SerialException { - isValid(); if (length > len) { - throw new SerialException - ("Length more than what can be truncated"); + throw new SerialException( + "Length more than what can be truncated"); } else if((int)length == 0) { - buf = new byte[0]; - len = length; + buf = new byte[0]; + len = length; } else { - len = length; - buf = this.getBytes(1, (int)len); + len = length; + buf = this.getBytes(1, (int)len); } } @@ -467,8 +467,8 @@ public class SerialBlob implements Blob, Serializable, Cloneable { throw new SerialException("Invalid position in BLOB object set"); } if (length < 1 || length > len - pos + 1) { - throw new SerialException("length is < 1 or pos + length >" - + "total number of bytes"); + throw new SerialException( + "length is < 1 or pos + length > total number of bytes"); } return new ByteArrayInputStream(buf, (int) pos - 1, (int) length); } @@ -537,14 +537,13 @@ public class SerialBlob implements Blob, Serializable, Cloneable { public Object clone() { try { SerialBlob sb = (SerialBlob) super.clone(); - sb.buf = (buf != null) ? Arrays.copyOf(buf, (int)len) : null; + sb.buf = (buf != null) ? Arrays.copyOf(buf, (int)len) : null; sb.blob = null; return sb; } catch (CloneNotSupportedException ex) { // this shouldn't happen, since we are Cloneable throw new InternalError(); } - } /** @@ -555,15 +554,15 @@ public class SerialBlob implements Blob, Serializable, Cloneable { throws IOException, ClassNotFoundException { ObjectInputStream.GetField fields = s.readFields(); - byte[] tmp = (byte[])fields.get("buf", null); - if (tmp == null) - throw new InvalidObjectException("buf is null and should not be!"); - buf = tmp.clone(); - len = fields.get("len", 0L); - if (buf.length != len) - throw new InvalidObjectException("buf is not the expected size"); - origLen = fields.get("origLen", 0L); - blob = (Blob) fields.get("blob", null); + byte[] tmp = (byte[])fields.get("buf", null); + if (tmp == null) + throw new InvalidObjectException("buf is null and should not be!"); + buf = tmp.clone(); + len = fields.get("len", 0L); + if (buf.length != len) + throw new InvalidObjectException("buf is not the expected size"); + origLen = fields.get("origLen", 0L); + blob = (Blob) fields.get("blob", null); } /** @@ -591,8 +590,8 @@ public class SerialBlob implements Blob, Serializable, Cloneable { */ private void isValid() throws SerialException { if (buf == null) { - throw new SerialException("Error: You cannot call a method on a " - + "SerialBlob instance once free() has been called."); + throw new SerialException("Error: You cannot call a method on a " + + "SerialBlob instance once free() has been called."); } } From cbe55b316ec3539145f3e781bb34bc2c8b5211fe Mon Sep 17 00:00:00 2001 From: Ivan Gerasimov Date: Fri, 15 May 2015 22:10:29 +0300 Subject: [PATCH 39/70] 8071571: Move substring of same string to slow path Reviewed-by: martin --- .../share/classes/java/lang/String.java | 119 +++++++++--------- 1 file changed, 61 insertions(+), 58 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/lang/String.java b/jdk/src/java.base/share/classes/java/lang/String.java index f11292f2cda..45ee5411def 100644 --- a/jdk/src/java.base/share/classes/java/lang/String.java +++ b/jdk/src/java.base/share/classes/java/lang/String.java @@ -179,7 +179,7 @@ public final class String * not affect the newly created string. * * @param value - * Array that is the source of characters + * Array that is the source of characters * * @param offset * The initial offset @@ -208,7 +208,7 @@ public final class String if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } - this.value = Arrays.copyOfRange(value, offset, offset+count); + this.value = Arrays.copyOfRange(value, offset, offset + count); } /** @@ -262,11 +262,11 @@ public final class String // Pass 1: Compute precise size of char[] int n = count; for (int i = offset; i < end; i++) { - int c = codePoints[i]; - if (Character.isBmpCodePoint(c)) - continue; - else if (Character.isValidCodePoint(c)) - n++; + int c = codePoints[i]; + if (Character.isBmpCodePoint(c)) + continue; + else if (Character.isValidCodePoint(c)) + n++; else throw new IllegalArgumentException(Integer.toString(c)); } @@ -327,7 +327,7 @@ public final class String @Deprecated public String(byte ascii[], int hibyte, int offset, int count) { checkBounds(ascii, offset, count); - char value[] = new char[count]; + char[] value = new char[count]; if (hibyte == 0) { for (int i = count; i-- > 0;) { @@ -465,7 +465,7 @@ public final class String if (charset == null) throw new NullPointerException("charset"); checkBounds(bytes, offset, length); - this.value = StringCoding.decode(charset, bytes, offset, length); + this.value = StringCoding.decode(charset, bytes, offset, length); } /** @@ -567,7 +567,7 @@ public final class String * * @since 1.1 */ - public String(byte bytes[]) { + public String(byte[] bytes) { this(bytes, 0, bytes.length); } @@ -983,11 +983,10 @@ public final class String return true; } if (anObject instanceof String) { - String anotherString = (String)anObject; - int n = value.length; - if (n == anotherString.value.length) { - char v1[] = value; - char v2[] = anotherString.value; + char[] v1 = value; + char[] v2 = ((String)anObject).value; + int n = v1.length; + if (n == v2.length) { int i = 0; while (n-- != 0) { if (v1[i] != v2[i]) @@ -1020,8 +1019,8 @@ public final class String } private boolean nonSyncContentEquals(AbstractStringBuilder sb) { - char v1[] = value; - char v2[] = sb.getValue(); + char[] v1 = value; + char[] v2 = sb.getValue(); int n = v1.length; if (n != sb.length()) { return false; @@ -1066,7 +1065,7 @@ public final class String return equals(cs); } // Argument is a generic CharSequence - char v1[] = value; + char[] v1 = value; int n = v1.length; if (n != cs.length()) { return false; @@ -1156,20 +1155,18 @@ public final class String * lexicographically greater than the string argument. */ public int compareTo(String anotherString) { - int len1 = value.length; - int len2 = anotherString.value.length; + char[] v1 = value; + char[] v2 = anotherString.value; + int len1 = v1.length; + int len2 = v2.length; int lim = Math.min(len1, len2); - char v1[] = value; - char v2[] = anotherString.value; - int k = 0; - while (k < lim) { + for (int k = 0; k < lim; k++) { char c1 = v1[k]; char c2 = v2[k]; if (c1 != c2) { return c1 - c2; } - k++; } return len1 - len2; } @@ -1278,14 +1275,14 @@ public final class String */ public boolean regionMatches(int toffset, String other, int ooffset, int len) { - char ta[] = value; + char[] ta = value; int to = toffset; - char pa[] = other.value; + char[] pa = other.value; int po = ooffset; // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) - || (toffset > (long)value.length - len) - || (ooffset > (long)other.value.length - len)) { + || (toffset > (long)ta.length - len) + || (ooffset > (long)pa.length - len)) { return false; } while (len-- > 0) { @@ -1348,14 +1345,14 @@ public final class String */ public boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) { - char ta[] = value; + char[] ta = value; int to = toffset; - char pa[] = other.value; + char[] pa = other.value; int po = ooffset; // Note: toffset, ooffset, or len might be near -1>>>1. if ((ooffset < 0) || (toffset < 0) - || (toffset > (long)value.length - len) - || (ooffset > (long)other.value.length - len)) { + || (toffset > (long)ta.length - len) + || (ooffset > (long)pa.length - len)) { return false; } while (len-- > 0) { @@ -1405,13 +1402,13 @@ public final class String * */ public boolean startsWith(String prefix, int toffset) { - char ta[] = value; + char[] ta = value; int to = toffset; - char pa[] = prefix.value; + char[] pa = prefix.value; int po = 0; - int pc = prefix.value.length; + int pc = pa.length; // Note: toffset might be near -1>>>1. - if ((toffset < 0) || (toffset > value.length - pc)) { + if ((toffset < 0) || (toffset > ta.length - pc)) { return false; } while (--pc >= 0) { @@ -1930,14 +1927,17 @@ public final class String * length of this {@code String} object. */ public String substring(int beginIndex) { - if (beginIndex < 0) { - throw new StringIndexOutOfBoundsException(beginIndex); + if (beginIndex <= 0) { + if (beginIndex < 0) { + throw new StringIndexOutOfBoundsException(beginIndex); + } + return this; } int subLen = value.length - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } - return (beginIndex == 0) ? this : new String(value, beginIndex, subLen); + return new String(value, beginIndex, subLen); } /** @@ -1963,8 +1963,13 @@ public final class String * {@code endIndex}. */ public String substring(int beginIndex, int endIndex) { - if (beginIndex < 0) { - throw new StringIndexOutOfBoundsException(beginIndex); + if (beginIndex <= 0) { + if (beginIndex < 0) { + throw new StringIndexOutOfBoundsException(beginIndex); + } + if (endIndex == value.length) { + return this; + } } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); @@ -1973,8 +1978,7 @@ public final class String if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } - return ((beginIndex == 0) && (endIndex == value.length)) ? this - : new String(value, beginIndex, subLen); + return new String(value, beginIndex, subLen); } /** @@ -2036,7 +2040,7 @@ public final class String return this; } int len = value.length; - char buf[] = Arrays.copyOf(value, len + otherLen); + char[] buf = Arrays.copyOf(value, len + otherLen); str.getChars(buf, len); return new String(buf, true); } @@ -2072,9 +2076,9 @@ public final class String */ public String replace(char oldChar, char newChar) { if (oldChar != newChar) { - int len = value.length; - int i = -1; char[] val = value; /* avoid getfield opcode */ + int len = val.length; + int i = -1; while (++i < len) { if (val[i] == oldChar) { @@ -2082,7 +2086,7 @@ public final class String } } if (i < len) { - char buf[] = new char[len]; + char[] buf = new char[len]; for (int j = 0; j < i; j++) { buf[j] = val[j]; } @@ -2878,17 +2882,17 @@ public final class String * trailing white space. */ public String trim() { - int len = value.length; - int st = 0; char[] val = value; /* avoid getfield opcode */ + int end = val.length; + int beg = 0; - while ((st < len) && (val[st] <= ' ')) { - st++; + while ((beg < end) && (val[beg] <= ' ')) { + beg++; } - while ((st < len) && (val[len - 1] <= ' ')) { - len--; + while ((beg < end) && (val[end - 1] <= ' ')) { + end--; } - return ((st > 0) || (len < value.length)) ? substring(st, len) : this; + return substring(beg, end); } /** @@ -3083,7 +3087,7 @@ public final class String */ public char[] toCharArray() { // Cannot use Arrays.copyOf because of class initialization order issues - char result[] = new char[value.length]; + char[] result = new char[value.length]; System.arraycopy(value, 0, result, 0, value.length); return result; } @@ -3268,8 +3272,7 @@ public final class String * as its single character the argument {@code c}. */ public static String valueOf(char c) { - char data[] = {c}; - return new String(data, true); + return new String(new char[]{c}, true); } /** From 30bcd97f8173c15991c4d706378d5a35ffe0529f Mon Sep 17 00:00:00 2001 From: Peter Levart Date: Sun, 17 May 2015 10:38:36 +0200 Subject: [PATCH 40/70] 8077846: improve locking strategy for readConfiguration(), reset(), and initializeGlobalHandlers() Co-authored-by: Daniel Fuchs Reviewed-by: dholmes, alanb, mchung --- .../classes/java/util/logging/LogManager.java | 230 ++++++--- .../Configuration/TestConfigurationLock.java | 457 ++++++++++++++++++ .../TestConfigurationLock.properties | 22 + 3 files changed, 635 insertions(+), 74 deletions(-) create mode 100644 jdk/test/java/util/logging/LogManager/Configuration/TestConfigurationLock.java create mode 100644 jdk/test/java/util/logging/LogManager/Configuration/TestConfigurationLock.properties diff --git a/jdk/src/java.logging/share/classes/java/util/logging/LogManager.java b/jdk/src/java.logging/share/classes/java/util/logging/LogManager.java index 972b74a7efb..77c6585ec87 100644 --- a/jdk/src/java.logging/share/classes/java/util/logging/LogManager.java +++ b/jdk/src/java.logging/share/classes/java/util/logging/LogManager.java @@ -33,6 +33,7 @@ import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; +import java.util.concurrent.locks.ReentrantLock; import sun.misc.JavaAWTAccess; import sun.misc.ManagedLocalsThread; import sun.misc.SharedSecrets; @@ -180,10 +181,16 @@ public class LogManager { // initialization has been done) private volatile boolean readPrimordialConfiguration; // Have we initialized global (root) handlers yet? - // This gets set to false in readConfiguration - private boolean initializedGlobalHandlers = true; - // True if JVM death is imminent and the exit hook has been called. - private boolean deathImminent; + // This gets set to STATE_UNINITIALIZED in readConfiguration + private static final int + STATE_INITIALIZED = 0, // initial state + STATE_INITIALIZING = 1, + STATE_READING_CONFIG = 2, + STATE_UNINITIALIZED = 3, + STATE_SHUTDOWN = 4; // terminal state + private volatile int globalHandlersState; // = STATE_INITIALIZED; + // A concurrency lock for reset(), readConfiguration() and Cleaner. + private final ReentrantLock configurationLock = new ReentrantLock(); // This list contains the loggers for which some handlers have been // explicitly configured in the configuration file. @@ -264,13 +271,12 @@ public class LogManager { // before synchronized block. Otherwise deadlocks are possible. LogManager mgr = manager; - // If the global handlers haven't been initialized yet, we - // don't want to initialize them just so we can close them! - synchronized (LogManager.this) { - // Note that death is imminent. - deathImminent = true; - initializedGlobalHandlers = true; - } + // set globalHandlersState to STATE_SHUTDOWN atomically so that + // no attempts are made to (re)initialize the handlers or (re)read + // the configuration again. This is terminal state. + configurationLock.lock(); + globalHandlersState = STATE_SHUTDOWN; + configurationLock.unlock(); // Do a reset to close all active handlers. reset(); @@ -1314,8 +1320,14 @@ public class LogManager { public void reset() throws SecurityException { checkPermission(); + List persistent; - synchronized (this) { + + // We don't want reset() and readConfiguration() + // to run in parallel + configurationLock.lock(); + try { + // install new empty properties props = new Properties(); // make sure we keep the loggers persistent until reset is done. // Those are the loggers for which we previously created a @@ -1323,26 +1335,41 @@ public class LogManager { // from being gc'ed until those handlers are closed. persistent = new ArrayList<>(closeOnResetLoggers); closeOnResetLoggers.clear(); - // Since we are doing a reset we no longer want to initialize - // the global handlers, if they haven't been initialized yet. - initializedGlobalHandlers = true; - } - for (LoggerContext cx : contexts()) { - Enumeration enum_ = cx.getLoggerNames(); - while (enum_.hasMoreElements()) { - String name = enum_.nextElement(); - Logger logger = cx.findLogger(name); - if (logger != null) { - resetLogger(logger); - } + + // if reset has been called from shutdown-hook (Cleaner), + // or if reset has been called from readConfiguration() which + // already holds the lock and will change the state itself, + // then do not change state here... + if (globalHandlersState != STATE_SHUTDOWN && + globalHandlersState != STATE_READING_CONFIG) { + // ...else user called reset()... + // Since we are doing a reset we no longer want to initialize + // the global handlers, if they haven't been initialized yet. + globalHandlersState = STATE_INITIALIZED; } + + for (LoggerContext cx : contexts()) { + resetLoggerContext(cx); + } + + persistent.clear(); + } finally { + configurationLock.unlock(); } - persistent.clear(); } - // Private method to reset an individual target logger. - private void resetLogger(Logger logger) { - // Close all the Logger's handlers. + private void resetLoggerContext(LoggerContext cx) { + Enumeration enum_ = cx.getLoggerNames(); + while (enum_.hasMoreElements()) { + String name = enum_.nextElement(); + Logger logger = cx.findLogger(name); + if (logger != null) { + resetLogger(logger); + } + } + } + + private void closeHandlers(Logger logger) { Handler[] targets = logger.getHandlers(); for (Handler h : targets) { logger.removeHandler(h); @@ -1352,6 +1379,14 @@ public class LogManager { // Problems closing a handler? Keep going... } } + } + + // Private method to reset an individual target logger. + private void resetLogger(Logger logger) { + // Close all the Logger handlers. + closeHandlers(logger); + + // Reset Logger level String name = logger.getName(); if (name != null && name.equals("")) { // This is the root logger. @@ -1408,48 +1443,74 @@ public class LogManager { */ public void readConfiguration(InputStream ins) throws IOException, SecurityException { checkPermission(); - reset(); - // Load the properties + // We don't want reset() and readConfiguration() to run + // in parallel. + configurationLock.lock(); try { - props.load(ins); - } catch (IllegalArgumentException x) { - // props.load may throw an IllegalArgumentException if the stream - // contains malformed Unicode escape sequences. - // We wrap that in an IOException as readConfiguration is - // specified to throw IOException if there are problems reading - // from the stream. - // Note: new IOException(x.getMessage(), x) allow us to get a more - // concise error message than new IOException(x); - throw new IOException(x.getMessage(), x); - } + if (globalHandlersState == STATE_SHUTDOWN) { + // already in terminal state: don't even bother + // to read the configuration + return; + } - // Instantiate new configuration objects. - String names[] = parseClassNames("config"); - - for (String word : names) { + // change state to STATE_READING_CONFIG to signal reset() to not change it + globalHandlersState = STATE_READING_CONFIG; try { - Class clz = ClassLoader.getSystemClassLoader().loadClass(word); - clz.newInstance(); - } catch (Exception ex) { - System.err.println("Can't load config class \"" + word + "\""); - System.err.println("" + ex); - // ex.printStackTrace(); + // reset configuration which leaves globalHandlersState at STATE_READING_CONFIG + // so that while reading configuration, any ongoing logging requests block and + // wait for the outcome (see the end of this try statement) + reset(); + + try { + // Load the properties + props.load(ins); + } catch (IllegalArgumentException x) { + // props.load may throw an IllegalArgumentException if the stream + // contains malformed Unicode escape sequences. + // We wrap that in an IOException as readConfiguration is + // specified to throw IOException if there are problems reading + // from the stream. + // Note: new IOException(x.getMessage(), x) allow us to get a more + // concise error message than new IOException(x); + throw new IOException(x.getMessage(), x); + } + + // Instantiate new configuration objects. + String names[] = parseClassNames("config"); + + for (String word : names) { + try { + Class clz = ClassLoader.getSystemClassLoader().loadClass(word); + clz.newInstance(); + } catch (Exception ex) { + System.err.println("Can't load config class \"" + word + "\""); + System.err.println("" + ex); + // ex.printStackTrace(); + } + } + + // Set levels on any pre-existing loggers, based on the new properties. + setLevelsOnExistingLoggers(); + + // Note that we need to reinitialize global handles when + // they are first referenced. + globalHandlersState = STATE_UNINITIALIZED; + } catch (Throwable t) { + // If there were any trouble, then set state to STATE_INITIALIZED + // so that no global handlers reinitialization is performed on not fully + // initialized configuration. + globalHandlersState = STATE_INITIALIZED; + // re-throw + throw t; } - } - - // Set levels on any pre-existing loggers, based on the new properties. - setLevelsOnExistingLoggers(); - - try { - invokeConfigurationListeners(); } finally { - // Note that we need to reinitialize global handles when - // they are first referenced. - synchronized (this) { - initializedGlobalHandlers = false; - } + configurationLock.unlock(); } + + // should be called out of lock to avoid dead-lock situations + // when user code is involved + invokeConfigurationListeners(); } /** @@ -1576,20 +1637,41 @@ public class LogManager { // Private method to load the global handlers. // We do the real work lazily, when the global handlers // are first used. - private synchronized void initializeGlobalHandlers() { - if (initializedGlobalHandlers) { + private void initializeGlobalHandlers() { + int state = globalHandlersState; + if (state == STATE_INITIALIZED || + state == STATE_SHUTDOWN) { + // Nothing to do: return. return; } - initializedGlobalHandlers = true; - - if (deathImminent) { - // Aaargh... - // The VM is shutting down and our exit hook has been called. - // Avoid allocating global handlers. - return; + // If we have not initialized global handlers yet (or need to + // reinitialize them), lets do it now (this case is indicated by + // globalHandlersState == STATE_UNINITIALIZED). + // If we are in the process of initializing global handlers we + // also need to lock & wait (this case is indicated by + // globalHandlersState == STATE_INITIALIZING). + // If we are in the process of reading configuration we also need to + // wait to see what the outcome will be (this case + // is indicated by globalHandlersState == STATE_READING_CONFIG) + // So in either case we need to wait for the lock. + configurationLock.lock(); + try { + if (globalHandlersState != STATE_UNINITIALIZED) { + return; // recursive call or nothing to do + } + // set globalHandlersState to STATE_INITIALIZING first to avoid + // getting an infinite recursion when loadLoggerHandlers(...) + // is going to call addHandler(...) + globalHandlersState = STATE_INITIALIZING; + try { + loadLoggerHandlers(rootLogger, null, "handlers"); + } finally { + globalHandlersState = STATE_INITIALIZED; + } + } finally { + configurationLock.unlock(); } - loadLoggerHandlers(rootLogger, null, "handlers"); } static final Permission controlPermission = new LoggingPermission("control", null); @@ -1684,7 +1766,7 @@ public class LogManager { // Private method to be called when the configuration has // changed to apply any level settings to any pre-existing loggers. - synchronized private void setLevelsOnExistingLoggers() { + private void setLevelsOnExistingLoggers() { Enumeration enum_ = props.propertyNames(); while (enum_.hasMoreElements()) { String key = (String)enum_.nextElement(); diff --git a/jdk/test/java/util/logging/LogManager/Configuration/TestConfigurationLock.java b/jdk/test/java/util/logging/LogManager/Configuration/TestConfigurationLock.java new file mode 100644 index 00000000000..47e812cc012 --- /dev/null +++ b/jdk/test/java/util/logging/LogManager/Configuration/TestConfigurationLock.java @@ -0,0 +1,457 @@ +/* + * Copyright (c) 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + */ +import java.io.File; +import java.io.IOException; +import java.lang.management.LockInfo; +import java.lang.management.ManagementFactory; +import java.lang.management.MonitorInfo; +import java.lang.management.ThreadInfo; +import java.security.Permission; +import java.security.Policy; +import java.security.ProtectionDomain; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.atomic.AtomicLong; +import java.util.logging.Level; +import java.util.logging.LogManager; +import java.util.logging.Logger; + + +/** + * @test + * @bug 8077846 + * @key randomness + * @summary Test that using a reentrant configuration lock does not introduce + * new synchronization issues in Logger and LogManager. This test + * focuses more particularly on potential deadlock in + * drainLoggerRefQueueBounded / readConfiguration / reset + * todo: add at randomness + * @run main/othervm TestConfigurationLock + * @author danielfuchs + */ +// This test is a best effort to try & detect issues. The test itself will run +// for 8secs. This might be unsufficient to detect issues. +// To get a greater confidence it is recommended to run this test in a loop: +// e.g. use something like: +// $ while jtreg -jdk:$JDK -verbose:all \ +// test/java/util/logging/TestConfigurationLock.java ; \ +// do echo Running test again ; done +// and let it run for a few hours... +// +public class TestConfigurationLock { + + static volatile Exception thrown = null; + static volatile boolean goOn = true; + static volatile boolean deadlock = false; + + static final double CONFSYNCTHRESHOLD = 0.3; + static final double LOGSYNCTHRESHOLD = 0.3; + static final int RESETERS = 0; + static final int READERS = 3; + static final int LOGGERS = 4; + static final long TIME = 8 * 1000; // 8 sec. + static final long STEP = 1 * 1000; // message every 1 sec. + static final int LCOUNT = 50; // 50 loggers created in a row... + static final AtomicLong nextLogger = new AtomicLong(0); + static final AtomicLong resetCount = new AtomicLong(0); + static final AtomicLong readCount = new AtomicLong(0); + static final AtomicLong checkCount = new AtomicLong(0); + + static final String BLAH = "blah"; + + static Object fakeConfExternalLock() { + return LogManager.getLogManager(); + } + + static Object fakeLogExternalLock() { + return LogManager.getLogManager(); + } + + + /** + * This test will run both with and without a security manager. + * + * The test starts a number of threads that will call + * LogManager.reset() concurrently (ResetConf), and a number of threads + * that will call readConfiguration() (ReadConf), and then starts a + * number of threads that will create new loggers concurrently + * (AddLogger), and finally two additional threads: + * - one (Stopper) that will stop the test after 4secs (TIME ms), + * - and one DeadlockDetector that will attempt to detect deadlocks. + * If after 4secs no deadlock was detected and no exception was thrown + * then the test is considered a success and passes. + * + * This procedure is done twice: once without a security manager and once + * again with a security manager - which means the test takes ~8secs to + * run. + * + * Note that 8sec may not be enough to detect issues if there are some. + * This is a best effort test. + * + * @param args the command line arguments + * @throws java.lang.Exception if the test fails + */ + public static void main(String[] args) throws Exception { + + File conf = new File(System.getProperty("test.src", "./src"), + TestConfigurationLock.class.getSimpleName() + ".properties"); + if (!conf.canRead()) { + throw new IOException("Can't read config file: " + conf.getAbsolutePath()); + } + System.setProperty("java.util.logging.config.file", conf.getAbsolutePath()); + // test without security + System.out.println("No security"); + test(); + + // test with security + System.out.println("\nWith security"); + Policy.setPolicy(new Policy() { + @Override + public boolean implies(ProtectionDomain domain, Permission permission) { + if (super.implies(domain, permission)) return true; + // System.out.println("Granting " + permission); + return true; // all permissions + } + }); + System.setSecurityManager(new SecurityManager()); + test(); + } + + + /** + * Starts all threads, wait 4secs, then stops all threads. + * @throws Exception if a deadlock was detected or an error occurred. + */ + public static void test() throws Exception { + goOn = true; + thrown = null; + long sNextLogger = nextLogger.get(); + long sUpdateCount = resetCount.get(); + long sReadCount = readCount.get(); + long sCheckCount = checkCount.get(); + List threads = new ArrayList<>(); + for (int i = 0; i CONFSYNCTHRESHOLD) { + // calling reset while holding a lock can increase + // deadlock probability... + synchronized(fakeConfExternalLock()) { + LogManager.getLogManager().reset(); + } + } else { + LogManager.getLogManager().reset(); + } + Logger blah = Logger.getLogger(BLAH); + blah.setLevel(Level.FINEST); + blah.fine(BLAH); + resetCount.incrementAndGet(); + pause(1); + } catch (Exception x) { + fail(x); + } + } + } + } + + final static class ReadConf extends Thread { + + public ReadConf() { + setDaemon(true); + } + + @Override + public void run() { + while (goOn) { + try { + if (Math.random() > CONFSYNCTHRESHOLD) { + // calling readConfiguration while holding a lock can + // increase deadlock probability... + synchronized(fakeConfExternalLock()) { + LogManager.getLogManager().readConfiguration(); + } + } else { + LogManager.getLogManager().readConfiguration(); + } + Logger blah = Logger.getLogger(BLAH); + blah.setLevel(Level.FINEST); + blah.fine(BLAH); + readCount.incrementAndGet(); + pause(1); + } catch (Exception x) { + fail(x); + } + } + } + } + + final static class AddLogger extends Thread { + + public AddLogger() { + setDaemon(true); + } + + @Override + public void run() { + try { + while (goOn) { + Logger l; + Logger foo = Logger.getLogger("foo"); + Logger bar = Logger.getLogger("foo.bar"); + for (int i=0; i < LCOUNT ; i++) { + LogManager manager = LogManager.getLogManager(); + if (Math.random() > LOGSYNCTHRESHOLD) { + synchronized(fakeLogExternalLock()) { + l = Logger.getLogger("foo.bar.l"+nextLogger.incrementAndGet()); + } + } else { + l = Logger.getLogger("foo.bar.l"+nextLogger.incrementAndGet()); + } + l.setLevel(Level.FINEST); + l.fine("I'm fine"); + if (!goOn) break; + pause(1); + } + } + } catch (InterruptedException | RuntimeException x ) { + fail(x); + } + } + } + + final static class DeadlockDetector extends Thread { + + @Override + public void run() { + boolean deadlock = false; + while(goOn) { + try { + long[] ids = ManagementFactory.getThreadMXBean().findDeadlockedThreads(); + checkCount.incrementAndGet(); + ids = ids == null ? new long[0] : ids; + if (ids.length == 1) { + throw new RuntimeException("Found 1 deadlocked thread: "+ids[0]); + } else if (ids.length > 0) { + deadlock = true; + ThreadInfo[] infos = ManagementFactory.getThreadMXBean() + .getThreadInfo(ids, true, true); + System.err.println("Found "+ids.length+" deadlocked threads: "); + for (ThreadInfo inf : infos) { + System.err.println(asString(inf)); + } + throw new RuntimeException("Found "+ids.length+" deadlocked threads"); + } + pause(100); + } catch(InterruptedException | RuntimeException x) { + if (deadlock) deadlock(x); + else fail(x); + } + } + } + + } + + static final class Stopper extends Thread { + long start; + long time; + + Stopper(long time) { + start = System.currentTimeMillis(); + this.time = time; + setDaemon(true); + } + + @Override + public void run() { + try { + long rest, previous; + int msgCount = 0; + previous = time; + Logger logger = Logger.getLogger("remaining"); + while (goOn && (rest = start - System.currentTimeMillis() + time) > 0) { + if (previous == time || previous - rest >= STEP) { + logger.log(Level.INFO, "{0}ms remaining...", String.valueOf(rest)); + msgCount++; + previous = rest == time ? rest -1 : rest; + System.gc(); + } + if (goOn == false) break; + pause(Math.min(rest, 100)); + } + System.err.println(this + ": " + msgCount + " messages."); + System.err.flush(); + System.out.println(System.currentTimeMillis() - start + + " ms elapsed ("+time+ " requested)"); + goOn = false; + } catch(InterruptedException | RuntimeException x) { + fail(x); + } + } + + } + + // ThreadInfo.toString() only prints 8 frames... + static String asString(ThreadInfo inf) { + StringBuilder sb = new StringBuilder(); + sb.append("\"").append(inf.getThreadName()).append("\"") + .append(inf.isDaemon() ? " daemon" : "") + .append(" prio=").append(inf.getPriority()) + .append(" Id=").append(inf.getThreadId()) + .append(" ").append(inf.getThreadState()); + if (inf.getLockName() != null) { + sb.append(" on ").append(inf.getLockName()); + } + if (inf.getLockOwnerName() != null) { + sb.append(" owned by \"").append(inf.getLockOwnerName()) + .append("\" Id=").append(inf.getLockOwnerId()); + } + if (inf.isSuspended()) { + sb.append(" (suspended)"); + } + if (inf.isInNative()) { + sb.append(" (in native)"); + } + sb.append('\n'); + int i = 0; + StackTraceElement[] stackTrace = inf.getStackTrace(); + for (; i < stackTrace.length; i++) { + StackTraceElement ste = stackTrace[i]; + sb.append("\tat ").append(ste.toString()); + sb.append('\n'); + if (i == 0 && inf.getLockInfo() != null) { + Thread.State ts = inf.getThreadState(); + switch (ts) { + case BLOCKED: + sb.append("\t- blocked on ").append(inf.getLockInfo()); + sb.append('\n'); + break; + case WAITING: + sb.append("\t- waiting on ").append(inf.getLockInfo()); + sb.append('\n'); + break; + case TIMED_WAITING: + sb.append("\t- waiting on ").append(inf.getLockInfo()); + sb.append('\n'); + break; + default: + } + } + + for (MonitorInfo mi : inf.getLockedMonitors()) { + if (mi.getLockedStackDepth() == i) { + sb.append("\t- locked ").append(mi); + sb.append('\n'); + } + } + } + if (i < stackTrace.length) { + sb.append("\t..."); + sb.append('\n'); + } + + LockInfo[] locks = inf.getLockedSynchronizers(); + if (locks.length > 0) { + sb.append("\n\tNumber of locked synchronizers = ").append(locks.length); + sb.append('\n'); + for (LockInfo li : locks) { + sb.append("\t- ").append(li); + sb.append('\n'); + } + } + sb.append('\n'); + return sb.toString(); + } + + static void pause(long millis) throws InterruptedException { + Thread.sleep(millis); + } + + static void fail(Exception x) { + x.printStackTrace(System.err); + if (thrown == null) { + thrown = x; + } + goOn = false; + } + + static void deadlock(Exception x) { + deadlock = true; + System.out.flush(); + fail(x); + System.err.flush(); + } +} diff --git a/jdk/test/java/util/logging/LogManager/Configuration/TestConfigurationLock.properties b/jdk/test/java/util/logging/LogManager/Configuration/TestConfigurationLock.properties new file mode 100644 index 00000000000..c512b0ea067 --- /dev/null +++ b/jdk/test/java/util/logging/LogManager/Configuration/TestConfigurationLock.properties @@ -0,0 +1,22 @@ +######################################################################## +# Logging configuration property file for TestConfigurationLock.java # +######################################################################## + +handlers= java.util.logging.ConsoleHandler + +.level= INFO + +java.util.logging.FileHandler.pattern = %h/java%u.log +java.util.logging.FileHandler.limit = 50000 +java.util.logging.FileHandler.count = 1 +java.util.logging.FileHandler.formatter = java.util.logging.XMLFormatter + +java.util.logging.ConsoleHandler.level = INFO +java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter + +blah.level = FINE +foo.bar.l10.level = INFO +foo.bar.l100.level = INFO +foo.bar.l1000.level = INFO + + From f79ca89ac724bf4f88688946473584b7c88325c8 Mon Sep 17 00:00:00 2001 From: Peter Levart Date: Sun, 17 May 2015 18:49:21 +0200 Subject: [PATCH 41/70] 8074002: java.time.ZoneId.systemDefault() should be faster Cache ZoneId inside TimeZone object Reviewed-by: scolebourne, rriggs, dfuchs --- .../share/classes/java/util/TimeZone.java | 36 ++++++++++++++++--- 1 file changed, 31 insertions(+), 5 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/TimeZone.java b/jdk/src/java.base/share/classes/java/util/TimeZone.java index adc6ad349df..f28919f36db 100644 --- a/jdk/src/java.base/share/classes/java/util/TimeZone.java +++ b/jdk/src/java.base/share/classes/java/util/TimeZone.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -293,6 +293,7 @@ abstract public class TimeZone implements Serializable, Cloneable { throw new NullPointerException(); } this.ID = ID; + this.zoneId = null; // invalidate cache } /** @@ -544,7 +545,23 @@ abstract public class TimeZone implements Serializable, Cloneable { * @since 1.8 */ public ZoneId toZoneId() { + ZoneId zId = zoneId; + if (zId == null) { + zoneId = zId = toZoneId0(); + } + return zId; + } + + private ZoneId toZoneId0() { String id = getID(); + TimeZone defaultZone = defaultTimeZone; + // are we not defaultTimeZone but our id is equal to default's? + if (defaultZone != this && + defaultZone != null && id.equals(defaultZone.getID())) { + // delegate to default TZ which is effectively immutable + return defaultZone.toZoneId(); + } + // derive it ourselves if (ZoneInfoFile.useOldMapping() && id.length() == 3) { if ("EST".equals(id)) return ZoneId.of("America/New_York"); @@ -710,7 +727,12 @@ abstract public class TimeZone implements Serializable, Cloneable { sm.checkPermission(new PropertyPermission ("user.timezone", "write")); } - defaultTimeZone = zone; + // by saving a defensive clone and returning a clone in getDefault() too, + // the defaultTimeZone instance is isolated from user code which makes it + // effectively immutable. This is important to avoid races when the + // following is evaluated in ZoneId.systemDefault(): + // TimeZone.getDefault().toZoneId(). + defaultTimeZone = (zone == null) ? null : (TimeZone) zone.clone(); } /** @@ -735,9 +757,7 @@ abstract public class TimeZone implements Serializable, Cloneable { public Object clone() { try { - TimeZone other = (TimeZone) super.clone(); - other.ID = ID; - return other; + return super.clone(); } catch (CloneNotSupportedException e) { throw new InternalError(e); } @@ -759,6 +779,12 @@ abstract public class TimeZone implements Serializable, Cloneable { * @serial */ private String ID; + + /** + * Cached {@link ZoneId} for this TimeZone + */ + private transient ZoneId zoneId; + private static volatile TimeZone defaultTimeZone; static final String GMT_ID = "GMT"; From 9fe30fb1187d19ac96cc24dde139342a15bf892e Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Sun, 17 May 2015 11:04:01 -0700 Subject: [PATCH 42/70] 8078136: Incorrect figure number in reference to Hacker's Delight book in Long.bitCount() method Reviewed-by: lancea --- jdk/src/java.base/share/classes/java/lang/Long.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/jdk/src/java.base/share/classes/java/lang/Long.java b/jdk/src/java.base/share/classes/java/lang/Long.java index 9382a2df1e9..b1b37032397 100644 --- a/jdk/src/java.base/share/classes/java/lang/Long.java +++ b/jdk/src/java.base/share/classes/java/lang/Long.java @@ -1708,7 +1708,7 @@ public final class Long extends Number implements Comparable { * @since 1.5 */ public static int bitCount(long i) { - // HD, Figure 5-14 + // HD, Figure 5-2 i = i - ((i >>> 1) & 0x5555555555555555L); i = (i & 0x3333333333333333L) + ((i >>> 2) & 0x3333333333333333L); i = (i + (i >>> 4)) & 0x0f0f0f0f0f0f0f0fL; From c5889bc1027e03256920408f9456e41fb571e607 Mon Sep 17 00:00:00 2001 From: Zaiyao Liu Date: Mon, 18 May 2015 02:11:39 +0000 Subject: [PATCH 43/70] 8048820: Implement tests for SecretKeyFactory Reviewed-by: xuelei --- .../SecretKeyFactory/PBKDF2TranslateTest.java | 270 ++++++++++++++++++ .../SecretKeyFactory/SecKFTranslateTest.java | 206 +++++++++++++ 2 files changed, 476 insertions(+) create mode 100644 jdk/test/javax/crypto/SecretKeyFactory/PBKDF2TranslateTest.java create mode 100644 jdk/test/javax/crypto/SecretKeyFactory/SecKFTranslateTest.java diff --git a/jdk/test/javax/crypto/SecretKeyFactory/PBKDF2TranslateTest.java b/jdk/test/javax/crypto/SecretKeyFactory/PBKDF2TranslateTest.java new file mode 100644 index 00000000000..acd2081b0f6 --- /dev/null +++ b/jdk/test/javax/crypto/SecretKeyFactory/PBKDF2TranslateTest.java @@ -0,0 +1,270 @@ +/* + * Copyright (c) 2003, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.spec.InvalidKeySpecException; +import java.util.Arrays; +import java.util.Random; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.interfaces.PBEKey; +import javax.crypto.spec.PBEKeySpec; +import javax.security.auth.DestroyFailedException; + +import static java.lang.System.out; + +/* + * @test + * @bug 8048820 + * @summary The test verifies if the SecretKeyFactory.translateKey() method + * works as expected for the PBKDF2 algorithms. + */ + +public class PBKDF2TranslateTest { + + private static final String PASS_PHRASE = "some hidden string"; + private static final int ITERATION_COUNT = 1000; + private static final int KEY_SIZE = 128; + private static final String[] TEST_ALGOS = { "PBKDF2WithHmacSHA1", + "PBKDF2WithHmacSHA224", "PBKDF2WithHmacSHA256", + "PBKDF2WithHmacSHA384", "PBKDF2WithHmacSHA512" }; + private final String algoForTest; + + public static void main(String[] args) throws Exception { + for (String algo : TEST_ALGOS) { + PBKDF2TranslateTest theTest = new PBKDF2TranslateTest(algo); + byte[] salt = new byte[8]; + new Random().nextBytes(salt); + theTest.testMyOwnSecretKey(salt); + theTest.generateAndTranslateKey(salt); + theTest.translateSpoiledKey(salt); + } + } + + public PBKDF2TranslateTest(String algo) { + algoForTest = algo; + } + + /** + * The test case scenario implemented in the method: - derive PBKDF2 key + * using the given algorithm; - translate the key - check if the translated + * and original keys have the same key value. + * + */ + public void generateAndTranslateKey(byte[] salt) + throws NoSuchAlgorithmException, InvalidKeySpecException, + InvalidKeyException { + // derive PBKDF2 key + SecretKey key1 = getSecretKeyForPBKDF2(algoForTest, salt); + + // translate key + SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest); + SecretKey key2 = skf.translateKey(key1); + + // Check if it still the same after translation + if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) { + System.out.println("Key1=" + new String(key1.getEncoded()) + + " key2=" + new String(key2.getEncoded()) + " salt=" + + new String(salt)); + throw new RuntimeException( + "generateAndTranslateKey test case failed: the key1 and" + + " key2 values in its primary encoding format are" + + " not the same for " + algoForTest + + " algorithm."); + } + } + + /** + * The test case scenario implemented in the method: - derive Key1 for the + * given PBKDF2 algorithm - create my own secret Key2 as an instance of a + * class implements PBEKey - translate Key2 - check if the key value of the + * translated key and Key1 are the same. + */ + private void testMyOwnSecretKey(byte[] salt) + throws NoSuchAlgorithmException, InvalidKeySpecException, + InvalidKeyException { + SecretKey key1 = getSecretKeyForPBKDF2(algoForTest, salt); + SecretKey key2 = getMyOwnSecretKey(salt); + + // Is it actually the same? + if (!Arrays.equals(key1.getEncoded(), key2.getEncoded())) { + throw new RuntimeException( + "We shouldn't be here. The key1 and key2 values in its" + + " primary encoding format have to be the same!"); + } + + // translate key + SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest); + SecretKey key3 = skf.translateKey(key2); + + // Check if it still the same after translation + if (!Arrays.equals(key1.getEncoded(), key3.getEncoded())) { + System.out.println("Key1=" + new String(key1.getEncoded()) + + " key3=" + new String(key3.getEncoded()) + " salt=" + + new String(salt)); + throw new RuntimeException( + "testMyOwnSecretKey test case failed: the key1 and key3" + + " values in its primary encoding format are not" + + " the same for " + algoForTest + " algorithm."); + } + + } + + /** + * The test case scenario implemented in the method: - create my own secret + * Key2 as an instance of a class implements PBEKey - spoil the key (set + * iteration count to 0, for example) - try to translate key - + * InvalidKeyException is expected. + */ + public void translateSpoiledKey(byte[] salt) + throws NoSuchAlgorithmException, InvalidKeySpecException { + // derive the key + SecretKey key1 = getMyOwnSecretKey(salt); + + // spoil the key + ((MyPBKDF2SecretKey) key1).spoil(); + + // translate key + SecretKeyFactory skf = SecretKeyFactory.getInstance(algoForTest); + try { + skf.translateKey(key1); + throw new RuntimeException( + "translateSpoiledKey test case failed, should throw" + + " InvalidKeyException when spoil the key"); + } catch (InvalidKeyException ike) { + out.println("Expected exception when spoil the key"); + } + + } + + /** + * Generate a PBKDF2 secret key using given algorithm. + */ + private SecretKey getSecretKeyForPBKDF2(String algoDeriveKey, byte[] salt) + throws NoSuchAlgorithmException, InvalidKeySpecException { + + SecretKeyFactory skf = SecretKeyFactory.getInstance(algoDeriveKey); + PBEKeySpec spec = new PBEKeySpec(PASS_PHRASE.toCharArray(), salt, + ITERATION_COUNT, KEY_SIZE); + + return skf.generateSecret(spec); + } + + /** + * Generate a secrete key as an instance of a class implements PBEKey. + */ + private SecretKey getMyOwnSecretKey(byte[] salt) + throws InvalidKeySpecException, NoSuchAlgorithmException { + return new MyPBKDF2SecretKey(PASS_PHRASE, algoForTest, salt, + ITERATION_COUNT, KEY_SIZE); + } + + /** + * An utility class to check the SecretKeyFactory.translateKey() method. + */ + class MyPBKDF2SecretKey implements PBEKey { + private final byte[] key; + private final byte[] salt; + private final String algorithm; + private final int keyLength; + private final String pass; + private int itereationCount; + + /** + * The key is generating by SecretKeyFactory and its value just copying + * in the key field of MySecretKey class. So, this is real key derived + * using the given algo. + */ + public MyPBKDF2SecretKey(String passPhrase, String algo, byte[] salt1, + int iterationCount, int keySize) + throws InvalidKeySpecException, NoSuchAlgorithmException { + algorithm = algo; + salt = salt1; + itereationCount = iterationCount; + pass = passPhrase; + + PBEKeySpec spec = new PBEKeySpec(passPhrase.toCharArray(), salt, + iterationCount, keySize); + + SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(algo); + + SecretKey realKey = keyFactory.generateSecret(spec); + + keyLength = realKey.getEncoded().length; + + key = new byte[keyLength]; + System.arraycopy(realKey.getEncoded(), 0, key, 0, keyLength); + } + + @Override + public String getAlgorithm() { + return algorithm; + } + + @Override + public String getFormat() { + return "RAW"; + } + + @Override + public byte[] getEncoded() { + byte[] copy = new byte[keyLength]; + System.arraycopy(key, 0, copy, 0, keyLength); + return copy; + } + + @Override + public int getIterationCount() { + return itereationCount; + } + + @Override + public byte[] getSalt() { + return salt; + } + + @Override + public char[] getPassword() { + return pass.toCharArray(); + } + + /** + * Spoil the generated key (before translation) to cause an + * InvalidKeyException + */ + public void spoil() { + itereationCount = -1; + } + + @Override + public void destroy() throws DestroyFailedException { + } + + @Override + public boolean isDestroyed() { + return false; + } + + } +} \ No newline at end of file diff --git a/jdk/test/javax/crypto/SecretKeyFactory/SecKFTranslateTest.java b/jdk/test/javax/crypto/SecretKeyFactory/SecKFTranslateTest.java new file mode 100644 index 00000000000..f1b5c825798 --- /dev/null +++ b/jdk/test/javax/crypto/SecretKeyFactory/SecKFTranslateTest.java @@ -0,0 +1,206 @@ +/* + * Copyright (c) 2003, 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.NoSuchAlgorithmException; +import java.security.NoSuchProviderException; +import java.security.SecureRandom; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.InvalidKeySpecException; +import java.util.Arrays; +import java.util.Random; + +import javax.crypto.BadPaddingException; +import javax.crypto.Cipher; +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.SecretKeyFactory; +import javax.crypto.ShortBufferException; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.PBEParameterSpec; +import javax.security.auth.DestroyFailedException; + +/* + * @test + * @bug 8048820 + * @summary The test verifies SecretKey values should remain the same after + * translation with SecretKeyFactory.translateKey(). + */ + +public class SecKFTranslateTest { + private static final String SUN_JCE = "SunJCE"; + + public static void main(String[] args) throws Exception { + + SecKFTranslateTest test = new SecKFTranslateTest(); + test.run(); + } + + private void run() throws Exception { + + for (Algorithm algorithm : Algorithm.values()) { + runTest(algorithm); + } + } + + private void runTest(Algorithm algo) throws NoSuchAlgorithmException, + NoSuchProviderException, InvalidKeyException, + InvalidKeySpecException, NoSuchPaddingException, + InvalidAlgorithmParameterException, ShortBufferException, + IllegalBlockSizeException, BadPaddingException { + AlgorithmParameterSpec[] aps = new AlgorithmParameterSpec[1]; + byte[] plainText = new byte[800]; + + SecretKey key1 = algo.intSecurityKey(aps); + Random random = new Random(); + // Initialization + SecretKeyFactory skf = SecretKeyFactory.getInstance(algo.toString(), + SUN_JCE); + + random.nextBytes(plainText); + Cipher ci = Cipher.getInstance(algo.toString(), SUN_JCE); + // Encryption + ci.init(Cipher.ENCRYPT_MODE, key1, aps[0]); + byte[] cipherText = new byte[ci.getOutputSize(plainText.length)]; + int offset = ci.update(plainText, 0, plainText.length, cipherText, 0); + ci.doFinal(cipherText, offset); + // translate key + SecretKey key2 = skf.translateKey(key1); + + // Decryption + ci.init(Cipher.DECRYPT_MODE, key2, aps[0]); + byte[] recoveredText = new byte[ci.getOutputSize(plainText.length)]; + ci.doFinal(cipherText, 0, cipherText.length, recoveredText); + + // Comparison + if (!Arrays.equals(plainText, recoveredText)) { + System.out.println("Key1:" + new String(key1.getEncoded()) + + " Key2:" + new String(key2.getEncoded())); + throw new RuntimeException("Testing translate key failed with " + + algo); + } + + } +} + +class MyOwnSecKey implements SecretKey { + + private static final String DEFAULT_ALGO = "PBEWithMD5AndDES"; + private final byte[] key; + private final String algorithm; + private final int keySize; + + public MyOwnSecKey(byte[] key1, int offset, String algo) + throws InvalidKeyException { + algorithm = algo; + if (algo.equalsIgnoreCase("DES")) { + keySize = 8; + } else if (algo.equalsIgnoreCase("DESede")) { + keySize = 24; + } else { + throw new InvalidKeyException( + "Inappropriate key format and algorithm"); + } + + if (key1 == null || key1.length - offset < keySize) { + throw new InvalidKeyException("Wrong key size"); + } + key = new byte[keySize]; + System.arraycopy(key, offset, key, 0, keySize); + } + + public MyOwnSecKey(PBEKeySpec ks) throws InvalidKeySpecException { + algorithm = DEFAULT_ALGO; + key = new String(ks.getPassword()).getBytes(); + keySize = key.length; + } + + @Override + public String getAlgorithm() { + return algorithm; + } + + @Override + public String getFormat() { + return "RAW"; + } + + @Override + public byte[] getEncoded() { + byte[] copy = new byte[keySize]; + System.arraycopy(key, 0, copy, 0, keySize); + return copy; + } + + @Override + public void destroy() throws DestroyFailedException { + } + + @Override + public boolean isDestroyed() { + return false; + } +} + +enum Algorithm { + DES { + @Override + SecretKey intSecurityKey(AlgorithmParameterSpec[] spec) + throws InvalidKeyException { + int keyLength = 8; + byte[] keyVal = new byte[keyLength]; + new SecureRandom().nextBytes(keyVal); + SecretKey key1 = new MyOwnSecKey(keyVal, 0, this.toString()); + return key1; + } + }, + DESEDE { + @Override + SecretKey intSecurityKey(AlgorithmParameterSpec[] spec) + throws InvalidKeyException { + int keyLength = 24; + byte[] keyVal = new byte[keyLength]; + new SecureRandom().nextBytes(keyVal); + SecretKey key1 = new MyOwnSecKey(keyVal, 0, this.toString()); + return key1; + } + }, + PBEWithMD5ANDdes { + @Override + SecretKey intSecurityKey(AlgorithmParameterSpec[] spec) + throws InvalidKeySpecException { + byte[] salt = new byte[8]; + int iterCnt = 6; + new Random().nextBytes(salt); + spec[0] = new PBEParameterSpec(salt, iterCnt); + PBEKeySpec pbeKS = new PBEKeySpec( + new String("So far so good").toCharArray()); + SecretKey key1 = new MyOwnSecKey(pbeKS); + return key1; + } + }; + abstract SecretKey intSecurityKey(AlgorithmParameterSpec[] spec) + throws InvalidKeyException, InvalidKeySpecException; +} From 268d0924b973796fd329f1ac4148545f10c337c6 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Mon, 18 May 2015 18:57:35 +0530 Subject: [PATCH 44/70] 8072853: SimpleScriptContext used by NashornScriptEngine doesn't completely complies to the spec regarding exception throwing Reviewed-by: psandoz, lagergren --- .../javax/script/SimpleScriptContext.java | 15 ++- .../SimpleScriptContextNameChecksTest.java | 105 ++++++++++++++++++ 2 files changed, 117 insertions(+), 3 deletions(-) create mode 100644 jdk/test/javax/script/SimpleScriptContextNameChecksTest.java diff --git a/jdk/src/java.scripting/share/classes/javax/script/SimpleScriptContext.java b/jdk/src/java.scripting/share/classes/javax/script/SimpleScriptContext.java index 3cd3cbe0344..c56ce7adb8c 100644 --- a/jdk/src/java.scripting/share/classes/javax/script/SimpleScriptContext.java +++ b/jdk/src/java.scripting/share/classes/javax/script/SimpleScriptContext.java @@ -140,6 +140,7 @@ public class SimpleScriptContext implements ScriptContext { * @throws IllegalArgumentException if the name is empty. */ public Object getAttribute(String name) { + checkName(name); if (engineScope.containsKey(name)) { return getAttribute(name, ENGINE_SCOPE); } else if (globalScope != null && globalScope.containsKey(name)) { @@ -162,7 +163,7 @@ public class SimpleScriptContext implements ScriptContext { * @throws NullPointerException if the name is null. */ public Object getAttribute(String name, int scope) { - + checkName(name); switch (scope) { case ENGINE_SCOPE: @@ -191,7 +192,7 @@ public class SimpleScriptContext implements ScriptContext { * @throws NullPointerException if the name is null. */ public Object removeAttribute(String name, int scope) { - + checkName(name); switch (scope) { case ENGINE_SCOPE: @@ -223,7 +224,7 @@ public class SimpleScriptContext implements ScriptContext { * @throws NullPointerException if the name is null. */ public void setAttribute(String name, Object value, int scope) { - + checkName(name); switch (scope) { case ENGINE_SCOPE: @@ -281,6 +282,7 @@ public class SimpleScriptContext implements ScriptContext { * @throws IllegalArgumentException if name is empty. */ public int getAttributesScope(String name) { + checkName(name); if (engineScope.containsKey(name)) { return ENGINE_SCOPE; } else if (globalScope != null && globalScope.containsKey(name)) { @@ -314,6 +316,13 @@ public class SimpleScriptContext implements ScriptContext { return scopes; } + private void checkName(String name) { + Objects.requireNonNull(name); + if (name.isEmpty()) { + throw new IllegalArgumentException("name cannot be empty"); + } + } + private static List scopes; static { scopes = new ArrayList(2); diff --git a/jdk/test/javax/script/SimpleScriptContextNameChecksTest.java b/jdk/test/javax/script/SimpleScriptContextNameChecksTest.java new file mode 100644 index 00000000000..02b33553a26 --- /dev/null +++ b/jdk/test/javax/script/SimpleScriptContextNameChecksTest.java @@ -0,0 +1,105 @@ +/* + * Copyright (c) 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8072853 + * @summary SimpleScriptContext used by NashornScriptEngine doesn't completely complies to the spec regarding exception throwing + * @run testng SimpleScriptContextNameChecksTest + */ + +import java.util.List; +import java.util.function.Consumer; +import javax.script.*; +import org.testng.annotations.Test; + +public class SimpleScriptContextNameChecksTest { + private List getFactories() { + return new ScriptEngineManager().getEngineFactories(); + } + + private void testAndExpect(Consumer c, Class clazz) { + for (ScriptEngineFactory fac : getFactories()) { + ScriptContext sc = fac.getScriptEngine().getContext(); + String name = fac.getEngineName(); + try { + c.accept(sc); + throw new RuntimeException("no exception for " + name); + } catch (NullPointerException | IllegalArgumentException e) { + if (e.getClass() == clazz) { + System.out.println("got " + e + " as expected for " + name); + } else { + throw e; + } + } + } + } + + private void testAndExpectIAE(Consumer c) { + testAndExpect(c, IllegalArgumentException.class); + } + + private void testAndExpectNPE(Consumer c) { + testAndExpect(c, NullPointerException.class); + } + + @Test + public void getAttributeEmptyName() { + testAndExpectIAE(sc -> sc.getAttribute("", ScriptContext.GLOBAL_SCOPE)); + } + + @Test + public void getAttributeNullName() { + testAndExpectNPE(sc -> sc.getAttribute(null, ScriptContext.GLOBAL_SCOPE)); + } + + @Test + public void removeAttributeEmptyName() { + testAndExpectIAE(sc -> sc.removeAttribute("", ScriptContext.GLOBAL_SCOPE)); + } + + @Test + public void removeAttributeNullName() { + testAndExpectNPE(sc -> sc.removeAttribute(null, ScriptContext.GLOBAL_SCOPE)); + } + + @Test + public void setAttributeEmptyName() { + testAndExpectIAE(sc -> sc.setAttribute("", "value", ScriptContext.GLOBAL_SCOPE)); + } + + @Test + public void setAttributeNullName() { + testAndExpectNPE(sc -> sc.setAttribute(null, "value", ScriptContext.GLOBAL_SCOPE)); + } + + @Test + public void getAttributesScopeEmptyName() { + testAndExpectIAE(sc -> sc.getAttributesScope("")); + } + + @Test + public void getAttributesScopeNullName() { + testAndExpectNPE(sc -> sc.getAttributesScope(null)); + } +} From e8064300cbba0e0109656f0d0e101fd8f6346c5e Mon Sep 17 00:00:00 2001 From: Artem Smotrakov Date: Mon, 18 May 2015 17:34:48 +0300 Subject: [PATCH 45/70] 8079138: Additional negative tests for XML signature processing Reviewed-by: mullan --- .../xml/crypto/dsig/ValidationTests.java | 34 ++++++++++++++++--- .../signature-extra-text-in-signed-info.xml | 3 ++ .../dsig/data/signature-no-reference-uri.xml | 3 ++ ...rong-canonicalization-method-algorithm.xml | 3 ++ ...ature-wrong-signature-method-algorithm.xml | 3 ++ .../dsig/data/signature-wrong-tag-names.xml | 3 ++ .../signature-wrong-transform-algorithm.xml | 4 +++ 7 files changed, 48 insertions(+), 5 deletions(-) create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-extra-text-in-signed-info.xml create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-no-reference-uri.xml create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-wrong-canonicalization-method-algorithm.xml create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-wrong-signature-method-algorithm.xml create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-wrong-tag-names.xml create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-wrong-transform-algorithm.xml diff --git a/jdk/test/javax/xml/crypto/dsig/ValidationTests.java b/jdk/test/javax/xml/crypto/dsig/ValidationTests.java index 3480f23b2be..d7384815f44 100644 --- a/jdk/test/javax/xml/crypto/dsig/ValidationTests.java +++ b/jdk/test/javax/xml/crypto/dsig/ValidationTests.java @@ -35,6 +35,7 @@ import java.io.FileInputStream; import java.security.*; import javax.xml.crypto.Data; import javax.xml.crypto.KeySelector; +import javax.xml.crypto.MarshalException; import javax.xml.crypto.OctetStreamData; import javax.xml.crypto.URIDereferencer; import javax.xml.crypto.URIReference; @@ -60,9 +61,17 @@ public class ValidationTests { static class Test { String file; KeySelector ks; - Test(String file, KeySelector ks) { + Class exception; + + Test(String file, KeySelector ks, Class exception) { this.file = file; this.ks = ks; + this.exception = exception; + } + + // XMLSignatureException is expected by default + Test(String file, KeySelector ks) { + this(file, ks, XMLSignatureException.class); } } @@ -110,7 +119,17 @@ public class ValidationTests { private final static Test[] INVALID_TESTS = { new Test("signature-enveloping-hmac-sha1-40.xml", SKKS), new Test("signature-enveloping-hmac-sha1-trunclen-0-attack.xml", SKKS), - new Test("signature-enveloping-hmac-sha1-trunclen-8-attack.xml", SKKS) + new Test("signature-enveloping-hmac-sha1-trunclen-8-attack.xml", SKKS), + new Test("signature-extra-text-in-signed-info.xml", SKKS, + MarshalException.class), + new Test("signature-wrong-canonicalization-method-algorithm.xml", SKKS, + MarshalException.class), + new Test("signature-wrong-transform-algorithm.xml", SKKS, + MarshalException.class), + new Test("signature-no-reference-uri.xml", SKKS), + new Test("signature-wrong-signature-method-algorithm.xml", SKKS, + MarshalException.class), + new Test("signature-wrong-tag-names.xml", SKKS, MarshalException.class) }; public static void main(String args[]) throws Exception { @@ -143,9 +162,14 @@ public class ValidationTests { test_signature(test); System.out.println("FAILED"); atLeastOneFailed = true; - } catch (XMLSignatureException xse) { - System.out.println(xse.getMessage()); - System.out.println("PASSED"); + } catch (Exception e) { + System.out.println("Exception: " + e); + if (e.getClass() != test.exception) { + System.out.println("FAILED: unexpected exception"); + atLeastOneFailed = true; + } else { + System.out.println("PASSED"); + } } } diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-extra-text-in-signed-info.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-extra-text-in-signed-info.xml new file mode 100644 index 00000000000..578e7bb16e9 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-extra-text-in-signed-info.xml @@ -0,0 +1,3 @@ +test1Bq8FsjajUBYPD7stQeJSc66GlM=extra textiTrgJERmYeD5hFwY8/MwJpkF+nd++AAOgf/Kxt9SwdE6BIYq2Vyxq4CQPhD+t2971BGTgvF6ejZd ++/Ko4Zs5Dqf4Lt65Vck0q43rM0PdP1e8gJov0IPYnZ1zeqFpah+N/OjmqTbshaZWRIjf3eqS6en5 +ZKjn+TkCQ1kOX/YUNDc= \ No newline at end of file diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-no-reference-uri.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-no-reference-uri.xml new file mode 100644 index 00000000000..eb199f79df2 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-no-reference-uri.xml @@ -0,0 +1,3 @@ +test1Bq8FsjajUBYPD7stQeJSc66GlM=BNPSYlNcyXcO/Tc1tr9mQ/KAZ40eFybLTDyB/HH1EHHMpc972A+nOX2EWBaLsVgG8apl0Isp1ZqV +gmoDHNF6xrcJJQVydVJzU08GVV4GiXHMqRYQbted7STQLhlhssvNNdMEoVApsX5ByL66wxKZQXrT +z1kZtOHAi88DOrmIJu0= \ No newline at end of file diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-canonicalization-method-algorithm.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-canonicalization-method-algorithm.xml new file mode 100644 index 00000000000..2ce430e1de9 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-canonicalization-method-algorithm.xml @@ -0,0 +1,3 @@ +test1Bq8FsjajUBYPD7stQeJSc66GlM=EBbyEV7e+1CTUsyCTyxiN8p+U3/za1oTjK7q+kF8Q87r8e/7C1z4ndGWbk6zyI3w6leT+I2suW9U +KkdvkrDXX2OyLw0GfgJfLkNn+1pGK6kyWpL95NoWJZhHkUAKKBZ0ikfZ4j33gYxrYK+IYCLeZYzr +hlZjdXXXCiSH0Sq+weQ= \ No newline at end of file diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-signature-method-algorithm.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-signature-method-algorithm.xml new file mode 100644 index 00000000000..a2709caec76 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-signature-method-algorithm.xml @@ -0,0 +1,3 @@ +test1Bq8FsjajUBYPD7stQeJSc66GlM=RjL9nfQg9u6+KEFfAlBBH7E7ilFgB7YEQ5MxOIJN/fOdQmc5iDD+YuhiHzNGXGi/UOyo6t8LxTxl +X4oFE1RNlPVkSAZK4LcTWhVa757WwgW1/EZo8PQYWp5NScLq6PumYaujoovSYBKW2N6+jQpnD/L6 +4cuEVNnwEFqvOLrjogY= \ No newline at end of file diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-tag-names.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-tag-names.xml new file mode 100644 index 00000000000..152eb791985 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-tag-names.xml @@ -0,0 +1,3 @@ +test1Bq8FsjajUBYPD7stQeJSc66GlM=cbNpPGavhM0BGUtrvLxvy2SCIt+I27BPpVEt0Q9mXrdPYurMqWF/67AdY9m5RqS7+ZZlwUtem083 +MczRYbKoOIq7sMbCqKKdzbSE/U6rfmky/ACQ5wgemZl8jtipwu5LhAUzjhzT8hhTjVqOYpHdkVJz +l9dnd9eWbLmEr3BI0VA= \ No newline at end of file diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-transform-algorithm.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-transform-algorithm.xml new file mode 100644 index 00000000000..a64abc75c46 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-wrong-transform-algorithm.xml @@ -0,0 +1,4 @@ + +test1Bq8FsjajUBYPD7stQeJSc66GlM=Wzyx3jgEKGwY+pBXBmqWLWhASHQYCCGZVii5sKKKeZUBKxNBthjiSVfzKANuLgX6zAt16XRycrSL +zFKTPuvGeWVPDvd+KTNKCJxN9ccrG7v23EM7RY2eMJGu2r5DLfKwV7H6YuJPsOuWifVkKAhvq7gd +6akJshxyAj9Ud+mjo48= \ No newline at end of file From 7e89934d9ee507b9cef08552f69f5e9a10ead61e Mon Sep 17 00:00:00 2001 From: Ivan Gerasimov Date: Mon, 18 May 2015 17:38:38 +0300 Subject: [PATCH 46/70] 8080522: Optimize string operations in java.base/share/classes/sun/security/x509/ Reviewed-by: mullan --- .../share/classes/sun/security/x509/AVA.java | 14 ++-- .../x509/AuthorityKeyIdentifierExtension.java | 13 ++-- .../x509/BasicConstraintsExtension.java | 14 ++-- .../x509/CRLDistributionPointsExtension.java | 8 +- .../sun/security/x509/CRLNumberExtension.java | 23 +++--- .../sun/security/x509/CertException.java | 4 +- .../x509/CertificatePoliciesExtension.java | 8 +- .../security/x509/CertificateValidity.java | 4 +- .../sun/security/x509/DistributionPoint.java | 14 +++- .../security/x509/DistributionPointName.java | 8 +- .../sun/security/x509/EDIPartyName.java | 13 +++- .../classes/sun/security/x509/Extension.java | 9 +-- .../sun/security/x509/GeneralSubtree.java | 25 ++++--- .../sun/security/x509/GeneralSubtrees.java | 3 +- .../sun/security/x509/IPAddressName.java | 4 +- .../x509/IssuerAlternativeNameExtension.java | 19 +++-- .../IssuingDistributionPointExtension.java | 35 ++++----- .../x509/NameConstraintsExtension.java | 19 +++-- .../x509/PolicyConstraintsExtension.java | 31 ++++---- .../sun/security/x509/PolicyInformation.java | 4 +- .../x509/PrivateKeyUsageExtension.java | 21 ++++-- .../share/classes/sun/security/x509/RDN.java | 18 ++--- .../sun/security/x509/SerialNumber.java | 2 +- .../x509/SubjectInfoAccessExtension.java | 4 +- .../x509/SubjectKeyIdentifierExtension.java | 4 +- .../classes/sun/security/x509/X500Name.java | 54 ++++++-------- .../sun/security/x509/X509CRLEntryImpl.java | 31 +++++--- .../sun/security/x509/X509CRLImpl.java | 74 ++++++++++++------- .../sun/security/x509/X509CertImpl.java | 32 +++----- .../sun/security/x509/X509CertInfo.java | 47 ++++++------ 30 files changed, 305 insertions(+), 254 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/security/x509/AVA.java b/jdk/src/java.base/share/classes/sun/security/x509/AVA.java index d1f94fb23a4..c75030a21a7 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/AVA.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/AVA.java @@ -454,7 +454,7 @@ public class AVA implements DerEncoder { if (embeddedHex.size() > 0) { // add space(s) before embedded hex bytes for (int i = 0; i < spaceCount; i++) { - temp.append(" "); + temp.append(' '); } spaceCount = 0; @@ -472,7 +472,7 @@ public class AVA implements DerEncoder { } else { // add space(s) for (int i = 0; i < spaceCount; i++) { - temp.append(" "); + temp.append(' '); } spaceCount = 0; temp.append((char)c); @@ -853,7 +853,7 @@ public class AVA implements DerEncoder { } sbuffer.append(c); } - typeAndValue.append(sbuffer.toString()); + typeAndValue.append(sbuffer); } return typeAndValue.toString(); } @@ -1039,7 +1039,7 @@ public class AVA implements DerEncoder { StringBuilder retval = new StringBuilder(40); retval.append(keyword); - retval.append("="); + retval.append('='); try { String valStr = value.getAsString(); @@ -1147,9 +1147,11 @@ public class AVA implements DerEncoder { // Emit the string ... quote it if needed // if string is already quoted, don't re-quote if (!alreadyQuoted && quoteNeeded) { - retval.append("\"" + sbuffer.toString() + "\""); + retval.append('\"') + .append(sbuffer) + .append('\"'); } else { - retval.append(sbuffer.toString()); + retval.append(sbuffer); } } } catch (IOException e) { diff --git a/jdk/src/java.base/share/classes/sun/security/x509/AuthorityKeyIdentifierExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/AuthorityKeyIdentifierExtension.java index a8b04dea2b8..14754b2536c 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/AuthorityKeyIdentifierExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/AuthorityKeyIdentifierExtension.java @@ -196,17 +196,20 @@ implements CertAttrSet { * Return the object as a string. */ public String toString() { - String s = super.toString() + "AuthorityKeyIdentifier [\n"; + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()) + .append("AuthorityKeyIdentifier [\n"); if (id != null) { - s += id.toString(); // id already has a newline + sb.append(id); // id already has a newline } if (names != null) { - s += names.toString() + "\n"; + sb.append(names).append('\n'); } if (serialNum != null) { - s += serialNum.toString() + "\n"; + sb.append(serialNum).append('\n'); } - return (s + "]\n"); + sb.append("]\n"); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/BasicConstraintsExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/BasicConstraintsExtension.java index 35c8cfc65b9..65e62ec25c0 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/BasicConstraintsExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/BasicConstraintsExtension.java @@ -171,15 +171,11 @@ implements CertAttrSet { * Return user readable form of extension. */ public String toString() { - String s = super.toString() + "BasicConstraints:[\n"; - - s += ((ca) ? (" CA:true") : (" CA:false")) + "\n"; - if (pathLen >= 0) { - s += " PathLen:" + pathLen + "\n"; - } else { - s += " PathLen: undefined\n"; - } - return (s + "]\n"); + return super.toString() + + "BasicConstraints:[\n CA:" + ca + + "\n PathLen:" + + ((pathLen >= 0) ? String.valueOf(pathLen) : " undefined") + + "\n]\n"; } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/CRLDistributionPointsExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/CRLDistributionPointsExtension.java index eb2b0801fb8..d60f7f13079 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/CRLDistributionPointsExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/CRLDistributionPointsExtension.java @@ -231,8 +231,8 @@ public class CRLDistributionPointsExtension extends Extension distributionPoints = (List)obj; } else { throw new IOException("Attribute name [" + name + - "] not recognized by " + - "CertAttrSet:" + extensionName + "."); + "] not recognized by " + + "CertAttrSet:" + extensionName + '.'); } encodeThis(); } @@ -245,8 +245,8 @@ public class CRLDistributionPointsExtension extends Extension return distributionPoints; } else { throw new IOException("Attribute name [" + name + - "] not recognized by " + - "CertAttrSet:" + extensionName + "."); + "] not recognized by " + + "CertAttrSet:" + extensionName + '.'); } } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/CRLNumberExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/CRLNumberExtension.java index 9649df6aa94..7a66f0b935f 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/CRLNumberExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/CRLNumberExtension.java @@ -146,8 +146,8 @@ implements CertAttrSet { } crlNumber = (BigInteger)obj; } else { - throw new IOException("Attribute name not recognized by" - + " CertAttrSet:" + extensionName + "."); + throw new IOException("Attribute name not recognized by" + + " CertAttrSet:" + extensionName + '.'); } encodeThis(); } @@ -172,8 +172,8 @@ implements CertAttrSet { if (name.equalsIgnoreCase(NUMBER)) { crlNumber = null; } else { - throw new IOException("Attribute name not recognized by" - + " CertAttrSet:" + extensionName + "."); + throw new IOException("Attribute name not recognized by" + + " CertAttrSet:" + extensionName + '.'); } encodeThis(); } @@ -182,10 +182,15 @@ implements CertAttrSet { * Returns a printable representation of the CRLNumberExtension. */ public String toString() { - String s = super.toString() + extensionLabel + ": " + - ((crlNumber == null) ? "" : Debug.toHexString(crlNumber)) - + "\n"; - return (s); + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()) + .append(extensionLabel) + .append(": "); + if (crlNumber != null) { + sb.append(Debug.toHexString(crlNumber)); + } + sb.append('\n'); + return sb.toString(); } /** @@ -195,7 +200,7 @@ implements CertAttrSet { * @exception IOException on encoding errors. */ public void encode(OutputStream out) throws IOException { - DerOutputStream tmp = new DerOutputStream(); + DerOutputStream tmp = new DerOutputStream(); encode(out, PKIXExtensions.CRLNumber_Id, true); } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/CertException.java b/jdk/src/java.base/share/classes/sun/security/x509/CertException.java index 585d1f825ea..4c2dcc6cfb9 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/CertException.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/CertException.java @@ -158,7 +158,7 @@ public class CertException extends SecurityException { */ public String toString() { - return "[Certificate Exception: " + getMessage() + "]"; + return "[Certificate Exception: " + getMessage() + ']'; } /** @@ -168,6 +168,6 @@ public class CertException extends SecurityException { { return getVerfDescription() + ( (moreData != null) - ? ( "\n (" + moreData + ")" ) : "" ); + ? ( "\n (" + moreData + ')' ) : "" ); } } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/CertificatePoliciesExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/CertificatePoliciesExtension.java index 4f04bedd37c..925936658f7 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/CertificatePoliciesExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/CertificatePoliciesExtension.java @@ -160,10 +160,12 @@ implements CertAttrSet { if (certPolicies == null) { return ""; } - StringBuilder sb = new StringBuilder(super.toString()); - sb.append("CertificatePolicies [\n"); + + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()) + .append("CertificatePolicies [\n"); for (PolicyInformation info : certPolicies) { - sb.append(info.toString()); + sb.append(info); } sb.append("]\n"); return sb.toString(); diff --git a/jdk/src/java.base/share/classes/sun/security/x509/CertificateValidity.java b/jdk/src/java.base/share/classes/sun/security/x509/CertificateValidity.java index cd9b00fa235..29852d35e28 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/CertificateValidity.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/CertificateValidity.java @@ -134,8 +134,8 @@ public class CertificateValidity implements CertAttrSet { public String toString() { if (notBefore == null || notAfter == null) return ""; - return ("Validity: [From: " + notBefore.toString() + - ",\n To: " + notAfter.toString() + "]"); + return "Validity: [From: " + notBefore + + ",\n To: " + notAfter + ']'; } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/DistributionPoint.java b/jdk/src/java.base/share/classes/sun/security/x509/DistributionPoint.java index 29b5f933dd3..e2d4971dd1a 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/DistributionPoint.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/DistributionPoint.java @@ -380,23 +380,29 @@ public class DistributionPoint { */ public String toString() { StringBuilder sb = new StringBuilder(); + sb.append("DistributionPoint:\n "); if (fullName != null) { - sb.append("DistributionPoint:\n " + fullName + "\n"); + sb.append(fullName); } if (relativeName != null) { - sb.append("DistributionPoint:\n " + relativeName + "\n"); + sb.append(relativeName); } + sb.append('\n'); if (reasonFlags != null) { sb.append(" ReasonFlags:\n"); for (int i = 0; i < reasonFlags.length; i++) { if (reasonFlags[i]) { - sb.append(" " + reasonToString(i) + "\n"); + sb.append(" ") + .append(reasonToString(i)) + .append('\n'); } } } if (crlIssuer != null) { - sb.append(" CRLIssuer:" + crlIssuer + "\n"); + sb.append(" CRLIssuer:") + .append(crlIssuer) + .append('\n'); } return sb.toString(); } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/DistributionPointName.java b/jdk/src/java.base/share/classes/sun/security/x509/DistributionPointName.java index 4409dc0c6c2..36fe6170bfd 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/DistributionPointName.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/DistributionPointName.java @@ -230,13 +230,13 @@ public class DistributionPointName { */ public String toString() { StringBuilder sb = new StringBuilder(); + sb.append("DistributionPointName:\n "); if (fullName != null) { - sb.append("DistributionPointName:\n " + fullName + "\n"); - + sb.append(fullName); } else { - sb.append("DistributionPointName:\n " + relativeName + "\n"); + sb.append(relativeName); } - + sb.append('\n'); return sb.toString(); } } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/EDIPartyName.java b/jdk/src/java.base/share/classes/sun/security/x509/EDIPartyName.java index e6a8c3bb076..74c0e4df7d4 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/EDIPartyName.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/EDIPartyName.java @@ -209,10 +209,15 @@ public class EDIPartyName implements GeneralNameInterface { * Return the printable string. */ public String toString() { - return ("EDIPartyName: " + - ((assigner == null) ? "" : - (" nameAssigner = " + assigner + ",")) - + " partyName = " + party); + StringBuilder sb = new StringBuilder("EDIPartyName: "); + if (assigner != null) { + sb.append(" nameAssigner = ") + .append(assigner) + .append(','); + } + sb.append(" partyName = ") + .append(party); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/Extension.java b/jdk/src/java.base/share/classes/sun/security/x509/Extension.java index 04489d70094..d3a711e4b5e 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/Extension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/Extension.java @@ -219,13 +219,8 @@ public class Extension implements java.security.cert.Extension { * Returns the Extension in user readable form. */ public String toString() { - String s = "ObjectId: " + extensionId.toString(); - if (critical) { - s += " Criticality=true\n"; - } else { - s += " Criticality=false\n"; - } - return (s); + return "ObjectId: " + extensionId + + " Criticality=" + critical + '\n'; } // Value to mix up the hash diff --git a/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtree.java b/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtree.java index bbd2b2586bd..5635c2b9281 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtree.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtree.java @@ -127,15 +127,22 @@ public class GeneralSubtree { * Return a printable string of the GeneralSubtree. */ public String toString() { - String s = "\n GeneralSubtree: [\n" + - " GeneralName: " + ((name == null) ? "" : name.toString()) + - "\n Minimum: " + minimum; - if (maximum == -1) { - s += "\t Maximum: undefined"; - } else - s += "\t Maximum: " + maximum; - s += " ]\n"; - return (s); + StringBuilder sb = new StringBuilder(); + sb.append("\n GeneralSubtree: [") + .append("\n GeneralName: "); + if (name != null) { + sb.append(name); + } + sb.append("\n Minimum: ") + .append(minimum) + .append("\n Maximum: "); + if (maximum == -1) { + sb.append("undefined"); + } else { + sb.append(maximum); + } + sb.append(" ]\n"); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtrees.java b/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtrees.java index 40c4db15986..5a1f8c7de65 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtrees.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/GeneralSubtrees.java @@ -124,8 +124,7 @@ public class GeneralSubtrees implements Cloneable { * Return a printable string of the GeneralSubtree. */ public String toString() { - String s = " GeneralSubtrees:\n" + trees.toString() + "\n"; - return s; + return " GeneralSubtrees:\n" + trees + '\n'; } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/IPAddressName.java b/jdk/src/java.base/share/classes/sun/security/x509/IPAddressName.java index d9dd126baaa..6d2e78305d5 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/IPAddressName.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/IPAddressName.java @@ -263,7 +263,7 @@ public class IPAddressName implements GeneralNameInterface { if (address.length == 8) { byte[] mask = new byte[4]; System.arraycopy(address, 4, mask, 0, 4); - name = name + "/" + + name = name + '/' + InetAddress.getByAddress(mask).getHostAddress(); } } else { @@ -285,7 +285,7 @@ public class IPAddressName implements GeneralNameInterface { if (!ba.get(i)) break; } - name = name + "/" + i; + name = name + '/' + i; // Verify remaining bits 0 for (; i < 16*8; i++) { if (ba.get(i)) { diff --git a/jdk/src/java.base/share/classes/sun/security/x509/IssuerAlternativeNameExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/IssuerAlternativeNameExtension.java index ba1f584612a..da7dde9a9b8 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/IssuerAlternativeNameExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/IssuerAlternativeNameExtension.java @@ -140,17 +140,20 @@ extends Extension implements CertAttrSet { * Returns a printable representation of the IssuerAlternativeName. */ public String toString() { - - String result = super.toString() + "IssuerAlternativeName [\n"; - if(names == null) { - result += " null\n"; + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()) + .append("IssuerAlternativeName [\n"); + if (names == null) { + sb.append(" null\n"); } else { - for(GeneralName name: names.names()) { - result += " "+name+"\n"; + for (GeneralName name : names.names()) { + sb.append(" ") + .append(name) + .append('\n'); } } - result += "]\n"; - return result; + sb.append("]\n"); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/IssuingDistributionPointExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/IssuingDistributionPointExtension.java index 4be49475ded..26dd18a352b 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/IssuingDistributionPointExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/IssuingDistributionPointExtension.java @@ -441,9 +441,9 @@ public class IssuingDistributionPointExtension extends Extension * Returns the extension as user readable string. */ public String toString() { - - StringBuilder sb = new StringBuilder(super.toString()); - sb.append("IssuingDistributionPoint [\n "); + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()) + .append("IssuingDistributionPoint [\n "); if (distributionPoint != null) { sb.append(distributionPoint); @@ -453,23 +453,18 @@ public class IssuingDistributionPointExtension extends Extension sb.append(revocationReasons); } - sb.append((hasOnlyUserCerts) - ? (" Only contains user certs: true") - : (" Only contains user certs: false")).append("\n"); - - sb.append((hasOnlyCACerts) - ? (" Only contains CA certs: true") - : (" Only contains CA certs: false")).append("\n"); - - sb.append((hasOnlyAttributeCerts) - ? (" Only contains attribute certs: true") - : (" Only contains attribute certs: false")).append("\n"); - - sb.append((isIndirectCRL) - ? (" Indirect CRL: true") - : (" Indirect CRL: false")).append("\n"); - - sb.append("]\n"); + sb.append(" Only contains user certs: ") + .append(hasOnlyUserCerts) + .append('\n') + .append(" Only contains CA certs: ") + .append(hasOnlyCACerts) + .append('\n') + .append(" Only contains attribute certs: ") + .append(hasOnlyAttributeCerts) + .append('\n') + .append(" Indirect CRL: ") + .append(isIndirectCRL) + .append("\n]\n"); return sb.toString(); } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java index a8d46a8a8d0..4d1e4cdd126 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/NameConstraintsExtension.java @@ -214,12 +214,19 @@ implements CertAttrSet, Cloneable { * Return the printable string. */ public String toString() { - return (super.toString() + "NameConstraints: [" + - ((permitted == null) ? "" : - ("\n Permitted:" + permitted.toString())) + - ((excluded == null) ? "" : - ("\n Excluded:" + excluded.toString())) - + " ]\n"); + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()) + .append("NameConstraints: ["); + if (permitted != null) { + sb.append("\n Permitted:") + .append(permitted); + } + if (excluded != null) { + sb.append("\n Excluded:") + .append(excluded); + } + sb.append(" ]\n"); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/PolicyConstraintsExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/PolicyConstraintsExtension.java index 3b0543b202f..eca45828aa6 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/PolicyConstraintsExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/PolicyConstraintsExtension.java @@ -175,19 +175,24 @@ implements CertAttrSet { * Return the extension as user readable string. */ public String toString() { - String s; - s = super.toString() + "PolicyConstraints: [" + " Require: "; - if (require == -1) - s += "unspecified;"; - else - s += require + ";"; - s += "\tInhibit: "; - if (inhibit == -1) - s += "unspecified"; - else - s += inhibit; - s += " ]\n"; - return s; + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()) + .append("PolicyConstraints: [") + .append(" Require: "); + if (require == -1) { + sb.append("unspecified;"); + } else { + sb.append(require) + .append(';'); + } + sb.append("\tInhibit: "); + if (inhibit == -1) { + sb.append("unspecified"); + } else { + sb.append(inhibit); + } + sb.append(" ]\n"); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/PolicyInformation.java b/jdk/src/java.base/share/classes/sun/security/x509/PolicyInformation.java index 0e98e425cd7..491b2b99c0a 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/PolicyInformation.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/PolicyInformation.java @@ -258,9 +258,7 @@ public class PolicyInformation { * Return a printable representation of the PolicyInformation. */ public String toString() { - StringBuilder s = new StringBuilder(" [" + policyIdentifier.toString()); - s.append(policyQualifiers + " ]\n"); - return s.toString(); + return " [" + policyIdentifier + policyQualifiers + " ]\n"; } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/PrivateKeyUsageExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/PrivateKeyUsageExtension.java index c20d8557b03..0cb40155025 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/PrivateKeyUsageExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/PrivateKeyUsageExtension.java @@ -175,11 +175,22 @@ implements CertAttrSet { * Return the printable string. */ public String toString() { - return(super.toString() + - "PrivateKeyUsage: [\n" + - ((notBefore == null) ? "" : "From: " + notBefore.toString() + ", ") - + ((notAfter == null) ? "" : "To: " + notAfter.toString()) - + "]\n"); + StringBuilder sb = new StringBuilder(); + sb.append(super.toString()) + .append("PrivateKeyUsage: [\n"); + if (notBefore != null) { + sb.append("From: ") + .append(notBefore); + if (notAfter != null) { + sb.append(", "); + } + } + if (notAfter != null) { + sb.append("To: ") + .append(notAfter); + } + sb.append("]\n"); + return sb.toString(); } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/RDN.java b/jdk/src/java.base/share/classes/sun/security/x509/RDN.java index aa492e4e127..6ba421d3b27 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/RDN.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/RDN.java @@ -348,14 +348,11 @@ public class RDN { return assertion[0].toString(); } - StringBuilder sb = new StringBuilder(); + StringJoiner sj = new StringJoiner(" + "); for (int i = 0; i < assertion.length; i++) { - if (i != 0) { - sb.append(" + "); - } - sb.append(assertion[i].toString()); + sj.add(assertion[i].toString()); } - return sb.toString(); + return sj.toString(); } /* @@ -376,14 +373,11 @@ public class RDN { return assertion[0].toRFC1779String(oidMap); } - StringBuilder sb = new StringBuilder(); + StringJoiner sj = new StringJoiner(" + "); for (int i = 0; i < assertion.length; i++) { - if (i != 0) { - sb.append(" + "); - } - sb.append(assertion[i].toRFC1779String(oidMap)); + sj.add(assertion[i].toRFC1779String(oidMap)); } - return sb.toString(); + return sj.toString(); } /* diff --git a/jdk/src/java.base/share/classes/sun/security/x509/SerialNumber.java b/jdk/src/java.base/share/classes/sun/security/x509/SerialNumber.java index c61be63edae..2264edfd4ab 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/SerialNumber.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/SerialNumber.java @@ -101,7 +101,7 @@ public class SerialNumber { * Return the SerialNumber as user readable string. */ public String toString() { - return ("SerialNumber: [" + Debug.toHexString(serialNum) + "]"); + return "SerialNumber: [" + Debug.toHexString(serialNum) + ']'; } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/SubjectInfoAccessExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/SubjectInfoAccessExtension.java index 43defaaa176..8daa0b319b4 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/SubjectInfoAccessExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/SubjectInfoAccessExtension.java @@ -238,8 +238,8 @@ public class SubjectInfoAccessExtension extends Extension * Return the extension as user readable string. */ public String toString() { - return super.toString() + "SubjectInfoAccess [\n " - + accessDescriptions + "\n]\n"; + return super.toString() + + "SubjectInfoAccess [\n " + accessDescriptions + "\n]\n"; } } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/SubjectKeyIdentifierExtension.java b/jdk/src/java.base/share/classes/sun/security/x509/SubjectKeyIdentifierExtension.java index 79482c9bfe8..b3dd2132407 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/SubjectKeyIdentifierExtension.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/SubjectKeyIdentifierExtension.java @@ -115,8 +115,8 @@ implements CertAttrSet { * Returns a printable representation. */ public String toString() { - return super.toString() + "SubjectKeyIdentifier [\n" - + String.valueOf(id) + "]\n"; + return super.toString() + + "SubjectKeyIdentifier [\n" + id + "]\n"; } /** diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java b/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java index 578f8026666..79d64e84555 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X500Name.java @@ -31,6 +31,7 @@ import java.security.PrivilegedExceptionAction; import java.security.AccessController; import java.security.Principal; import java.util.*; +import java.util.StringJoiner; import sun.security.util.*; import javax.security.auth.x500.X500Principal; @@ -689,14 +690,11 @@ public class X500Name implements GeneralNameInterface, Principal { * The encodings of adjoining RelativeDistinguishedNames are separated * by a comma character (',' ASCII 44). */ - StringBuilder fullname = new StringBuilder(48); + StringJoiner sj = new StringJoiner(","); for (int i = names.length - 1; i >= 0; i--) { - if (i < names.length - 1) { - fullname.append(','); - } - fullname.append(names[i].toRFC2253String(oidMap)); + sj.add(names[i].toRFC2253String(oidMap)); } - return fullname.toString(); + return sj.toString(); } public String getRFC2253CanonicalName() { @@ -722,14 +720,11 @@ public class X500Name implements GeneralNameInterface, Principal { * The encodings of adjoining RelativeDistinguishedNames are separated * by a comma character (',' ASCII 44). */ - StringBuilder fullname = new StringBuilder(48); + StringJoiner sj = new StringJoiner(","); for (int i = names.length - 1; i >= 0; i--) { - if (i < names.length - 1) { - fullname.append(','); - } - fullname.append(names[i].toRFC2253String(true)); + sj.add(names[i].toRFC2253String(true)); } - canonicalDn = fullname.toString(); + canonicalDn = sj.toString(); return canonicalDn; } @@ -1064,16 +1059,16 @@ public class X500Name implements GeneralNameInterface, Principal { return; } - StringBuilder sb = new StringBuilder(48); - if (names != null) { - for (int i = names.length - 1; i >= 0; i--) { - if (i != names.length - 1) { - sb.append(", "); - } - sb.append(names[i].toString()); - } + if (names == null) { + dn = ""; + return; } - dn = sb.toString(); + + StringJoiner sj = new StringJoiner(", "); + for (int i = names.length - 1; i >= 0; i--) { + sj.add(names[i].toString()); + } + dn = sj.toString(); } /* @@ -1090,16 +1085,15 @@ public class X500Name implements GeneralNameInterface, Principal { return names[0].toRFC1779String(oidMap); } - StringBuilder sb = new StringBuilder(48); - if (names != null) { - for (int i = names.length - 1; i >= 0; i--) { - if (i != names.length - 1) { - sb.append(", "); - } - sb.append(names[i].toRFC1779String(oidMap)); - } + if (names == null) { + return ""; } - return sb.toString(); + + StringJoiner sj = new StringJoiner(", "); + for (int i = names.length - 1; i >= 0; i--) { + sj.add(names[i].toRFC1779String(oidMap)); + } + return sj.toString(); } /****************************************************************/ diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X509CRLEntryImpl.java b/jdk/src/java.base/share/classes/sun/security/x509/X509CRLEntryImpl.java index ccc7b893430..8646b43841a 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X509CRLEntryImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X509CRLEntryImpl.java @@ -291,40 +291,47 @@ public class X509CRLEntryImpl extends X509CRLEntry public String toString() { StringBuilder sb = new StringBuilder(); - sb.append(serialNumber.toString()); - sb.append(" On: " + revocationDate.toString()); + sb.append(serialNumber) + .append(" On: ") + .append(revocationDate); if (certIssuer != null) { - sb.append("\n Certificate issuer: " + certIssuer); + sb.append("\n Certificate issuer: ") + .append(certIssuer); } if (extensions != null) { Collection allEntryExts = extensions.getAllExtensions(); Extension[] exts = allEntryExts.toArray(new Extension[0]); - sb.append("\n CRL Entry Extensions: " + exts.length); + sb.append("\n CRL Entry Extensions: ") + .append(exts.length); for (int i = 0; i < exts.length; i++) { - sb.append("\n [" + (i+1) + "]: "); + sb.append("\n [") + .append(i+1) + .append("]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { - sb.append(ext.toString()); + sb.append(ext); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); - sb.append("Extension unknown: " - + "DER encoded OCTET string =\n" - + enc.encodeBuffer(extValue) + "\n"); + sb.append("Extension unknown: ") + .append("DER encoded OCTET string =\n") + .append(enc.encodeBuffer(extValue)) + .append('\n'); } - } else - sb.append(ext.toString()); //sub-class exists + } else { + sb.append(ext); //sub-class exists + } } catch (Exception e) { sb.append(", Error parsing this extension"); } } } - sb.append("\n"); + sb.append('\n'); return sb.toString(); } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java b/jdk/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java index 3797105c770..7a68cebdabb 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X509CRLImpl.java @@ -537,47 +537,65 @@ public class X509CRLImpl extends X509CRL implements DerEncoder { */ public String toString() { StringBuilder sb = new StringBuilder(); - sb.append("X.509 CRL v" + (version+1) + "\n"); + sb.append("X.509 CRL v") + .append(version+1) + .append('\n'); if (sigAlgId != null) - sb.append("Signature Algorithm: " + sigAlgId.toString() + - ", OID=" + (sigAlgId.getOID()).toString() + "\n"); + sb.append("Signature Algorithm: ") + .append(sigAlgId) + .append(", OID=") + .append(sigAlgId.getOID()) + .append('\n'); if (issuer != null) - sb.append("Issuer: " + issuer.toString() + "\n"); + sb.append("Issuer: ") + .append(issuer) + .append('\n'); if (thisUpdate != null) - sb.append("\nThis Update: " + thisUpdate.toString() + "\n"); + sb.append("\nThis Update: ") + .append(thisUpdate) + .append('\n'); if (nextUpdate != null) - sb.append("Next Update: " + nextUpdate.toString() + "\n"); + sb.append("Next Update: ") + .append(nextUpdate) + .append('\n'); if (revokedList.isEmpty()) sb.append("\nNO certificates have been revoked\n"); else { - sb.append("\nRevoked Certificates: " + revokedList.size()); + sb.append("\nRevoked Certificates: ") + .append(revokedList.size()); int i = 1; for (X509CRLEntry entry: revokedList) { - sb.append("\n[" + i++ + "] " + entry.toString()); + sb.append("\n[") + .append(i++) + .append("] ") + .append(entry); } } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Object[] objs = allExts.toArray(); - sb.append("\nCRL Extensions: " + objs.length); + sb.append("\nCRL Extensions: ") + .append(objs.length); for (int i = 0; i < objs.length; i++) { - sb.append("\n[" + (i+1) + "]: "); + sb.append("\n[").append(i+1).append("]: "); Extension ext = (Extension)objs[i]; try { - if (OIDMap.getClass(ext.getExtensionId()) == null) { - sb.append(ext.toString()); - byte[] extValue = ext.getExtensionValue(); - if (extValue != null) { - DerOutputStream out = new DerOutputStream(); - out.putOctetString(extValue); - extValue = out.toByteArray(); - HexDumpEncoder enc = new HexDumpEncoder(); - sb.append("Extension unknown: " - + "DER encoded OCTET string =\n" - + enc.encodeBuffer(extValue) + "\n"); - } - } else - sb.append(ext.toString()); // sub-class exists + if (OIDMap.getClass(ext.getExtensionId()) == null) { + sb.append(ext); + byte[] extValue = ext.getExtensionValue(); + if (extValue != null) { + DerOutputStream out = new DerOutputStream(); + out.putOctetString(extValue); + extValue = out.toByteArray(); + HexDumpEncoder enc = new HexDumpEncoder(); + sb.append("Extension unknown: ") + .append("DER encoded OCTET string =\n") + .append(enc.encodeBuffer(extValue)) + .append('\n'); + } + } else { + sb.append(ext); // sub-class exists + } } catch (Exception e) { sb.append(", Error parsing this extension"); } @@ -585,10 +603,12 @@ public class X509CRLImpl extends X509CRL implements DerEncoder { } if (signature != null) { HexDumpEncoder encoder = new HexDumpEncoder(); - sb.append("\nSignature:\n" + encoder.encodeBuffer(signature) - + "\n"); - } else + sb.append("\nSignature:\n") + .append(encoder.encodeBuffer(signature)) + .append('\n'); + } else { sb.append("NOT signed yet\n"); + } return sb.toString(); } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X509CertImpl.java b/jdk/src/java.base/share/classes/sun/security/x509/X509CertImpl.java index d1142a26336..b74de5a5dfe 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X509CertImpl.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X509CertImpl.java @@ -81,7 +81,7 @@ public class X509CertImpl extends X509Certificate implements DerEncoder { private static final long serialVersionUID = -3457612960190864406L; - private static final String DOT = "."; + private static final char DOT = '.'; /** * Public attribute names. */ @@ -799,17 +799,10 @@ public class X509CertImpl extends X509Certificate implements DerEncoder { if (info == null || algId == null || signature == null) return ""; - StringBuilder sb = new StringBuilder(); - - sb.append("[\n"); - sb.append(info.toString() + "\n"); - sb.append(" Algorithm: [" + algId.toString() + "]\n"); - HexDumpEncoder encoder = new HexDumpEncoder(); - sb.append(" Signature:\n" + encoder.encodeBuffer(signature)); - sb.append("\n]"); - - return sb.toString(); + return "[\n" + info + '\n' + + " Algorithm: [" + algId + "]\n" + + " Signature:\n" + encoder.encodeBuffer(signature) + "\n]"; } // the strongly typed gets, as per java.security.cert.X509Certificate @@ -1941,31 +1934,30 @@ public class X509CertImpl extends X509Certificate implements DerEncoder { * only contains 0-9 and A-F. No small case, no colon. */ private String getCertificateFingerPrint(String mdAlg) { - String fingerPrint = ""; try { byte[] encCertInfo = getEncoded(); MessageDigest md = MessageDigest.getInstance(mdAlg); byte[] digest = md.digest(encCertInfo); - StringBuffer buf = new StringBuffer(); + StringBuilder sb = new StringBuilder(digest.length * 2); for (int i = 0; i < digest.length; i++) { - byte2hex(digest[i], buf); + byte2hex(digest[i], sb); } - fingerPrint = buf.toString(); + return sb.toString(); } catch (NoSuchAlgorithmException | CertificateEncodingException e) { // ignored } - return fingerPrint; + return ""; } /** - * Converts a byte to hex digit and writes to the supplied buffer + * Converts a byte to hex digit and writes to the supplied builder */ - private static void byte2hex(byte b, StringBuffer buf) { + private static void byte2hex(byte b, StringBuilder buf) { char[] hexChars = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; int high = ((b & 0xf0) >> 4); int low = (b & 0x0f); - buf.append(hexChars[high]); - buf.append(hexChars[low]); + buf.append(hexChars[high]) + .append(hexChars[low]); } } diff --git a/jdk/src/java.base/share/classes/sun/security/x509/X509CertInfo.java b/jdk/src/java.base/share/classes/sun/security/x509/X509CertInfo.java index 9411519eec8..cdea7551fa9 100644 --- a/jdk/src/java.base/share/classes/sun/security/x509/X509CertInfo.java +++ b/jdk/src/java.base/share/classes/sun/security/x509/X509CertInfo.java @@ -299,55 +299,60 @@ public class X509CertInfo implements CertAttrSet { } StringBuilder sb = new StringBuilder(); - sb.append("[\n"); - sb.append(" " + version.toString() + "\n"); - sb.append(" Subject: " + subject.toString() + "\n"); - sb.append(" Signature Algorithm: " + algId.toString() + "\n"); - sb.append(" Key: " + pubKey.toString() + "\n"); - sb.append(" " + interval.toString() + "\n"); - sb.append(" Issuer: " + issuer.toString() + "\n"); - sb.append(" " + serialNum.toString() + "\n"); + sb.append("[\n") + .append(" ").append(version).append('\n') + .append(" Subject: ").append(subject).append('\n') + .append(" Signature Algorithm: ").append(algId).append('\n') + .append(" Key: ").append(pubKey).append('\n') + .append(" ").append(interval).append('\n') + .append(" Issuer: ").append(issuer).append('\n') + .append(" ").append(serialNum).append('\n'); // optional v2, v3 extras if (issuerUniqueId != null) { - sb.append(" Issuer Id:\n" + issuerUniqueId.toString() + "\n"); + sb.append(" Issuer Id:\n").append(issuerUniqueId).append('\n'); } if (subjectUniqueId != null) { - sb.append(" Subject Id:\n" + subjectUniqueId.toString() + "\n"); + sb.append(" Subject Id:\n").append(subjectUniqueId).append('\n'); } if (extensions != null) { Collection allExts = extensions.getAllExtensions(); Extension[] exts = allExts.toArray(new Extension[0]); - sb.append("\nCertificate Extensions: " + exts.length); + sb.append("\nCertificate Extensions: ").append(exts.length); for (int i = 0; i < exts.length; i++) { - sb.append("\n[" + (i+1) + "]: "); + sb.append("\n[").append(i+1).append("]: "); Extension ext = exts[i]; try { if (OIDMap.getClass(ext.getExtensionId()) == null) { - sb.append(ext.toString()); + sb.append(ext); byte[] extValue = ext.getExtensionValue(); if (extValue != null) { DerOutputStream out = new DerOutputStream(); out.putOctetString(extValue); extValue = out.toByteArray(); HexDumpEncoder enc = new HexDumpEncoder(); - sb.append("Extension unknown: " - + "DER encoded OCTET string =\n" - + enc.encodeBuffer(extValue) + "\n"); + sb.append("Extension unknown: ") + .append("DER encoded OCTET string =\n") + .append(enc.encodeBuffer(extValue)) + .append('\n'); } - } else - sb.append(ext.toString()); //sub-class exists + } else { + sb.append(ext); //sub-class exists + } } catch (Exception e) { sb.append(", Error parsing this extension"); } } Map invalid = extensions.getUnparseableExtensions(); if (invalid.isEmpty() == false) { - sb.append("\nUnparseable certificate extensions: " + invalid.size()); + sb.append("\nUnparseable certificate extensions: ") + .append(invalid.size()); int i = 1; for (Extension ext : invalid.values()) { - sb.append("\n[" + (i++) + "]: "); - sb.append(ext); + sb.append("\n[") + .append(i++) + .append("]: ") + .append(ext); } } } From 43b2601a963afb4f2cbb96fb9bb10b893b7e4566 Mon Sep 17 00:00:00 2001 From: Ivan Gerasimov Date: Mon, 18 May 2015 19:15:50 +0300 Subject: [PATCH 47/70] 8080535: (ch) Expected size of Character.UnicodeBlock.map is not optimal Reviewed-by: martin, chegar --- .../share/classes/java/lang/Character.java | 12 +++- .../UnicodeBlock/NonOptimalMapSize.java | 72 +++++++++++++++++++ 2 files changed, 81 insertions(+), 3 deletions(-) create mode 100644 jdk/test/java/lang/Character/UnicodeBlock/NonOptimalMapSize.java diff --git a/jdk/src/java.base/share/classes/java/lang/Character.java b/jdk/src/java.base/share/classes/java/lang/Character.java index f546ab53b0a..e3d6c38a7c6 100644 --- a/jdk/src/java.base/share/classes/java/lang/Character.java +++ b/jdk/src/java.base/share/classes/java/lang/Character.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -645,8 +645,14 @@ class Character implements java.io.Serializable, Comparable { * @since 1.2 */ public static final class UnicodeBlock extends Subset { - - private static Map map = new HashMap<>(256); + /** + * 510 - the expected number of enteties + * 0.75 - the default load factor of HashMap + */ + private static final int INITIAL_CAPACITY = + (int)(510 / 0.75f + 1.0f); + private static Map map = + new HashMap<>(INITIAL_CAPACITY); /** * Creates a UnicodeBlock with the given identifier name. diff --git a/jdk/test/java/lang/Character/UnicodeBlock/NonOptimalMapSize.java b/jdk/test/java/lang/Character/UnicodeBlock/NonOptimalMapSize.java new file mode 100644 index 00000000000..73688021596 --- /dev/null +++ b/jdk/test/java/lang/Character/UnicodeBlock/NonOptimalMapSize.java @@ -0,0 +1,72 @@ +/* + * Copyright (c) 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 8080535 + * @summary Expected size of Character.UnicodeBlock.map is not optimal + */ + +import java.lang.reflect.Field; +import java.util.HashMap; +import java.util.Map; + +public class NonOptimalMapSize { + public static void main(String[] args) throws Throwable { + Class ubCls = Character.UnicodeBlock.class; + Field mapField = ubCls.getDeclaredField("map"); + mapField.setAccessible(true); + Map map = (Map)mapField.get(null); + if (!map.getClass().equals(HashMap.class)) { + throw new RuntimeException( + "Character.UnicodeBlock.map is expected to be HashMap"); + } + int mapSize = map.size(); + + Field sizeField = ubCls.getDeclaredField("INITIAL_CAPACITY"); + sizeField.setAccessible(true); + int INITIAL_CAPACITY = sizeField.getInt(null); + + // Construct a HashMap with specified initial capacity + HashMap map1 = new HashMap<>(INITIAL_CAPACITY); + Class hmCls = HashMap.class; + Field tableField = hmCls.getDeclaredField("table"); + tableField.setAccessible(true); + // ... and fill it up + map1.put(new Object(), new Object()); + final Object initialTable = tableField.get(map1); + while (map1.size() < map.size() && + initialTable == tableField.get(map1)) { + map1.put(new Object(), new Object()); + } + + // Now check that internal storage didn't change + if (initialTable != tableField.get(map1)) { + throw new RuntimeException( + "Initial capacity " + INITIAL_CAPACITY + + " was only enough to hold " + (map1.size()-1) + + " entries, but needed " + map.size()); + } + } +} From eb68509b7dd3a41e220148053e8f8488518042c5 Mon Sep 17 00:00:00 2001 From: Artem Smotrakov Date: Mon, 18 May 2015 19:26:48 +0300 Subject: [PATCH 48/70] 8079140: IgnoreAllErrorHandler should use doPrivileged when it reads system properties Reviewed-by: mullan --- .../security/utils/IgnoreAllErrorHandler.java | 23 +++- .../crypto/dsig/ErrorHandlerPermissions.java | 121 ++++++++++++++++++ .../dsig/ErrorHandlerPermissions.policy | 5 + .../dsig/data/signature-external-rsa.xml | 3 + 4 files changed, 147 insertions(+), 5 deletions(-) create mode 100644 jdk/test/javax/xml/crypto/dsig/ErrorHandlerPermissions.java create mode 100644 jdk/test/javax/xml/crypto/dsig/ErrorHandlerPermissions.policy create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-external-rsa.xml diff --git a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java index d06a41ffd20..4d0ab5266b5 100644 --- a/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java +++ b/jdk/src/java.xml.crypto/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java @@ -35,19 +35,30 @@ import org.xml.sax.SAXParseException; public class IgnoreAllErrorHandler implements ErrorHandler { /** {@link org.apache.commons.logging} logging facility */ - private static java.util.logging.Logger log = + private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(IgnoreAllErrorHandler.class.getName()); /** Field throwExceptions */ - private static final boolean warnOnExceptions = - System.getProperty("com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); + private static final boolean warnOnExceptions = getProperty( + "com.sun.org.apache.xml.internal.security.test.warn.on.exceptions"); /** Field throwExceptions */ - private static final boolean throwExceptions = - System.getProperty("com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); + private static final boolean throwExceptions = getProperty( + "com.sun.org.apache.xml.internal.security.test.throw.exceptions"); + private static boolean getProperty(String name) { + return java.security.AccessController.doPrivileged( + new java.security.PrivilegedAction() { + + @Override + public Boolean run() { + return Boolean.getBoolean(name); + } + }); + } /** @inheritDoc */ + @Override public void warning(SAXParseException ex) throws SAXException { if (IgnoreAllErrorHandler.warnOnExceptions) { log.log(java.util.logging.Level.WARNING, "", ex); @@ -59,6 +70,7 @@ public class IgnoreAllErrorHandler implements ErrorHandler { /** @inheritDoc */ + @Override public void error(SAXParseException ex) throws SAXException { if (IgnoreAllErrorHandler.warnOnExceptions) { log.log(java.util.logging.Level.SEVERE, "", ex); @@ -70,6 +82,7 @@ public class IgnoreAllErrorHandler implements ErrorHandler { /** @inheritDoc */ + @Override public void fatalError(SAXParseException ex) throws SAXException { if (IgnoreAllErrorHandler.warnOnExceptions) { log.log(java.util.logging.Level.WARNING, "", ex); diff --git a/jdk/test/javax/xml/crypto/dsig/ErrorHandlerPermissions.java b/jdk/test/javax/xml/crypto/dsig/ErrorHandlerPermissions.java new file mode 100644 index 00000000000..1231d3cfe33 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/ErrorHandlerPermissions.java @@ -0,0 +1,121 @@ +/* + * Copyright (c) 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. + */ + +import java.io.ByteArrayInputStream; +import java.io.File; +import java.security.KeyFactory; +import java.security.PublicKey; +import java.security.spec.X509EncodedKeySpec; +import java.util.Base64; +import javax.xml.XMLConstants; +import javax.xml.crypto.Data; +import javax.xml.crypto.KeySelector; +import javax.xml.crypto.OctetStreamData; +import javax.xml.crypto.URIDereferencer; +import javax.xml.crypto.URIReference; +import javax.xml.crypto.URIReferenceException; +import javax.xml.crypto.XMLCryptoContext; +import javax.xml.crypto.dsig.XMLSignature; +import javax.xml.crypto.dsig.XMLSignatureFactory; +import javax.xml.crypto.dsig.dom.DOMValidateContext; +import javax.xml.parsers.DocumentBuilderFactory; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.w3c.dom.NodeList; + +/** + * @test + * @bug 8079140 + * @summary Check if IgnoreAllErrorHandler doesn't require additional permission + * @run main/othervm/java.security.policy=ErrorHandlerPermissions.policy + * ErrorHandlerPermissions + */ +public class ErrorHandlerPermissions { + + private final static String FS = System.getProperty("file.separator"); + private final static String DIR = System.getProperty("test.src", "."); + private final static String DATA_DIR = DIR + FS + "data"; + private final static String SIGNATURE = DATA_DIR + FS + + "signature-external-rsa.xml"; + + private static final String validationKey = + "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnx4TdvPSA5vcsPi0OJZi9Ox0Z" + + "2FRz2oeUCtuWoyEg0kUCeFd+jJZMstDJUiZNSOeuCO3FWSpdJgAwI4zlveHvuU/o" + + "qHSa1eYTObOCvxfVYGGflWsSvGXyiANtRWVUrYODBeyL+2pWxDYh+Fi5EKizPfTG" + + "wRjBVRSkRZKTnSjnQwIDAQAB"; + + private static final URIDereferencer dereferencer = + new DummyURIDereferencer(); + + public static void main(String[] args) throws Exception { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setValidating(false); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + Document doc = dbf.newDocumentBuilder().parse(new File(SIGNATURE)); + NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, + "Signature"); + if (nl.getLength() == 0) { + throw new RuntimeException("Couldn't find 'Signature' element"); + } + Element element = (Element) nl.item(0); + + byte[] keyBytes = Base64.getDecoder().decode(validationKey); + X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); + KeyFactory kf = KeyFactory.getInstance("RSA"); + PublicKey key = kf.generatePublic(spec); + KeySelector ks = KeySelector.singletonKeySelector(key); + + DOMValidateContext vc = new DOMValidateContext(ks, element); + + // disable secure validation mode + vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE); + + // set a dummy dereferencer to be able to get content by references + vc.setURIDereferencer(dereferencer); + + XMLSignatureFactory factory = XMLSignatureFactory.getInstance(); + XMLSignature signature = factory.unmarshalXMLSignature(vc); + + // run validation + signature.validate(vc); + } + + /** + * This URIDereferencer returns a static XML document. + */ + private static class DummyURIDereferencer implements URIDereferencer { + + @Override + public Data dereference(final URIReference ref, XMLCryptoContext ctx) + throws URIReferenceException { + // return static content + return new OctetStreamData(new ByteArrayInputStream( + "test".getBytes()), ref.getURI(), + ref.getType()); + } + } + +} diff --git a/jdk/test/javax/xml/crypto/dsig/ErrorHandlerPermissions.policy b/jdk/test/javax/xml/crypto/dsig/ErrorHandlerPermissions.policy new file mode 100644 index 00000000000..8db9c01c3c8 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/ErrorHandlerPermissions.policy @@ -0,0 +1,5 @@ +grant { + permission java.util.PropertyPermission "test.src", "read"; + permission java.util.PropertyPermission "file.separator", "read"; + permission java.io.FilePermission "${test.src}/-", "read"; +}; diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-external-rsa.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-external-rsa.xml new file mode 100644 index 00000000000..fb3a0f4f986 --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-external-rsa.xml @@ -0,0 +1,3 @@ +test1Bq8FsjajUBYPD7stQeJSc66GlM=f6trDCcPsLLkIV/V4DGFbRf8b9Jwal8xGBDshNzEXwPmym2ChN85rbKIg/cbunf04F89/SXLo2v9 +AYjLcUr3G/Vz5YUmqNhnBvJukXgsIG0ddWl3mFi9Tk+CLINlbgfsaFqU9pQwFjmDyAqIrvZYqW7p +rTHLetv218mbUVBBAkc= \ No newline at end of file From 13c92b58f07aa89426aa2f9915f2e27bf28bcf0c Mon Sep 17 00:00:00 2001 From: Jeremy Manson Date: Mon, 18 May 2015 13:34:56 -0700 Subject: [PATCH 49/70] 8080538: hprof does not work well with multiple agents on non-Solaris platforms Never take the address of Agent_OnLoad. Reviewed-by: sla, martin --- .../unix/native/libhprof/hprof_md.c | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/jdk/src/jdk.hprof.agent/unix/native/libhprof/hprof_md.c b/jdk/src/jdk.hprof.agent/unix/native/libhprof/hprof_md.c index 78a4f606735..9b3063562d5 100644 --- a/jdk/src/jdk.hprof.agent/unix/native/libhprof/hprof_md.c +++ b/jdk/src/jdk.hprof.agent/unix/native/libhprof/hprof_md.c @@ -290,19 +290,7 @@ md_get_prelude_path(char *path, int path_len, char *filename) Dl_info dlinfo; libdir[0] = 0; -#if defined(LINUX) || defined(_ALLBSD_SOURCE) || defined(AIX) - addr = (void*)&Agent_OnLoad; -#else - /* Just using &Agent_OnLoad will get the first external symbol with - * this name in the first .so, which may not be libhprof.so. - * On Solaris we can actually ask for the address of our Agent_OnLoad. - */ - addr = dlsym(RTLD_SELF, "Agent_OnLoad"); - /* Just in case the above didn't work (missing linker patch?). */ - if ( addr == NULL ) { - addr = (void*)&Agent_OnLoad; - } -#endif + addr = (void*)&md_get_prelude_path; /* Use dladdr() to get the full path to libhprof.so, which we use to find * the prelude file. From ae7da8e1198339d7f085b681de620771ead2902f Mon Sep 17 00:00:00 2001 From: Weijun Wang Date: Tue, 19 May 2015 09:09:09 +0800 Subject: [PATCH 50/70] 8077102: dns_lookup_realm should be false by default Reviewed-by: valeriep --- .../classes/sun/security/krb5/Config.java | 13 +++-- .../security/krb5/config/ConfPlusProp.java | 33 +++-------- jdk/test/sun/security/krb5/config/DNS.java | 12 +++- .../sun/security/krb5/config/DnsFallback.java | 58 ++++++++++++------- .../security/krb5/config/confplusprop.conf | 2 +- .../security/krb5/config/confplusprop2.conf | 2 +- 6 files changed, 67 insertions(+), 53 deletions(-) diff --git a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/Config.java b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/Config.java index 72d8423e7dd..f2f74ab5c67 100644 --- a/jdk/src/java.security.jgss/share/classes/sun/security/krb5/Config.java +++ b/jdk/src/java.security.jgss/share/classes/sun/security/krb5/Config.java @@ -1085,27 +1085,30 @@ public class Config { * Check if need to use DNS to locate Kerberos services for name. If not * defined, check dns_fallback, whose default value is true. */ - private boolean useDNS(String name) { + private boolean useDNS(String name, boolean defaultValue) { Boolean value = getBooleanObject("libdefaults", name); if (value != null) { return value.booleanValue(); - } else { - return getBooleanObject("libdefaults", "dns_fallback") != Boolean.FALSE; } + value = getBooleanObject("libdefaults", "dns_fallback"); + if (value != null) { + return value.booleanValue(); + } + return defaultValue; } /** * Check if need to use DNS to locate the KDC */ private boolean useDNS_KDC() { - return useDNS("dns_lookup_kdc"); + return useDNS("dns_lookup_kdc", true); } /* * Check if need to use DNS to locate the Realm */ private boolean useDNS_Realm() { - return useDNS("dns_lookup_realm"); + return useDNS("dns_lookup_realm", false); } /** diff --git a/jdk/test/sun/security/krb5/config/ConfPlusProp.java b/jdk/test/sun/security/krb5/config/ConfPlusProp.java index 0a944989cd7..2376d02d46a 100644 --- a/jdk/test/sun/security/krb5/config/ConfPlusProp.java +++ b/jdk/test/sun/security/krb5/config/ConfPlusProp.java @@ -35,6 +35,12 @@ import sun.security.krb5.Config; public class ConfPlusProp { Config config; public static void main(String[] args) throws Exception { + if (System.getenv("USERDNSDOMAIN") != null || + System.getenv("LOGONSERVER") != null) { + System.out.println( + "Looks like a Windows machine in a domain. Skip test."); + return; + } new ConfPlusProp().run(); } @@ -90,23 +96,8 @@ public class ConfPlusProp { check("R2", "old"); check("R3", null); - int version = System.getProperty("java.version").charAt(2) - '0'; - System.out.println("JDK version is " + version); - - // Zero-config is supported since 1.7 - if (version >= 7) { - // Point to a non-existing file - System.setProperty("java.security.krb5.conf", "i-am-not-a file"); - refresh(); - - // Default realm might come from DNS - //checkDefaultRealm(null); - check("R1", null); - check("R2", null); - check("R3", null); - if (config.get("libdefaults", "forwardable") != null) { - throw new Exception("Extra config error"); - } + if (config.get("libdefaults", "forwardable") != null) { + throw new Exception("Extra config error"); } // Add prop @@ -136,14 +127,6 @@ public class ConfPlusProp { check("R2", "k2"); check("R3", "k2"); - // Point to a non-existing file - System.setProperty("java.security.krb5.conf", "i-am-not-a file"); - refresh(); - - checkDefaultRealm("R2"); - check("R1", "k2"); - check("R2", "k2"); - check("R3", "k2"); if (config.get("libdefaults", "forwardable") != null) { throw new Exception("Extra config error"); } diff --git a/jdk/test/sun/security/krb5/config/DNS.java b/jdk/test/sun/security/krb5/config/DNS.java index 8c574be92d5..7171441dcb4 100644 --- a/jdk/test/sun/security/krb5/config/DNS.java +++ b/jdk/test/sun/security/krb5/config/DNS.java @@ -23,12 +23,22 @@ // See dns.sh. import sun.security.krb5.Config; +import sun.security.krb5.KrbException; public class DNS { public static void main(String[] args) throws Exception { System.setProperty("java.security.krb5.conf", - System.getProperty("test.src", ".") +"/nothing.conf"); + System.getProperty("test.src", ".") +"/no-such-file.conf"); Config config = Config.getInstance(); + try { + String r = config.getDefaultRealm(); + throw new Exception("What? There is a default realm " + r + "?"); + } catch (KrbException ke) { + ke.printStackTrace(); + if (ke.getCause() != null) { + throw new Exception("There should be no cause. Won't try DNS"); + } + } String kdcs = config.getKDCList("X"); if (!kdcs.equals("a.com.:88 b.com.:99") && !kdcs.equals("a.com. b.com.:99")) { diff --git a/jdk/test/sun/security/krb5/config/DnsFallback.java b/jdk/test/sun/security/krb5/config/DnsFallback.java index b1e64197794..cf5e6bac942 100644 --- a/jdk/test/sun/security/krb5/config/DnsFallback.java +++ b/jdk/test/sun/security/krb5/config/DnsFallback.java @@ -22,8 +22,7 @@ */ /* * @test - * @bug 6673164 - * @bug 6552334 + * @bug 6673164 6552334 8077102 * @run main/othervm DnsFallback * @summary fix dns_fallback parse error, and use dns by default */ @@ -35,47 +34,66 @@ import sun.security.krb5.Config; public class DnsFallback { static Method useDNS_Realm; + static Method useDNS_KDC; public static void main(String[] args) throws Exception { useDNS_Realm = Config.class.getDeclaredMethod("useDNS_Realm"); useDNS_Realm.setAccessible(true); + useDNS_KDC = Config.class.getDeclaredMethod("useDNS_KDC"); + useDNS_KDC.setAccessible(true); // for 6673164 - check("true", "true", true); - check("false", "true", false); - check("true", "false", true); - check("false", "false", false); - check("true", null, true); - check("false", null, false); - check(null, "true", true); - check(null, "false", false); + check("true", "true", true, true); + check("false", "true", false, false); + check("true", "false", true, true); + check("false", "false", false, false); + check("true", null, true, true); + check("false", null, false, false); + check(null, "true", true, true); + check(null, "false", false, false); - // for 6552334 - check(null, null, true); + // for 6552334, no longer true + //check(null, null, true, true); + + // 8077102 + check(null, null, false, true); } - static void check(String realm, String fallback, boolean output) + /** + * Sets and checks. + * + * @param u dns_lookup_XXX value set, none if null + * @param f dns_fallback value set, none if null + * @param r expected useDNS_Realm + * @param k expected useDNS_KDC + */ + static void check(String u, String f, boolean r, boolean k) throws Exception { try (PrintStream ps = new PrintStream(new FileOutputStream("dnsfallback.conf"))) { ps.println("[libdefaults]\n"); - if (realm != null) { - ps.println("dns_lookup_realm=" + realm); + if (u != null) { + ps.println("dns_lookup_realm=" + u); + ps.println("dns_lookup_kdc=" + u); } - if (fallback != null) { - ps.println("dns_fallback=" + fallback); + if (f != null) { + ps.println("dns_fallback=" + f); } } System.setProperty("java.security.krb5.conf", "dnsfallback.conf"); Config.refresh(); - System.out.println("Testing " + realm + ", " + fallback + ", " + output); + System.out.println("Testing " + u + ", " + f + ", " + r + ", " + k); - if (!useDNS_Realm.invoke(Config.getInstance()).equals(output)) { - throw new Exception("Fail"); + if (!useDNS_Realm.invoke(Config.getInstance()).equals(r)) { + throw new Exception("useDNS_Realm Fail"); + } + + if (!useDNS_KDC.invoke(Config.getInstance()).equals(k)) { + throw new Exception("useDNS_KDC Fail"); } } } diff --git a/jdk/test/sun/security/krb5/config/confplusprop.conf b/jdk/test/sun/security/krb5/config/confplusprop.conf index 5e499483348..39f747293ba 100644 --- a/jdk/test/sun/security/krb5/config/confplusprop.conf +++ b/jdk/test/sun/security/krb5/config/confplusprop.conf @@ -1,7 +1,7 @@ [libdefaults] default_realm = R1 forwardable = well -dns_lookup_realm = false +dns_lookup_kdc = false [realms] R1 = { diff --git a/jdk/test/sun/security/krb5/config/confplusprop2.conf b/jdk/test/sun/security/krb5/config/confplusprop2.conf index c55464bd846..b308e7e41cb 100644 --- a/jdk/test/sun/security/krb5/config/confplusprop2.conf +++ b/jdk/test/sun/security/krb5/config/confplusprop2.conf @@ -1,5 +1,5 @@ [libdefaults] -dns_lookup_realm = false +dns_lookup_kdc = false [realms] R1 = { From d4f45f51c9e376648f27ab9aaf28b5f020b5cb36 Mon Sep 17 00:00:00 2001 From: Magnus Ihse Bursie Date: Tue, 19 May 2015 10:05:02 +0200 Subject: [PATCH 51/70] 8080630: Stop doing sed manipulation of manifest files in SetupJavaCompilation Reviewed-by: erikj --- jdk/make/CompileDemos.gmk | 16 +++++++++++++--- 1 file changed, 13 insertions(+), 3 deletions(-) diff --git a/jdk/make/CompileDemos.gmk b/jdk/make/CompileDemos.gmk index 5e03eb1aa46..7719a8663f5 100644 --- a/jdk/make/CompileDemos.gmk +++ b/jdk/make/CompileDemos.gmk @@ -30,6 +30,7 @@ include MakeBase.gmk include JavaCompilation.gmk include NativeCompilation.gmk include SetupJavaCompilers.gmk +include TextFileProcessing.gmk # Prepare the find cache. $(eval $(call FillCacheFind, $(JDK_TOPDIR)/src)) @@ -49,6 +50,15 @@ GLOBAL_VERSION_INFO_RESOURCE := $(JDK_TOPDIR)/src/java.base/windows/native/commo ################################################################################################## +# This rule will be depended on due to the MANIFEST line +$(eval $(call SetupTextFileProcessing, BUILD_JAVA_MANIFEST, \ + SOURCE_FILES := $(JDK_TOPDIR)/make/data/mainmanifest/manifest.mf, \ + OUTPUT_FILE := $(SUPPORT_OUTPUTDIR)/demo/java-main-manifest.mf, \ + REPLACEMENTS := \ + @@RELEASE@@ => $(RELEASE) ; \ + @@COMPANY_NAME@@ => $(COMPANY_NAME) , \ +)) + define SetupAppletDemo $$(eval $$(call SetupJavaCompilation,BUILD_DEMO_APPLET_$1, \ SETUP := GENERATE_USINGJDKBYTECODE, \ @@ -122,7 +132,7 @@ define SetupDemo COPY := $(PATTERNS_TO_COPY) $(10), \ JAR := $(SUPPORT_OUTPUTDIR)/demo/image/$2/$1/$$($1_JARFILE), \ JARMAIN := $4, \ - MANIFEST := $(JDK_TOPDIR)/make/data/mainmanifest/manifest.mf, \ + MANIFEST := $(SUPPORT_OUTPUTDIR)/demo/java-main-manifest.mf, \ EXTRA_MANIFEST_ATTR := $(11), \ SRCZIP := $(SUPPORT_OUTPUTDIR)/demo/image/$2/$1/src.zip, \ EXCLUDE_FILES := $9, \ @@ -290,7 +300,7 @@ define SetupJVMTIDemo COPY := $(PATTERNS_TO_COPY), \ JAR := $(SUPPORT_OUTPUTDIR)/demo/image/jvmti/$1/$1.jar, \ EXTRA_MANIFEST_ATTR := Main-Class: \n, \ - MANIFEST := $(JDK_TOPDIR)/make/data/mainmanifest/manifest.mf)) + MANIFEST := $(SUPPORT_OUTPUTDIR)/demo/java-main-manifest.mf)) BUILD_DEMOS += $(SUPPORT_OUTPUTDIR)/demo/image/jvmti/$1/$1.jar endif @@ -382,7 +392,7 @@ ifeq ($(OPENJDK_TARGET_OS), solaris) BIN := $(SUPPORT_OUTPUTDIR)/demo/classes/jni/Poller, \ HEADERS := $(SUPPORT_OUTPUTDIR)/demo/classes/jni/Poller, \ JAR := $(SUPPORT_OUTPUTDIR)/demo/image/jni/Poller/Poller.jar, \ - MANIFEST := $(JDK_TOPDIR)/make/data/mainmanifest/manifest.mf, \ + MANIFEST := $(SUPPORT_OUTPUTDIR)/demo/java-main-manifest.mf, \ SRCZIP := $(SUPPORT_OUTPUTDIR)/demo/image/jni/Poller/src.zip, \ COPY := README.txt Poller.c, \ JARMAIN := Client)) From 7695bc389d1b377b29e1eb8c2cf102bfd6454cc7 Mon Sep 17 00:00:00 2001 From: Denis Kononenko Date: Tue, 19 May 2015 14:03:20 +0300 Subject: [PATCH 52/70] 8077866: [TESTBUG] Some of java.lang tests cannot be run on compact profiles 1, 2 Reviewed-by: dholmes, alanb --- jdk/test/TEST.groups | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/jdk/test/TEST.groups b/jdk/test/TEST.groups index 73ac408f90e..ef17c46f0d3 100644 --- a/jdk/test/TEST.groups +++ b/jdk/test/TEST.groups @@ -599,6 +599,10 @@ needs_compact3 = \ sun/security/jgss \ sun/security/krb5 \ java/lang/annotation/AnnotationType/AnnotationTypeDeadlockTest.java \ + java/lang/invoke/lambda/LambdaStackTrace.java \ + java/lang/invoke/LFCaching/LFGarbageCollectedTest.java \ + java/lang/invoke/LFCaching/LFMultiThreadCachingTest.java \ + java/lang/invoke/LFCaching/LFSingleThreadCachingTest.java \ java/lang/System/MacEncoding/TestFileEncoding.java \ java/nio/channels/AsynchronousSocketChannel/Leaky.java \ java/security/PermissionCollection/Concurrent.java \ From 30cda926e9c7053ceba12a73fb9e24fb1bd4f1cb Mon Sep 17 00:00:00 2001 From: Alexander Stepanov Date: Tue, 19 May 2015 16:04:14 +0400 Subject: [PATCH 53/70] 8080422: some docs cleanup for core libs Some docs cleanup Reviewed-by: rriggs, lancea --- .../share/classes/java/text/ChoiceFormat.java | 2 +- .../classes/java/util/ArrayPrefixHelpers.java | 2 +- .../share/classes/java/util/Calendar.java | 6 +- .../share/classes/java/util/Collection.java | 2 +- .../share/classes/java/util/Locale.java | 6 +- .../share/classes/java/util/TreeMap.java | 4 +- .../util/concurrent/ConcurrentHashMap.java | 2 +- .../concurrent/ConcurrentSkipListMap.java | 4 +- .../jdk/internal/util/xml/impl/Parser.java | 58 +++++++------ .../jdk/internal/util/xml/impl/ParserSAX.java | 4 +- .../share/classes/sun/misc/Cache.java | 4 +- .../classes/sun/misc/CharacterDecoder.java | 2 +- .../classes/sun/misc/CharacterEncoder.java | 4 +- .../share/classes/sun/misc/ConditionLock.java | 2 +- .../classes/sun/misc/ExtensionDependency.java | 51 ++++------- .../share/classes/sun/misc/ExtensionInfo.java | 35 +++----- .../share/classes/sun/misc/FDBigInteger.java | 34 ++++---- .../classes/sun/misc/FloatingDecimal.java | 2 +- .../share/classes/sun/misc/IOUtils.java | 2 +- .../share/classes/sun/misc/JarFilter.java | 2 - .../classes/sun/misc/JavaLangAccess.java | 14 +-- .../share/classes/sun/misc/Perf.java | 9 +- .../share/classes/sun/misc/PerfCounter.java | 2 +- .../classes/sun/misc/PerformanceLogger.java | 4 +- .../share/classes/sun/misc/Resource.java | 3 +- .../share/classes/sun/misc/Signal.java | 6 +- .../share/classes/sun/misc/Unsafe.java | 13 ++- .../java.base/share/classes/sun/misc/VM.java | 2 +- .../classes/sun/misc/resources/Messages.java | 8 +- .../sun/misc/resources/Messages_de.java | 8 +- .../sun/misc/resources/Messages_es.java | 8 +- .../sun/misc/resources/Messages_fr.java | 8 +- .../sun/misc/resources/Messages_it.java | 8 +- .../sun/misc/resources/Messages_ja.java | 8 +- .../sun/misc/resources/Messages_ko.java | 8 +- .../sun/misc/resources/Messages_pt_BR.java | 8 +- .../sun/misc/resources/Messages_sv.java | 8 +- .../sun/misc/resources/Messages_zh_CN.java | 8 +- .../sun/misc/resources/Messages_zh_TW.java | 8 +- .../share/classes/sun/nio/cs/Surrogate.java | 28 +++--- .../classes/sun/text/CompactByteArray.java | 2 +- .../classes/sun/text/ComposedCharIter.java | 8 +- .../share/classes/sun/text/Normalizer.java | 2 +- .../share/classes/sun/text/bidi/BidiBase.java | 28 +++--- .../share/classes/sun/text/bidi/BidiRun.java | 2 +- .../sun/text/normalizer/ICUBinary.java | 6 +- .../classes/sun/text/normalizer/IntTrie.java | 2 +- .../sun/text/normalizer/NormalizerBase.java | 87 +++++++++---------- .../text/normalizer/RangeValueIterator.java | 13 +-- .../sun/text/normalizer/Replaceable.java | 11 ++- .../text/normalizer/ReplaceableString.java | 6 +- .../ReplaceableUCharacterIterator.java | 6 +- .../normalizer/RuleCharacterIterator.java | 15 ++-- .../sun/text/normalizer/SymbolTable.java | 4 +- .../classes/sun/text/normalizer/Trie.java | 6 +- .../sun/text/normalizer/TrieIterator.java | 35 ++++---- .../sun/text/normalizer/UCharacter.java | 4 +- .../text/normalizer/UCharacterIterator.java | 8 +- .../classes/sun/text/normalizer/UTF16.java | 18 ++-- .../sun/text/normalizer/UnicodeMatcher.java | 3 +- .../sun/text/normalizer/UnicodeSet.java | 26 +++--- .../text/normalizer/UnicodeSetIterator.java | 46 +++++----- .../classes/sun/text/normalizer/Utility.java | 8 +- .../sun/text/normalizer/VersionInfo.java | 12 +-- .../DefaultMXBeanMappingFactory.java | 42 ++++----- .../internal/ServerCommunicatorAdmin.java | 8 +- .../com/sun/jmx/remote/util/EnvHelp.java | 46 +++++----- .../sun/management/HotspotRuntimeMBean.java | 2 +- .../sun/management/HotspotThreadMBean.java | 5 +- .../sun/management/MappedMXBeanType.java | 16 ++-- .../share/classes/sun/management/Sensor.java | 18 ++-- .../sun/management/counter/Counter.java | 2 +- .../perf/InstrumentationException.java | 4 +- .../sun/management/jdp/JdpController.java | 15 ++-- .../com/sun/jndi/ldap/BasicControl.java | 2 +- .../classes/com/sun/jndi/ldap/BerDecoder.java | 2 +- .../classes/com/sun/jndi/ldap/EventQueue.java | 16 ++-- .../com/sun/jndi/ldap/EventSupport.java | 14 +-- .../classes/com/sun/jndi/ldap/LdapName.java | 2 +- .../sun/jndi/ldap/LdapReferralException.java | 16 ++-- .../jndi/ldap/UnsolicitedResponseImpl.java | 4 +- .../jndi/ldap/ext/StartTlsResponseImpl.java | 26 +++--- .../com/sun/jndi/ldap/sasl/LdapSasl.java | 4 +- .../sun/jndi/toolkit/ctx/Continuation.java | 6 +- .../toolkit/ctx/PartialCompositeContext.java | 4 +- .../sun/jndi/toolkit/dir/HierMemDirCtx.java | 4 +- .../sun/jndi/toolkit/dir/SearchFilter.java | 8 +- .../jndi/toolkit/url/GenericURLContext.java | 2 + .../classes/com/sun/jndi/toolkit/url/Uri.java | 10 +-- .../sun/rmi/rmid/ExecOptionPermission.java | 9 +- .../com/sun/rmi/rmid/ExecPermission.java | 13 ++- .../classes/sun/rmi/log/LogInputStream.java | 2 +- .../classes/sun/rmi/log/LogOutputStream.java | 2 +- .../classes/sun/rmi/log/ReliableLog.java | 6 +- .../sun/rmi/registry/RegistryImpl.java | 4 +- .../share/classes/sun/rmi/runtime/Log.java | 2 +- .../sun/rmi/server/ActivationGroupImpl.java | 4 +- .../sun/rmi/server/ActivationGroupInit.java | 2 +- .../classes/sun/rmi/transport/Channel.java | 2 +- .../classes/sun/rmi/transport/LiveRef.java | 2 +- .../sun/rmi/transport/proxy/CGIHandler.java | 2 +- .../com/sun/rowset/FilteredRowSetImpl.java | 2 +- .../com/sun/rowset/JoinRowSetImpl.java | 6 +- .../providers/RIOptimisticProvider.java | 2 +- .../classes/sun/rmi/rmic/RMIGenerator.java | 2 +- .../classes/sun/rmi/rmic/RemoteClass.java | 2 +- 106 files changed, 539 insertions(+), 558 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/text/ChoiceFormat.java b/jdk/src/java.base/share/classes/java/text/ChoiceFormat.java index 601b019e886..8355dee87d4 100644 --- a/jdk/src/java.base/share/classes/java/text/ChoiceFormat.java +++ b/jdk/src/java.base/share/classes/java/text/ChoiceFormat.java @@ -490,7 +490,7 @@ public class ChoiceFormat extends NumberFormat { } /** - * Equality comparision between two + * Equality comparison between two */ public boolean equals(Object obj) { if (obj == null) return false; diff --git a/jdk/src/java.base/share/classes/java/util/ArrayPrefixHelpers.java b/jdk/src/java.base/share/classes/java/util/ArrayPrefixHelpers.java index 089b90039cc..abcdb2b35aa 100644 --- a/jdk/src/java.base/share/classes/java/util/ArrayPrefixHelpers.java +++ b/jdk/src/java.base/share/classes/java/util/ArrayPrefixHelpers.java @@ -85,7 +85,7 @@ class ArrayPrefixHelpers { * * As usual for this sort of utility, there are 4 versions, that * are simple copy/paste/adapt variants of each other. (The - * double and int versions differ from long version soley by + * double and int versions differ from long version solely by * replacing "long" (with case-matching)). */ diff --git a/jdk/src/java.base/share/classes/java/util/Calendar.java b/jdk/src/java.base/share/classes/java/util/Calendar.java index 80849001e74..6d696aaee87 100644 --- a/jdk/src/java.base/share/classes/java/util/Calendar.java +++ b/jdk/src/java.base/share/classes/java/util/Calendar.java @@ -1172,7 +1172,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparable - * setFeilds(Calendar.YEAR, 2013, + * setFields(Calendar.YEAR, 2013, * Calendar.MONTH, Calendar.DECEMBER, * Calendar.DAY_OF_MONTH, 23); * is equivalent to the sequence of the following @@ -1298,7 +1298,7 @@ public abstract class Calendar implements Serializable, Cloneable, ComparableTimeZone} will be used in the {@link #build() build} * method. @@ -3316,7 +3316,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparablefield is negative, - * equal to or greater then FIELD_COUNT. + * equal to or greater than {@code FIELD_COUNT}. */ static String getFieldName(int field) { return FIELD_NAME[field]; diff --git a/jdk/src/java.base/share/classes/java/util/Collection.java b/jdk/src/java.base/share/classes/java/util/Collection.java index 4545faa6143..3a01908d73e 100644 --- a/jdk/src/java.base/share/classes/java/util/Collection.java +++ b/jdk/src/java.base/share/classes/java/util/Collection.java @@ -537,7 +537,7 @@ public interface Collection extends Iterable { * @implSpec * The default implementation creates a * late-binding spliterator - * from the collections's {@code Iterator}. The spliterator inherits the + * from the collection's {@code Iterator}. The spliterator inherits the * fail-fast properties of the collection's iterator. *

* The created {@code Spliterator} reports {@link Spliterator#SIZED}. diff --git a/jdk/src/java.base/share/classes/java/util/Locale.java b/jdk/src/java.base/share/classes/java/util/Locale.java index ffea237b34a..e3b12c5769c 100644 --- a/jdk/src/java.base/share/classes/java/util/Locale.java +++ b/jdk/src/java.base/share/classes/java/util/Locale.java @@ -719,7 +719,7 @@ public final class Locale implements Cloneable, Serializable { * created and cached. * * @param language lowercase 2 to 8 language code. - * @param country uppercase two-letter ISO-3166 code and numric-3 UN M.49 area code. + * @param country uppercase two-letter ISO-3166 code and numeric-3 UN M.49 area code. * @param variant vendor and browser specific code. See class description. * @return the Locale instance requested * @exception NullPointerException if any argument is null. @@ -1236,7 +1236,7 @@ public final class Locale implements Cloneable, Serializable { /** * Package private method returning the Locale's LocaleExtensions, * used by ResourceBundle. - * @return locale exnteions of this Locale, + * @return locale extensions of this Locale, * or {@code null} if no extensions are defined */ LocaleExtensions getLocaleExtensions() { @@ -2609,7 +2609,7 @@ public final class Locale implements Cloneable, Serializable { * href="./Locale.html#def_locale_extension">well-formed or an exception * is thrown. * - *

Attribute comparision for removal is case-insensitive. + *

Attribute comparison for removal is case-insensitive. * * @param attribute the attribute * @return This builder. diff --git a/jdk/src/java.base/share/classes/java/util/TreeMap.java b/jdk/src/java.base/share/classes/java/util/TreeMap.java index c04053656cf..a5ed0f5e91c 100644 --- a/jdk/src/java.base/share/classes/java/util/TreeMap.java +++ b/jdk/src/java.base/share/classes/java/util/TreeMap.java @@ -859,7 +859,7 @@ public class TreeMap * Returns a {@link Set} view of the mappings contained in this map. * *

The set's iterator returns the entries in ascending key order. The - * sets's spliterator is + * set's spliterator is * late-binding, * fail-fast, and additionally reports {@link Spliterator#SORTED} and * {@link Spliterator#ORDERED} with an encounter order that is ascending key @@ -2643,7 +2643,7 @@ public class TreeMap * child, also serving as origin for the split-off spliterator. * Left-hands are symmetric. Descending versions place the origin * at the end and invert ascending split rules. This base class - * is non-commital about directionality, or whether the top-level + * is non-committal about directionality, or whether the top-level * spliterator covers the whole tree. This means that the actual * split mechanics are located in subclasses. Some of the subclass * trySplit methods are identical (except for return types), but diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java b/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java index b50bc5930c3..2ffaef68010 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentHashMap.java @@ -481,7 +481,7 @@ public class ConcurrentHashMap extends AbstractMap * * Maintaining API and serialization compatibility with previous * versions of this class introduces several oddities. Mainly: We - * leave untouched but unused constructor arguments refering to + * leave untouched but unused constructor arguments referring to * concurrencyLevel. We accept a loadFactor constructor argument, * but apply it only to initial table capacity (which is the only * time that we can guarantee to honor it.) We also declare an diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListMap.java b/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListMap.java index 7c2effb95b7..4daee40a362 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListMap.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/ConcurrentSkipListMap.java @@ -2710,7 +2710,7 @@ public class ConcurrentSkipListMap extends AbstractMap } /** - * Returns lowest absolute key (ignoring directonality). + * Returns lowest absolute key (ignoring directionality). */ K lowestKey() { Comparator cmp = m.comparator; @@ -2722,7 +2722,7 @@ public class ConcurrentSkipListMap extends AbstractMap } /** - * Returns highest absolute key (ignoring directonality). + * Returns highest absolute key (ignoring directionality). */ K highestKey() { Comparator cmp = m.comparator; diff --git a/jdk/src/java.base/share/classes/jdk/internal/util/xml/impl/Parser.java b/jdk/src/java.base/share/classes/jdk/internal/util/xml/impl/Parser.java index 6db4d4fdb6d..57115f2139d 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/util/xml/impl/Parser.java +++ b/jdk/src/java.base/share/classes/jdk/internal/util/xml/impl/Parser.java @@ -145,12 +145,12 @@ public abstract class Parser { /** * ASCII character type array. * - * This array maps an ASCII (7 bit) character to the character type.
- * Possible character type values are:
- ' ' for any kind of white - * space character;
- 'a' for any lower case alphabetical character - * value;
- 'A' for any upper case alphabetical character value;
- * - 'd' for any decimal digit character value;
- 'z' for any - * character less then ' ' except '\t', '\n', '\r';
An ASCII (7 bit) + * This array maps an ASCII (7 bit) character to the character type.
+ * Possible character type values are:
- ' ' for any kind of white + * space character;
- 'a' for any lower case alphabetical character + * value;
- 'A' for any upper case alphabetical character value;
+ * - 'd' for any decimal digit character value;
- 'z' for any + * character less than ' ' except '\t', '\n', '\r';
An ASCII (7 bit) * character which does not fall in any category listed above is mapped to * it self. */ @@ -158,11 +158,11 @@ public abstract class Parser { /** * NMTOKEN character type array. * - * This array maps an ASCII (7 bit) character to the character type.
- * Possible character type values are:
- 0 for underscore ('_') or any - * lower and upper case alphabetical character value;
- 1 for colon - * (':') character;
- 2 for dash ('-') and dot ('.') or any decimal - * digit character value;
- 3 for any kind of white space character
+ * Possible character type values are:
- 0 for underscore ('_') or any + * lower and upper case alphabetical character value;
- 1 for colon + * (':') character;
- 2 for dash ('-') and dot ('.') or any decimal + * digit character value;
- 3 for any kind of white space character
An ASCII (7 bit) character which does not fall in any category listed * above is mapped to 0xff. */ @@ -1841,10 +1841,12 @@ public abstract class Parser { /** * Reads an attribute value. * - * The grammar which this method can read is:
- * eqstr := S "=" qstr
- * qstr := S ("'" string "'") | - * ('"' string '"')
This method resolves entities + * The grammar this method can read is: + *

{@code
+     * eqstr := S "=" qstr
+     * qstr  := S ("'" string "'") | ('"' string '"')
+     * }
+ * This method resolves entities * inside a string unless the parser parses DTD. * * @param flag The '=' character forces the method to accept the '=' @@ -2633,7 +2635,7 @@ public abstract class Parser { * Reports characters and empties the parser's buffer. This method is called * only if parser is going to return control to the main loop. This means * that this method may use parser buffer to report white space without - * copeing characters to temporary buffer. + * copying characters to temporary buffer. */ protected abstract void bflash() throws Exception; @@ -2642,7 +2644,7 @@ public abstract class Parser { * Reports white space characters and empties the parser's buffer. This * method is called only if parser is going to return control to the main * loop. This means that this method may use parser buffer to report white - * space without copeing characters to temporary buffer. + * space without copying characters to temporary buffer. */ protected abstract void bflash_ws() throws Exception; @@ -3290,16 +3292,20 @@ public abstract class Parser { } /** - * Maps a character to it's type. + * Maps a character to its type. * - * Possible character type values are:
- ' ' for any kind of white - * space character;
- 'a' for any lower case alphabetical character - * value;
- 'A' for any upper case alphabetical character value;
- * - 'd' for any decimal digit character value;
- 'z' for any - * character less then ' ' except '\t', '\n', '\r';
- 'X' for any not - * ASCII character;
- 'Z' for EOS character.
An ASCII (7 bit) - * character which does not fall in any category listed above is mapped to - * it self. + * Possible character type values are: + *
    + *
  • ' ' - for any kind of whitespace character;
  • + *
  • 'a' - for any lower case alphabetical character value;
  • + *
  • 'A' - for any upper case alphabetical character value;
  • + *
  • 'd' - for any decimal digit character value;
  • + *
  • 'z' - for any character less than ' ' except '\t', '\n', '\r';
  • + *
  • 'X' - for any not ASCII character;
  • + *
  • 'Z' - for EOS character.
  • + *
+ * An ASCII (7 bit) character which does not fall in any category + * listed above is mapped to itself. * * @param ch The character to map. * @return The type of character. diff --git a/jdk/src/java.base/share/classes/jdk/internal/util/xml/impl/ParserSAX.java b/jdk/src/java.base/share/classes/jdk/internal/util/xml/impl/ParserSAX.java index da921dc4936..733f2665972 100644 --- a/jdk/src/java.base/share/classes/jdk/internal/util/xml/impl/ParserSAX.java +++ b/jdk/src/java.base/share/classes/jdk/internal/util/xml/impl/ParserSAX.java @@ -649,7 +649,7 @@ final class ParserSAX * Reports characters and empties the parser's buffer. This method is called * only if parser is going to return control to the main loop. This means * that this method may use parser buffer to report white space without - * copeing characters to temporary buffer. + * copying characters to temporary buffer. */ protected void bflash() throws SAXException { if (mBuffIdx >= 0) { @@ -663,7 +663,7 @@ final class ParserSAX * Reports white space characters and empties the parser's buffer. This * method is called only if parser is going to return control to the main * loop. This means that this method may use parser buffer to report white - * space without copeing characters to temporary buffer. + * space without copying characters to temporary buffer. */ protected void bflash_ws() throws SAXException { if (mBuffIdx >= 0) { diff --git a/jdk/src/java.base/share/classes/sun/misc/Cache.java b/jdk/src/java.base/share/classes/sun/misc/Cache.java index 467481183a6..fb0a9ea8724 100644 --- a/jdk/src/java.base/share/classes/sun/misc/Cache.java +++ b/jdk/src/java.base/share/classes/sun/misc/Cache.java @@ -196,8 +196,8 @@ public /** * Gets the object associated with the specified key in the Cache. * @param key the key in the hash table - * @returns the element for the key or null if the key - * is not defined in the hash table. + * @return the element for the key or null if the key + * is not defined in the hash table. * @see Cache#put */ public synchronized Object get(Object key) { diff --git a/jdk/src/java.base/share/classes/sun/misc/CharacterDecoder.java b/jdk/src/java.base/share/classes/sun/misc/CharacterDecoder.java index c076f46df28..07cbd413594 100644 --- a/jdk/src/java.base/share/classes/sun/misc/CharacterDecoder.java +++ b/jdk/src/java.base/share/classes/sun/misc/CharacterDecoder.java @@ -120,7 +120,7 @@ public abstract class CharacterDecoder { /** * This method does an actual decode. It takes the decoded bytes and * writes them to the OutputStream. The integer l tells the - * method how many bytes are required. This is always <= bytesPerAtom(). + * method how many bytes are required. This is always {@literal <=} bytesPerAtom(). */ protected void decodeAtom(PushbackInputStream aStream, OutputStream bStream, int l) throws IOException { throw new CEStreamExhausted(); diff --git a/jdk/src/java.base/share/classes/sun/misc/CharacterEncoder.java b/jdk/src/java.base/share/classes/sun/misc/CharacterEncoder.java index d152f954cf9..4042cb2c6e7 100644 --- a/jdk/src/java.base/share/classes/sun/misc/CharacterEncoder.java +++ b/jdk/src/java.base/share/classes/sun/misc/CharacterEncoder.java @@ -68,7 +68,7 @@ import java.nio.ByteBuffer; * referenced in the See Also list below. * * @author Chuck McManis - * @see CharacterDecoder; + * @see CharacterDecoder * @see UCEncoder * @see UUEncoder * @see BASE64Encoder @@ -107,7 +107,7 @@ public abstract class CharacterEncoder { /** * Encode the suffix that ends every output line. By default - * this method just prints a into the output stream. + * this method just prints a newline into the output stream. */ protected void encodeLineSuffix(OutputStream aStream) throws IOException { pStream.println(); diff --git a/jdk/src/java.base/share/classes/sun/misc/ConditionLock.java b/jdk/src/java.base/share/classes/sun/misc/ConditionLock.java index e1af5252117..60a6fa5ee04 100644 --- a/jdk/src/java.base/share/classes/sun/misc/ConditionLock.java +++ b/jdk/src/java.base/share/classes/sun/misc/ConditionLock.java @@ -34,7 +34,7 @@ package sun.misc; * with the lock() and unlock() methods. However if there is a thread * waiting for the state variable to become a particular value and you * simply call Unlock(), that thread will not be able to acquire the - * lock until the state variable equals its desired value.

+ * lock until the state variable equals its desired value. * * @author Peter King */ diff --git a/jdk/src/java.base/share/classes/sun/misc/ExtensionDependency.java b/jdk/src/java.base/share/classes/sun/misc/ExtensionDependency.java index c013169fa2f..97c9480efd8 100644 --- a/jdk/src/java.base/share/classes/sun/misc/ExtensionDependency.java +++ b/jdk/src/java.base/share/classes/sun/misc/ExtensionDependency.java @@ -45,26 +45,26 @@ import java.net.MalformedURLException; import sun.net.www.ParseUtil; /** - *

* This class checks dependent extensions a particular jar file may have * declared through its manifest attributes. - *

+ *

* Jar file declared dependent extensions through the extension-list * attribute. The extension-list contains a list of keys used to * fetch the other attributes describing the required extension. * If key is the extension key declared in the extension-list * attribute, the following describing attribute can be found in - * the manifest : - * key-Extension-Name: (Specification package name) - * key-Specification-Version: (Specification-Version) - * key-Implementation-Version: (Implementation-Version) - * key-Implementation-Vendor-Id: (Imlementation-Vendor-Id) - * key-Implementation-Version: (Implementation version) - * key-Implementation-URL: (URL to download the requested extension) + * the manifest: + *

    + *
  • key-Extension-Name: (Specification package name)
  • + *
  • key-Specification-Version: (Specification-Version)
  • + *
  • key-Implementation-Version: (Implementation-Version)
  • + *
  • key-Implementation-Vendor-Id: (Imlementation-Vendor-Id)
  • + *
  • key-Implementation-Version: (Implementation version)
  • + *
  • key-Implementation-URL: (URL to download the requested extension)
  • + *
*

* This class also maintain versioning consistency of installed * extensions dependencies declared in jar file manifest. - *

* * @deprecated this class will be removed in a future release. * @author Jerome Dochez @@ -76,10 +76,9 @@ public class ExtensionDependency { private static Vector providers; /** - *

* Register an ExtensionInstallationProvider. The provider is responsible * for handling the installation (upgrade) of any missing extensions. - *

+ * * @param eip ExtensionInstallationProvider implementation */ public synchronized static void addExtensionInstallationProvider @@ -92,9 +91,7 @@ public class ExtensionDependency { } /** - *

* Unregister a previously installed installation provider - *

*/ public synchronized static void removeExtensionInstallationProvider (ExtensionInstallationProvider eip) @@ -103,10 +100,9 @@ public class ExtensionDependency { } /** - *

* Checks the dependencies of the jar file on installed extension. - *

- * @param jarFile containing the attriutes declaring the dependencies + * + * @param jar containing the attributes declaring the dependencies */ public static boolean checkExtensionsDependencies(JarFile jar) { @@ -182,9 +178,8 @@ public class ExtensionDependency { /* - *

* Check that a particular dependency on an extension is satisfied. - *

+ * * @param extensionName is the key used for the attributes in the manifest * @param attr is the attributes of the manifest file * @@ -204,10 +199,9 @@ public class ExtensionDependency { } /* - *

* Check if a particular extension is part of the currently installed * extensions. - *

+ * * @param extensionName is the key for the attributes in the manifest * @param attr is the attributes of the manifest * @@ -262,11 +256,9 @@ public class ExtensionDependency { } /* - *

* Check if the requested extension described by the attributes * in the manifest under the key extensionName is compatible with * the jar file. - *

* * @param extensionName key in the attribute list * @param attr manifest file attributes @@ -337,10 +329,8 @@ public class ExtensionDependency { } /* - *

* An required extension is missing, if an ExtensionInstallationProvider is * registered, delegate the installation of that particular extension to it. - *

* * @param reqInfo Missing extension information * @param instInfo Older installed version information @@ -380,11 +370,9 @@ public class ExtensionDependency { } /** - *

* Checks if the extension, that is specified in the extension-list in * the applet jar manifest, is already installed (i.e. exists in the * extension directory). - *

* * @param extensionName extension name in the extension-list * @@ -428,9 +416,7 @@ public class ExtensionDependency { } /** - *

* @return the java.ext.dirs property as a list of directory - *

*/ private static File[] getExtDirs() { String s = java.security.AccessController.doPrivileged( @@ -456,9 +442,8 @@ public class ExtensionDependency { } /* - *

* Scan the directories and return all files installed in those - *

+ * * @param dirs list of directories to scan * * @return the list of files installed in all the directories @@ -483,9 +468,7 @@ public class ExtensionDependency { } /* - *

* @return the list of installed extensions jar files - *

*/ private File[] getInstalledExtensions() throws IOException { return AccessController.doPrivileged( @@ -503,9 +486,7 @@ public class ExtensionDependency { } /* - *

* Add the newly installed jar file to the extension class loader. - *

* * @param cl the current installed extension class loader * diff --git a/jdk/src/java.base/share/classes/sun/misc/ExtensionInfo.java b/jdk/src/java.base/share/classes/sun/misc/ExtensionInfo.java index e6aad939eb8..c3680cd00ec 100644 --- a/jdk/src/java.base/share/classes/sun/misc/ExtensionInfo.java +++ b/jdk/src/java.base/share/classes/sun/misc/ExtensionInfo.java @@ -45,9 +45,7 @@ import java.lang.Character.*; public class ExtensionInfo { /** - *

* public static values returned by the isCompatible method - *

*/ public static final int COMPATIBLE = 0; public static final int REQUIRE_SPECIFICATION_UPGRADE = 1; @@ -56,10 +54,8 @@ public class ExtensionInfo { public static final int INCOMPATIBLE = 4; /** - *

* attributes fully describer an extension. The underlying described * extension may be installed and requested. - *

*/ public String title; public String name; @@ -76,15 +72,12 @@ public class ExtensionInfo { /** - *

* Create a new uninitialized extension information object - *

*/ public ExtensionInfo() { } /** - *

* Create and initialize an extension information object. * The initialization uses the attributes passed as being * the content of a manifest file to load the extension @@ -93,7 +86,7 @@ public class ExtensionInfo { * extension they may depend on, the extension key parameter * is prepanded to the attribute name to make the key used * to retrieve the attribute from the manifest file - *

+ * * @param extensionKey unique extension key in the manifest * @param attr Attributes of a manifest file */ @@ -149,13 +142,11 @@ public class ExtensionInfo { } /** - *

* @return true if the extension described by this extension information * is compatible with the extension described by the extension * information passed as a parameter - *

* - * @param the requested extension information to compare to + * @param ei the requested extension information to compare to */ public int isCompatibleWith(ExtensionInfo ei) { @@ -204,10 +195,8 @@ public class ExtensionInfo { } /** - *

* helper method to print sensible information on the undelying described * extension - *

*/ public String toString() { return "Extension : title(" + title + "), name(" + name + "), spec vendor(" + @@ -217,15 +206,15 @@ public class ExtensionInfo { } /* - *

* helper method to compare two versions. * version are in the x.y.z.t pattern. - *

+ * * @param source version to compare to * @param target version used to compare against - * @return < 0 if source < version - * > 0 if source > version - * = 0 if source = version + * @return
{@code
+     *   < 0 if source < version
+     *   > 0 if source > version
+     *   = 0 if source = version}
*/ private int compareExtensionVersion(String source, String target) throws NumberFormatException @@ -238,15 +227,15 @@ public class ExtensionInfo { /* - *

* helper method to compare two versions. * version are in the x.y.z.t pattern. - *

+ * * @param source version to compare to * @param target version used to compare against - * @return < 0 if source < version - * > 0 if source > version - * = 0 if source = version + * @return
{@code
+     *   < 0 if source < version
+     *   > 0 if source > version
+     *   = 0 if source = version}
*/ private int strictCompareExtensionVersion(String source, String target) throws NumberFormatException diff --git a/jdk/src/java.base/share/classes/sun/misc/FDBigInteger.java b/jdk/src/java.base/share/classes/sun/misc/FDBigInteger.java index 77d6fbc08b6..972ccd1ef5f 100644 --- a/jdk/src/java.base/share/classes/sun/misc/FDBigInteger.java +++ b/jdk/src/java.base/share/classes/sun/misc/FDBigInteger.java @@ -384,8 +384,8 @@ public /*@ spec_bigint_math @*/ class FDBigInteger { * Retrieves the normalization bias of the FDBigIntger. The * normalization bias is a left shift such that after it the highest word * of the value will have the 4 highest bits equal to zero: - * (highestWord & 0xf0000000) == 0, but the next bit should be 1 - * (highestWord & 0x08000000) != 0. + * {@code (highestWord & 0xf0000000) == 0}, but the next bit should be 1 + * {@code (highestWord & 0x08000000) != 0}. * * @return The normalization bias. */ @@ -546,9 +546,9 @@ public /*@ spec_bigint_math @*/ class FDBigInteger { * We assume that S has been normalized, as above, and that * "this" has been left-shifted accordingly. * Also assumed, of course, is that the result, q, can be expressed - * as an integer, 0 <= q < 10. + * as an integer, {@code 0 <= q < 10}. * - * @param The divisor of this FDBigInteger. + * @param S The divisor of this FDBigInteger. * @return q = (int)(this / S). */ /*@ @@ -685,7 +685,7 @@ public /*@ spec_bigint_math @*/ class FDBigInteger { * * @param p5 The exponent of the power-of-five factor. * @param p2 The exponent of the power-of-two factor. - * @return + * @return The multiplication result. */ /*@ @ requires this.value() == 0 || p5 == 0 && p2 == 0; @@ -931,11 +931,11 @@ public /*@ spec_bigint_math @*/ class FDBigInteger { /** * Compares the parameter with this FDBigInteger. Returns an * integer accordingly as: - *
-     * >0: this > other
-     *  0: this == other
-     * <0: this < other
-     * 
+ *
{@code
+     * > 0: this > other
+     *   0: this == other
+     * < 0: this < other
+     * }
* * @param other The FDBigInteger to compare. * @return A negative value, zero, or a positive value according to the @@ -974,11 +974,11 @@ public /*@ spec_bigint_math @*/ class FDBigInteger { * Compares this FDBigInteger with * 5p5 * 2p2. * Returns an integer accordingly as: - *
-     * >0: this > other
-     *  0: this == other
-     * <0: this < other
-     * 
+ *
{@code
+     * > 0: this > other
+     *   0: this == other
+     * < 0: this < other
+     * }
* @param p5 The exponent of the power-of-five factor. * @param p2 The exponent of the power-of-two factor. * @return A negative value, zero, or a positive value according to the @@ -1011,11 +1011,11 @@ public /*@ spec_bigint_math @*/ class FDBigInteger { /** * Compares this FDBigInteger with x + y. Returns a * value according to the comparison as: - *
+     * 
{@code
      * -1: this <  x + y
      *  0: this == x + y
      *  1: this >  x + y
-     * 
+ * }
* @param x The first addend of the sum to compare. * @param y The second addend of the sum to compare. * @return -1, 0, or 1 according to the result of the comparison. diff --git a/jdk/src/java.base/share/classes/sun/misc/FloatingDecimal.java b/jdk/src/java.base/share/classes/sun/misc/FloatingDecimal.java index eef4caf9905..b3a4a2a7575 100644 --- a/jdk/src/java.base/share/classes/sun/misc/FloatingDecimal.java +++ b/jdk/src/java.base/share/classes/sun/misc/FloatingDecimal.java @@ -154,7 +154,7 @@ public class FloatingDecimal{ /** * Indicates the sign of the value. - * @return value < 0.0. + * @return {@code value < 0.0}. */ public boolean isNegative(); diff --git a/jdk/src/java.base/share/classes/sun/misc/IOUtils.java b/jdk/src/java.base/share/classes/sun/misc/IOUtils.java index 57f8918975a..bd4b1430c4e 100644 --- a/jdk/src/java.base/share/classes/sun/misc/IOUtils.java +++ b/jdk/src/java.base/share/classes/sun/misc/IOUtils.java @@ -39,7 +39,7 @@ public class IOUtils { /** * Read up to length of bytes from in * until EOF is detected. - * @param in input stream, must not be null + * @param is input stream, must not be null * @param length number of bytes to read, -1 or Integer.MAX_VALUE means * read as much as possible * @param readAll if true, an EOFException will be thrown if not enough diff --git a/jdk/src/java.base/share/classes/sun/misc/JarFilter.java b/jdk/src/java.base/share/classes/sun/misc/JarFilter.java index b4db96db08f..9036ecaed87 100644 --- a/jdk/src/java.base/share/classes/sun/misc/JarFilter.java +++ b/jdk/src/java.base/share/classes/sun/misc/JarFilter.java @@ -29,10 +29,8 @@ import java.io.File; import java.io.FilenameFilter; /** - *

* This class checks that only jar and zip files are included in the file list. * This class is used in extension installation support (ExtensionDependency). - *

* * @deprecated this class will be removed in a future release. * @author Michael Colburn diff --git a/jdk/src/java.base/share/classes/sun/misc/JavaLangAccess.java b/jdk/src/java.base/share/classes/sun/misc/JavaLangAccess.java index a86453df430..db37e18fffe 100644 --- a/jdk/src/java.base/share/classes/sun/misc/JavaLangAccess.java +++ b/jdk/src/java.base/share/classes/sun/misc/JavaLangAccess.java @@ -91,14 +91,14 @@ public interface JavaLangAccess { * may be added to the delete on exit list by the application shutdown * hooks. * - * @params slot the slot in the shutdown hook array, whose element - * will be invoked in order during shutdown - * @params registerShutdownInProgress true to allow the hook - * to be registered even if the shutdown is in progress. - * @params hook the hook to be registered + * @param slot the slot in the shutdown hook array, whose element + * will be invoked in order during shutdown + * @param registerShutdownInProgress true to allow the hook + * to be registered even if the shutdown is in progress. + * @param hook the hook to be registered * - * @throw IllegalStateException if shutdown is in progress and - * the slot is not valid to register. + * @throws IllegalStateException if shutdown is in progress and + * the slot is not valid to register. */ void registerShutdownHook(int slot, boolean registerShutdownInProgress, Runnable hook); diff --git a/jdk/src/java.base/share/classes/sun/misc/Perf.java b/jdk/src/java.base/share/classes/sun/misc/Perf.java index bafd39dd90c..311e92c8f64 100644 --- a/jdk/src/java.base/share/classes/sun/misc/Perf.java +++ b/jdk/src/java.base/share/classes/sun/misc/Perf.java @@ -67,13 +67,13 @@ public final class Perf { * AccessController.doPrivileged(PrivilegedAction). *

Here is a suggested idiom for use of this class: * - *

+     * 
{@code
      * class MyTrustedClass {
      *   private static final Perf perf =
      *       AccessController.doPrivileged(new Perf.GetPerfAction());
      *   ...
      * }
-     * 
+ * }
*

* In the presence of a security manager, the MyTrustedClass * class in the above example will need to be granted the @@ -171,8 +171,7 @@ public final class Perf { * The attach mode specifies the access permissions requested for the * instrumentation buffer of the target virtual machine. The permitted * access permissions are: - *

- * + *

    *
  • "r" - Read only access. This Java virtual machine has only * read access to the instrumentation buffer for the target Java * virtual machine. @@ -180,7 +179,7 @@ public final class Perf { * write access to the instrumentation buffer for the target Java virtual * machine. This mode is currently not supported and is reserved for * future enhancements. - * + *
* * @param lvmid an integer that uniquely identifies the * target local Java virtual machine. diff --git a/jdk/src/java.base/share/classes/sun/misc/PerfCounter.java b/jdk/src/java.base/share/classes/sun/misc/PerfCounter.java index 6d6969a1f69..21a36a8cf8d 100644 --- a/jdk/src/java.base/share/classes/sun/misc/PerfCounter.java +++ b/jdk/src/java.base/share/classes/sun/misc/PerfCounter.java @@ -37,7 +37,7 @@ import java.security.AccessController; * The perf counters will be created in the jvmstat perf buffer * that the HotSpot VM creates. The default size is 32K and thus * the number of counters is bounded. You can alter the size - * with -XX:PerfDataMemorySize= option. If there is + * with {@code -XX:PerfDataMemorySize=} option. If there is * insufficient memory in the jvmstat perf buffer, the C heap memory * will be used and thus the application will continue to run if * the counters added exceeds the buffer size but the counters diff --git a/jdk/src/java.base/share/classes/sun/misc/PerformanceLogger.java b/jdk/src/java.base/share/classes/sun/misc/PerformanceLogger.java index 9f4a9e490ec..6e8917b4545 100644 --- a/jdk/src/java.base/share/classes/sun/misc/PerformanceLogger.java +++ b/jdk/src/java.base/share/classes/sun/misc/PerformanceLogger.java @@ -51,10 +51,12 @@ import java.io.Writer; *

* To automatically track startup performance in an app or applet, * use the command-line parameter sun.perflog as follows:
+ *

{@code
  *     -Dsun.perflog[=file:]
+ * }
*
* where simply using the parameter with no value will enable output - * to the console and a value of "file:" will cause + * to the console and a value of "{@code file:}" will cause * that given filename to be created and used for all output. *

* By default, times are measured using System.currentTimeMillis(). To use diff --git a/jdk/src/java.base/share/classes/sun/misc/Resource.java b/jdk/src/java.base/share/classes/sun/misc/Resource.java index b314872a5eb..4ebf58144e4 100644 --- a/jdk/src/java.base/share/classes/sun/misc/Resource.java +++ b/jdk/src/java.base/share/classes/sun/misc/Resource.java @@ -154,7 +154,8 @@ public abstract class Resource { /** * Returns the Resource data as a ByteBuffer, but only if the input stream - * was implemented on top of a ByteBuffer. Return null otherwise. + * was implemented on top of a ByteBuffer. Return {@code null} otherwise. + * @return Resource data or null. */ public ByteBuffer getByteBuffer() throws IOException { InputStream in = cachedInputStream(); diff --git a/jdk/src/java.base/share/classes/sun/misc/Signal.java b/jdk/src/java.base/share/classes/sun/misc/Signal.java index a00ee9f089d..92438833737 100644 --- a/jdk/src/java.base/share/classes/sun/misc/Signal.java +++ b/jdk/src/java.base/share/classes/sun/misc/Signal.java @@ -50,7 +50,7 @@ import java.util.Hashtable; * Signal objects are created based on their names. For example: *

  * new Signal("INT");
- * 
+ * * constructs a signal object corresponding to SIGINT, which is * typically produced when the user presses Ctrl-C at the command line. * The Signal constructor throws IllegalArgumentException @@ -64,7 +64,7 @@ import java.util.Hashtable; * } * }; * Signal.handle(new Signal("INT"), handler); - * + * * * @author Sheng Liang * @author Bill Shannon @@ -149,7 +149,7 @@ public final class Signal { * * @param sig a signal * @param handler the handler to be registered with the given signal. - * @result the old handler + * @return the old handler * @exception IllegalArgumentException the signal is in use by the VM * @see sun.misc.Signal#raise(Signal sig) * @see sun.misc.SignalHandler diff --git a/jdk/src/java.base/share/classes/sun/misc/Unsafe.java b/jdk/src/java.base/share/classes/sun/misc/Unsafe.java index 1d3454e281e..6d7078a9751 100644 --- a/jdk/src/java.base/share/classes/sun/misc/Unsafe.java +++ b/jdk/src/java.base/share/classes/sun/misc/Unsafe.java @@ -641,9 +641,9 @@ public final class Unsafe { *
  • String: any object (not just a java.lang.String) *
  • InterfaceMethodRef: (NYI) a method handle to invoke on that call site's arguments * - * @params hostClass context for linkage, access control, protection domain, and class loader - * @params data bytes of a class file - * @params cpPatches where non-null entries exist, they replace corresponding CP entries in data + * @param hostClass context for linkage, access control, protection domain, and class loader + * @param data bytes of a class file + * @param cpPatches where non-null entries exist, they replace corresponding CP entries in data */ public native Class defineAnonymousClass(Class hostClass, byte[] data, Object[] cpPatches); @@ -808,9 +808,9 @@ public final class Unsafe { * The system imposes a maximum of 3 samples, representing * averages over the last 1, 5, and 15 minutes, respectively. * - * @params loadavg an array of double of size nelems - * @params nelems the number of samples to be retrieved and - * must be 1 to 3. + * @param loadavg an array of double of size nelems + * @param nelems the number of samples to be retrieved and + * must be 1 to 3. * * @return the number of samples actually retrieved; or -1 * if the load average is unobtainable. @@ -1108,7 +1108,6 @@ public final class Unsafe { *

    * 8-byte atomicity is only guaranteed on platforms on which * support atomic accesses to longs. - *

    * * @param o Java heap object in which the value resides, if any, else * null diff --git a/jdk/src/java.base/share/classes/sun/misc/VM.java b/jdk/src/java.base/share/classes/sun/misc/VM.java index 36bfb606495..8cb765758b4 100644 --- a/jdk/src/java.base/share/classes/sun/misc/VM.java +++ b/jdk/src/java.base/share/classes/sun/misc/VM.java @@ -315,7 +315,7 @@ public class VM { } /* - * Add n to the objects pending for finalization count. + * Add {@code n} to the objects pending for finalization count. * * @param n an integer value to be added to the objects pending * for finalization count diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages.java index 56f76bb2876..4cf913210a7 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_de.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_de.java index e2961c52e84..d22b1e592ec 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_de.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_de.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_de extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_es.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_es.java index 9e762017a45..1d4bc2de250 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_es.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_es.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_es extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_fr.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_fr.java index b742b26ef06..8f74b9b063e 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_fr.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_fr.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_fr extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_it.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_it.java index ee7dd0a33c8..2b23c638b31 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_it.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_it.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_it extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ja.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ja.java index 4f1455187b4..c5242bf108c 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ja.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ja.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_ja extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ko.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ko.java index 53c32fc3f03..63119101d46 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ko.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_ko.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_ko extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_pt_BR.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_pt_BR.java index 4781700e06f..ec756d2c4b0 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_pt_BR.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_pt_BR.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_pt_BR extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_sv.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_sv.java index a813852caa8..3c7402854ab 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_sv.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_sv.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_sv extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_CN.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_CN.java index d884f74a114..efd2ff0ba8d 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_CN.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_CN.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_zh_CN extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_TW.java b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_TW.java index 530a7cdef52..da6938f84a9 100644 --- a/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_TW.java +++ b/jdk/src/java.base/share/classes/sun/misc/resources/Messages_zh_TW.java @@ -26,7 +26,7 @@ package sun.misc.resources; /** - *

    This class represents the ResourceBundle + * This class represents the {@code ResourceBundle} * for sun.misc. * * @author Michael Colburn @@ -35,9 +35,9 @@ package sun.misc.resources; public class Messages_zh_TW extends java.util.ListResourceBundle { /** - * Returns the contents of this ResourceBundle. - *

    - * @return the contents of this ResourceBundle. + * Returns the contents of this {@code ResourceBundle}. + * + * @return the contents of this {@code ResourceBundle}. */ public Object[][] getContents() { return contents; diff --git a/jdk/src/java.base/share/classes/sun/nio/cs/Surrogate.java b/jdk/src/java.base/share/classes/sun/nio/cs/Surrogate.java index 8b2fcf6765f..96e30275866 100644 --- a/jdk/src/java.base/share/classes/sun/nio/cs/Surrogate.java +++ b/jdk/src/java.base/share/classes/sun/nio/cs/Surrogate.java @@ -175,10 +175,10 @@ public class Surrogate { * @param in The source buffer, from which one more character * will be consumed if c is a high surrogate * - * @returns Either a parsed UCS-4 character, in which case the isPair() - * and increment() methods will return meaningful values, or - * -1, in which case error() will return a descriptive result - * object + * @return Either a parsed UCS-4 character, in which case the isPair() + * and increment() methods will return meaningful values, or + * -1, in which case error() will return a descriptive result + * object */ public int parse(char c, CharBuffer in) { if (Character.isHighSurrogate(c)) { @@ -216,10 +216,10 @@ public class Surrogate { * @param ip The input index * @param il The input limit * - * @returns Either a parsed UCS-4 character, in which case the isPair() - * and increment() methods will return meaningful values, or - * -1, in which case error() will return a descriptive result - * object + * @return Either a parsed UCS-4 character, in which case the isPair() + * and increment() methods will return meaningful values, or + * -1, in which case error() will return a descriptive result + * object */ public int parse(char c, char[] ia, int ip, int il) { assert (ia[ip] == c); @@ -280,9 +280,9 @@ public class Surrogate { * @param dst The destination buffer, to which one or two UTF-16 * characters will be written * - * @returns Either a positive count of the number of UTF-16 characters - * written to the destination buffer, or -1, in which case - * error() will return a descriptive result object + * @return Either a positive count of the number of UTF-16 characters + * written to the destination buffer, or -1, in which case + * error() will return a descriptive result object */ public int generate(int uc, int len, CharBuffer dst) { if (Character.isBmpCodePoint(uc)) { @@ -325,9 +325,9 @@ public class Surrogate { * @param dp The destination position * @param dl The destination limit * - * @returns Either a positive count of the number of UTF-16 characters - * written to the destination buffer, or -1, in which case - * error() will return a descriptive result object + * @return Either a positive count of the number of UTF-16 characters + * written to the destination buffer, or -1, in which case + * error() will return a descriptive result object */ public int generate(int uc, int len, char[] da, int dp, int dl) { if (Character.isBmpCodePoint(uc)) { diff --git a/jdk/src/java.base/share/classes/sun/text/CompactByteArray.java b/jdk/src/java.base/share/classes/sun/text/CompactByteArray.java index 412bc0df36d..d9fa1da513f 100644 --- a/jdk/src/java.base/share/classes/sun/text/CompactByteArray.java +++ b/jdk/src/java.base/share/classes/sun/text/CompactByteArray.java @@ -49,7 +49,7 @@ package sun.text; * Han ideographs have the same value. However, lookup is much faster than a * hash table. * A compact array of any primitive data type serves two purposes: - *

      + *
        *
      • Fast access of the indexed values. *
      • Smaller memory footprint. *
      diff --git a/jdk/src/java.base/share/classes/sun/text/ComposedCharIter.java b/jdk/src/java.base/share/classes/sun/text/ComposedCharIter.java index 12560002455..53e0acb9cb1 100644 --- a/jdk/src/java.base/share/classes/sun/text/ComposedCharIter.java +++ b/jdk/src/java.base/share/classes/sun/text/ComposedCharIter.java @@ -50,7 +50,7 @@ public final class ComposedCharIter { } /** - * Construct a new ComposedCharIter. The iterator will return + * Construct a new {@code ComposedCharIter}. The iterator will return * all Unicode characters with canonical decompositions, excluding Korean * Hangul characters. */ @@ -58,10 +58,10 @@ public final class ComposedCharIter { /** * Returns the next precomposed Unicode character. - * Repeated calls to next return all of the precomposed characters defined + * Repeated calls to {@code next} return all of the precomposed characters defined * by Unicode, in ascending order. After all precomposed characters have - * been returned, {@link #hasNext} will return false and further calls - * to next will return {@link #DONE}. + * been returned, {@link #hasNext} will return {@code false} and further calls + * to {@code next} will return {@link #DONE}. */ public int next() { if (curChar == decompNum - 1) { diff --git a/jdk/src/java.base/share/classes/sun/text/Normalizer.java b/jdk/src/java.base/share/classes/sun/text/Normalizer.java index 3d393920559..82a6ebd9e40 100644 --- a/jdk/src/java.base/share/classes/sun/text/Normalizer.java +++ b/jdk/src/java.base/share/classes/sun/text/Normalizer.java @@ -32,7 +32,7 @@ import sun.text.normalizer.NormalizerImpl; * This Normalizer is for Unicode 3.2 support for IDNA only. * Developers should not use this class. * - * @ since 1.6 + * @since 1.6 */ public final class Normalizer { diff --git a/jdk/src/java.base/share/classes/sun/text/bidi/BidiBase.java b/jdk/src/java.base/share/classes/sun/text/bidi/BidiBase.java index bbf1b4b6a21..4691dbc853b 100644 --- a/jdk/src/java.base/share/classes/sun/text/bidi/BidiBase.java +++ b/jdk/src/java.base/share/classes/sun/text/bidi/BidiBase.java @@ -81,14 +81,13 @@ import sun.text.normalizer.UTF16; * *

      General remarks about the API:

      * - * The "limit" of a sequence of characters is the position just after + * The "limit" of a sequence of characters is the position just after * their last character, i.e., one more than that position. *

      * - * Some of the API methods provide access to "runs". Such a - * "run" is defined as a sequence of characters that are at the same + * Some of the API methods provide access to "runs". Such a + * "run" is defined as a sequence of characters that are at the same * embedding level after performing the Bidi algorithm. - *

      * *

      Basic concept: paragraph

      * A piece of text can be divided into several paragraphs by characters @@ -141,7 +140,8 @@ import sun.text.normalizer.UTF16; * these special values are designed that way. Also, the implementation * assumes that MAX_EXPLICIT_LEVEL is odd. * - *
        See Also: + *

        See Also: + *

          *
        • {@link #LEVEL_DEFAULT_LTR} *
        • {@link #LEVEL_DEFAULT_RTL} *
        • {@link #LEVEL_OVERRIDE} @@ -153,7 +153,8 @@ import sun.text.normalizer.UTF16; * Reordering mode values indicate which variant of the Bidi algorithm to * use. * - *
            See Also: + *

            See Also: + *

              *
            • {@link #setReorderingMode} *
            • {@link #REORDER_DEFAULT} *
            • {@link #REORDER_NUMBERS_SPECIAL} @@ -166,7 +167,8 @@ import sun.text.normalizer.UTF16; * *

              Basic concept: Reordering Options

              * Reordering options can be applied during Bidi text transformations. - *
                See Also: + *

                See Also: + *

                  *
                • {@link #setReorderingOptions} *
                • {@link #OPTION_DEFAULT} *
                • {@link #OPTION_INSERT_MARKS} @@ -202,7 +204,7 @@ import sun.text.normalizer.UTF16; * and therefore its implementation omitted from this sample code.
                • *
                * - *
                + * 
                {@code
                  *
                  *  package com.ibm.icu.dev.test.bidi;
                  *
                @@ -451,7 +453,7 @@ import sun.text.normalizer.UTF16;
                  *      }
                  *  }
                  *
                - * 
                + * }
                */ public class BidiBase { @@ -2419,9 +2421,9 @@ public class BidiBase { * (same index) character if the level has the * LEVEL_OVERRIDE bit set.

                * Except for that bit, it must be - * paraLevel<=embeddingLevels[]<=MAX_EXPLICIT_LEVEL, + * {@code paraLevel<=embeddingLevels[]<=MAX_EXPLICIT_LEVEL}, * with one exception: a level of zero may be specified for a - * paragraph separator even if paraLevel>0 when multiple + * paragraph separator even if {@code paraLevel > 0} when multiple * paragraphs are submitted in the same call to setPara().

                * Caution: A reference to this array, not a copy * of the levels, will be stored in the Bidi object; @@ -2680,7 +2682,7 @@ public class BidiBase { * For example, in pure LTR text with numbers the numbers would get * a resolved level of 2 higher than the surrounding text according to * the algorithm. This implementation may set all resolved levels to - * the same value in such a case.

                + * the same value in such a case. * * @param paragraph a paragraph of text with optional character and * paragraph attribute information @@ -2817,7 +2819,7 @@ public class BidiBase { } /** - * Get the index of a paragraph, given a position within the text.

                + * Get the index of a paragraph, given a position within the text. * * @param charIndex is the index of a character within the text, in the * range [0..getProcessedLength()-1]. diff --git a/jdk/src/java.base/share/classes/sun/text/bidi/BidiRun.java b/jdk/src/java.base/share/classes/sun/text/bidi/BidiRun.java index 07519db3934..c0323834c60 100644 --- a/jdk/src/java.base/share/classes/sun/text/bidi/BidiRun.java +++ b/jdk/src/java.base/share/classes/sun/text/bidi/BidiRun.java @@ -42,7 +42,7 @@ package sun.text.bidi; /** * A BidiRun represents a sequence of characters at the same embedding level. * The Bidi algorithm decomposes a piece of text into sequences of characters - * at the same embedding level, each such sequence is called a run. + * at the same embedding level, each such sequence is called a "run". * *

                A BidiRun represents such a run by storing its essential properties, * but does not duplicate the characters which form the run. diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/ICUBinary.java b/jdk/src/java.base/share/classes/sun/text/normalizer/ICUBinary.java index 20984d3b8fb..3e0c348a163 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/ICUBinary.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/ICUBinary.java @@ -65,7 +65,7 @@ public final class ICUBinary /** *

                ICU data header reader method. * Takes a ICU generated big-endian input stream, parse the ICU standard - * file header and authenticates them.

                + * file header and authenticates them. *

                Header format: *

                  *
                • Header size (char) @@ -84,7 +84,7 @@ public final class ICUBinary * [0] major [1] minor [2] milli [3] micro *
                • Unicode version (4 bytes) this ICU is based on. *
                - *

                + * *

                * Example of use:
                *

                @@ -98,7 +98,7 @@ public final class ICUBinary
                     *    System.out.println("This is not a ICU data file");
                     * }
                     * 
                - *

                + * * @param inputStream input stream that contains the ICU data header * @param dataFormatIDExpected Data format expected. An array of 4 bytes * information about the data format. diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/IntTrie.java b/jdk/src/java.base/share/classes/sun/text/normalizer/IntTrie.java index ddc2cc40e58..4be2d6e5862 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/IntTrie.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/IntTrie.java @@ -58,7 +58,7 @@ public class IntTrie extends Trie * trie.

                * @param inputStream file input stream to a ICU data file, containing * the trie - * @param dataManipulate object which provides methods to parse the char + * @param datamanipulate object which provides methods to parse the char * data * @throws IOException thrown when data reading fails * @draft 2.1 diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/NormalizerBase.java b/jdk/src/java.base/share/classes/sun/text/normalizer/NormalizerBase.java index b49db438449..43c4e10167c 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/NormalizerBase.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/NormalizerBase.java @@ -55,16 +55,16 @@ import java.text.Normalizer; * In Unicode, this can be encoded as a single character (the * "composed" form): * - *

                + *

                  *      00C1    LATIN CAPITAL LETTER A WITH ACUTE
                - * 

                + *
                * * or as two separate characters (the "decomposed" form): * - *

                + *

                  *      0041    LATIN CAPITAL LETTER A
                  *      0301    COMBINING ACUTE ACCENT
                - * 

                + *
                * * To a user of your program, however, both of these sequences should be * treated as the same "user-level" character "A with acute accent". When you @@ -76,17 +76,17 @@ import java.text.Normalizer; * * Similarly, the string "ffi" can be encoded as three separate letters: * - *

                + *

                  *      0066    LATIN SMALL LETTER F
                  *      0066    LATIN SMALL LETTER F
                  *      0069    LATIN SMALL LETTER I
                - * 

                + *
                * * or as the single character * - *

                + *

                  *      FB03    LATIN SMALL LIGATURE FFI
                - * 

                + *
                * * The ffi ligature is not a distinct semantic character, and strictly speaking * it shouldn't be in Unicode at all, but it was included for compatibility @@ -555,12 +555,12 @@ public final class NormalizerBase implements Cloneable { //------------------------------------------------------------------------- /** - * Creates a new Normalizer object for iterating over the + * Creates a new {@code Normalizer} object for iterating over the * normalized form of a given string. *

                - * The options parameter specifies which optional - * Normalizer features are to be enabled for this object. - *

                + * The {@code options} parameter specifies which optional + * {@code Normalizer} features are to be enabled for this object. + * * @param str The string to be normalized. The normalization * will start at the beginning of the string. * @@ -579,9 +579,9 @@ public final class NormalizerBase implements Cloneable { } /** - * Creates a new Normalizer object for iterating over the + * Creates a new {@code Normalizer} object for iterating over the * normalized form of the given text. - *

                + * * @param iter The input text to be normalized. The normalization * will start at the beginning of the string. * @@ -592,9 +592,9 @@ public final class NormalizerBase implements Cloneable { } /** - * Creates a new Normalizer object for iterating over the + * Creates a new {@code Normalizer} object for iterating over the * normalized form of the given text. - *

                + * * @param iter The input text to be normalized. The normalization * will start at the beginning of the string. * @@ -615,13 +615,13 @@ public final class NormalizerBase implements Cloneable { } /** - * Clones this Normalizer object. All properties of this + * Clones this {@code Normalizer} object. All properties of this * object are duplicated in the new object, including the cloning of any * {@link CharacterIterator} that was passed in to the constructor * or to {@link #setText(CharacterIterator) setText}. * However, the text storage underlying - * the CharacterIterator is not duplicated unless the - * iterator's clone method does so. + * the {@code CharacterIterator} is not duplicated unless the + * iterator's {@code clone} method does so. * @stable ICU 2.8 */ public Object clone() { @@ -791,7 +791,7 @@ public final class NormalizerBase implements Cloneable { //------------------------------------------------------------------------- /** - * Return the current character in the normalized text-> + * Return the current character in the normalized text. * @return The codepoint as an int * @stable ICU 2.8 */ @@ -872,10 +872,10 @@ public final class NormalizerBase implements Cloneable { * while {@link #next} and {@link #previous} iterate through characters * in the normalized output. This means that there is not * necessarily a one-to-one correspondence between characters returned - * by next and previous and the indices passed to and - * returned from setIndex and {@link #getIndex}. - *

                - * @param index the desired index in the input text-> + * by {@code next} and {@code previous} and the indices passed to and + * returned from {@code setIndex} and {@link #getIndex}. + * + * @param index the desired index in the input text. * * @return the first normalized character that is the result of iterating * forward starting at the given index. @@ -894,8 +894,8 @@ public final class NormalizerBase implements Cloneable { /** * Retrieve the index of the start of the input text. This is the begin - * index of the CharacterIterator or the start (i.e. 0) of the - * String over which this Normalizer is iterating + * index of the {@code CharacterIterator} or the start (i.e. 0) of the + * {@code String} over which this {@code Normalizer} is iterating * @deprecated ICU 2.2. Use startIndex() instead. * @return The codepoint as an int * @see #startIndex @@ -907,8 +907,8 @@ public final class NormalizerBase implements Cloneable { /** * Retrieve the index of the end of the input text. This is the end index - * of the CharacterIterator or the length of the String - * over which this Normalizer is iterating + * of the {@code CharacterIterator} or the length of the {@code String} + * over which this {@code Normalizer} is iterating * @deprecated ICU 2.2. Use endIndex() instead. * @return The codepoint as an int * @see #endIndex @@ -927,9 +927,9 @@ public final class NormalizerBase implements Cloneable { * Note: This method sets the position in the input, while * {@link #next} and {@link #previous} iterate through characters in the * output. This means that there is not necessarily a one-to-one - * correspondence between characters returned by next and - * previous and the indices passed to and returned from - * setIndex and {@link #getIndex}. + * correspondence between characters returned by {@code next} and + * {@code previous} and the indices passed to and returned from + * {@code setIndex} and {@link #getIndex}. * @return The current iteration position * @stable ICU 2.8 */ @@ -942,9 +942,9 @@ public final class NormalizerBase implements Cloneable { } /** - * Retrieve the index of the end of the input text-> This is the end index - * of the CharacterIterator or the length of the String - * over which this Normalizer is iterating + * Retrieve the index of the end of the input text. This is the end index + * of the {@code CharacterIterator} or the length of the {@code String} + * over which this {@code Normalizer} is iterating * @return The current iteration position * @stable ICU 2.8 */ @@ -963,9 +963,9 @@ public final class NormalizerBase implements Cloneable { * return previously buffers characters in the old normalization mode * until the iteration is able to re-sync at the next base character. * It is safest to call {@link #setText setText()}, {@link #first}, - * {@link #last}, etc. after calling setMode. - *

                - * @param newMode the new mode for this Normalizer. + * {@link #last}, etc. after calling {@code setMode}. + * + * @param newMode the new mode for this {@code Normalizer}. * The supported modes are: *

                  *
                • {@link #COMPOSE} - Unicode canonical decompositiion @@ -985,7 +985,7 @@ public final class NormalizerBase implements Cloneable { mode = newMode; } /** - * Return the basic operation performed by this Normalizer + * Return the basic operation performed by this {@code Normalizer} * * @see #setMode * @stable ICU 2.8 @@ -995,8 +995,8 @@ public final class NormalizerBase implements Cloneable { } /** - * Set the input text over which this Normalizer will iterate. - * The iteration position is set to the beginning of the input text-> + * Set the input text over which this {@code Normalizer} will iterate. + * The iteration position is set to the beginning of the input text. * @param newText The new string to be normalized. * @stable ICU 2.8 */ @@ -1011,8 +1011,8 @@ public final class NormalizerBase implements Cloneable { } /** - * Set the input text over which this Normalizer will iterate. - * The iteration position is set to the beginning of the input text-> + * Set the input text over which this {@code Normalizer} will iterate. + * The iteration position is set to the beginning of the input text. * @param newText The new string to be normalized. * @stable ICU 2.8 */ @@ -1571,7 +1571,7 @@ public final class NormalizerBase implements Cloneable { // /** - * Creates a new Normalizer object for iterating over the + * Creates a new {@code Normalizer} object for iterating over the * normalized form of a given string. * * @param str The string to be normalized. The normalization @@ -1646,7 +1646,6 @@ public final class NormalizerBase implements Cloneable { * perform further tests to arrive at a true/false result. * @param str the input string to be checked to see if it is normalized * @param form the normalization form - * @param options the optional features to be enabled. */ public static boolean isNormalized(String str, Normalizer.Form form) { return isNormalized(str, form, UNICODE_LATEST); diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/RangeValueIterator.java b/jdk/src/java.base/share/classes/sun/text/normalizer/RangeValueIterator.java index 71604fde007..771703859fe 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/RangeValueIterator.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/RangeValueIterator.java @@ -38,12 +38,13 @@ package sun.text.normalizer; /** - *

                  Interface for enabling iteration over sets of , + *

                  Interface for enabling iteration over sets of + * {@code }, * where index is the sorted integer index in ascending order and value, its - * associated integer value.

                  + * associated integer value. *

                  The result for each iteration is the consecutive range of - * with the same value. Result is represented by - * where

                  + * {@code } with the same value. Result is represented by + * {@code } where *
                    *
                  • start is the starting integer of the result range *
                  • limit is 1 after the maximum integer that follows start, such that @@ -56,10 +57,10 @@ package sun.text.normalizer; * Hence value(start) = value(start + 1) = .... = value(start + n) = .... = * value(limit - 1). However value(start -1) != value(start) and * value(limit) != value(start). - *

                    + * *

                    Most implementations will be created by factory methods, such as the * character type iterator in UCharacter.getTypeIterator. See example below. - *

                    + * * Example of use:
                    *
                      * RangeValueIterator iterator = UCharacter.getTypeIterator();
                    diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/Replaceable.java b/jdk/src/java.base/share/classes/sun/text/normalizer/Replaceable.java
                    index 5cf2bba578a..e05593540b8 100644
                    --- a/jdk/src/java.base/share/classes/sun/text/normalizer/Replaceable.java
                    +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/Replaceable.java
                    @@ -71,10 +71,9 @@ package sun.text.normalizer;
                      *   
                  • If there is no previous character (i.e. start == 0), use the * following character
                  • *
                  • If there is no following character (i.e. the replaceable was - * empty), use default metadata
                    + * empty), use default metadata
                  • *
                  • If the code point U+FFFF is seen, it should be interpreted as - * a special marker having no metadata
                  • - *
                  • + * a special marker having no metadata
                  • *
                  * If this is not the behavior, the subclass should document any differences. * @@ -111,10 +110,10 @@ public interface Replaceable { * starting at index dstStart and ending at index * dstStart + (srcLimit-srcStart) - 1. * - * @param srcStart the beginning index to copy, inclusive; 0 - * <= start <= limit. + * @param srcStart the beginning index to copy, inclusive; + * {@code 0 <= start <= limit}. * @param srcLimit the ending index to copy, exclusive; - * start <= limit <= length(). + * {@code start <= limit <= length()}. * @param dst the destination array. * @param dstStart the start offset in the destination array. * @stable ICU 2.0 diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/ReplaceableString.java b/jdk/src/java.base/share/classes/sun/text/normalizer/ReplaceableString.java index 0610d6964e3..eb2c4399cd2 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/ReplaceableString.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/ReplaceableString.java @@ -109,10 +109,10 @@ public class ReplaceableString implements Replaceable { * starting at index dstStart and ending at index * dstStart + (srcLimit-srcStart) - 1. * - * @param srcStart the beginning index to copy, inclusive; 0 - * <= start <= limit. + * @param srcStart the beginning index to copy, inclusive; + * {@code 0 <= start <= limit}. * @param srcLimit the ending index to copy, exclusive; - * start <= limit <= length(). + * {@code start <= limit <= length()}. * @param dst the destination array. * @param dstStart the start offset in the destination array. * @stable ICU 2.0 diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/ReplaceableUCharacterIterator.java b/jdk/src/java.base/share/classes/sun/text/normalizer/ReplaceableUCharacterIterator.java index 9eabcba4697..8227ca78124 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/ReplaceableUCharacterIterator.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/ReplaceableUCharacterIterator.java @@ -150,14 +150,12 @@ public class ReplaceableUCharacterIterator extends UCharacterIterator { } /** - *

                  Sets the currentIndex to the specified currentIndex in the text and returns that + * Sets the currentIndex to the specified currentIndex in the text and returns that * single UTF16 character at currentIndex. - * This assumes the text is stored as 16-bit code units.

                  + * This assumes the text is stored as 16-bit code units. * @param currentIndex the currentIndex within the text. * @exception IllegalArgumentException is thrown if an invalid currentIndex is * supplied. i.e. currentIndex is out of bounds. - * @return the character at the specified currentIndex or DONE if the specified - * currentIndex is equal to the end of the text. */ public void setIndex(int currentIndex) { if (currentIndex < 0 || currentIndex > replaceable.length()) { diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/RuleCharacterIterator.java b/jdk/src/java.base/share/classes/sun/text/normalizer/RuleCharacterIterator.java index 029ceecb5e5..a287400ed4f 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/RuleCharacterIterator.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/RuleCharacterIterator.java @@ -101,22 +101,25 @@ public class RuleCharacterIterator { public static final int DONE = -1; /** - * Bitmask option to enable parsing of variable names. If (options & - * PARSE_VARIABLES) != 0, then an embedded variable will be expanded to + * Bitmask option to enable parsing of variable names. + * If {@code (options & PARSE_VARIABLES) != 0}, + * then an embedded variable will be expanded to * its value. Variables are parsed using the SymbolTable API. */ public static final int PARSE_VARIABLES = 1; /** - * Bitmask option to enable parsing of escape sequences. If (options & - * PARSE_ESCAPES) != 0, then an embedded escape sequence will be expanded + * Bitmask option to enable parsing of escape sequences. + * If {@code (options & PARSE_ESCAPES) != 0}, + * then an embedded escape sequence will be expanded * to its value. Escapes are parsed using Utility.unescapeAt(). */ public static final int PARSE_ESCAPES = 2; /** - * Bitmask option to enable skipping of whitespace. If (options & - * SKIP_WHITESPACE) != 0, then whitespace characters will be silently + * Bitmask option to enable skipping of whitespace. + * If {@code (options & SKIP_WHITESPACE) != 0}, + * then whitespace characters will be silently * skipped, as if they were not present in the input. Whitespace * characters are defined by UCharacterProperty.isRuleWhiteSpace(). */ diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/SymbolTable.java b/jdk/src/java.base/share/classes/sun/text/normalizer/SymbolTable.java index f49110e6fa9..305cec72867 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/SymbolTable.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/SymbolTable.java @@ -78,7 +78,7 @@ public interface SymbolTable { /** * Lookup the characters associated with this string and return it. - * Return null if no such name exists. The resultant + * Return {@code null} if no such name exists. The resultant * array may have length zero. * @param s the symbolic name to lookup * @return a char array containing the name's value, or null if @@ -91,7 +91,7 @@ public interface SymbolTable { /** * Lookup the UnicodeMatcher associated with the given character, and - * return it. Return null if not found. + * return it. Return {@code null} if not found. * @param ch a 32-bit code point from 0 to 0x10FFFF inclusive. * @return the UnicodeMatcher object represented by the given * character, or null if there is no mapping for ch. diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/Trie.java b/jdk/src/java.base/share/classes/sun/text/normalizer/Trie.java index 0430bf5e955..f90b2990bd7 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/Trie.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/Trie.java @@ -160,8 +160,10 @@ public abstract class Trie /** * Lead surrogate code points' index displacement in the index array. + *
                  {@code
                       * 0x10000-0xd800=0x2800
                       * 0x2800 >> INDEX_STAGE_1_SHIFT_
                  +    * }
                  */ protected static final int LEAD_INDEX_OFFSET_ = 0x2800 >> 5; /** @@ -191,7 +193,7 @@ public abstract class Trie /** * Number of index (stage 1) entries per lead surrogate. * Same as number of index entries for 1024 trail surrogates, - * ==0x400>>INDEX_STAGE_1_SHIFT_ + * {@code ==0x400>>INDEX_STAGE_1_SHIFT_} */ protected static final int SURROGATE_BLOCK_COUNT=(1<Class enabling iteration of the values in a Trie.

                  + * Class enabling iteration of the values in a Trie. *

                  Result of each iteration contains the interval of codepoints that have - * the same value type and the value type itself.

                  + * the same value type and the value type itself. *

                  The comparison of each codepoint value is done via extract(), which the - * default implementation is to return the value as it is.

                  + * default implementation is to return the value as it is. *

                  Method extract() can be overwritten to perform manipulations on - * codepoint values in order to perform specialized comparison.

                  + * codepoint values in order to perform specialized comparison. *

                  TrieIterator is designed to be a generic iterator for the CharTrie * and the IntTrie, hence to accommodate both types of data, the return - * result will be in terms of int (32 bit) values.

                  - *

                  See com.ibm.icu.text.UCharacterTypeIterator for examples of use.

                  + * result will be in terms of int (32 bit) values. + *

                  See com.ibm.icu.text.UCharacterTypeIterator for examples of use. *

                  Notes for porting utrie_enum from icu4c to icu4j:
                  * Internally, icu4c's utrie_enum performs all iterations in its body. In Java * sense, the caller will have to pass a object with a callback function @@ -63,18 +63,17 @@ package sun.text.normalizer; * the method extract(int) (equivalent to UTrieEnumValue). Independent of icu4j, * the caller will have to code his own iteration and flesh out the task * (equivalent to UTrieEnumRange) to be performed in the iteration loop. - *

                  - *

                  There are basically 3 usage scenarios for porting:

                  + * + *

                  There are basically 3 usage scenarios for porting: *

                  1) UTrieEnumValue is the only implemented callback then just implement a * subclass of TrieIterator and override the extract(int) method. The * extract(int) method is analogus to UTrieEnumValue callback. - *

                  + * *

                  2) UTrieEnumValue and UTrieEnumRange both are implemented then implement - * a subclass of TrieIterator, override the extract method and iterate, e.g - *

                  - *

                  utrie_enum(&normTrie, _enumPropertyStartsValue, _enumPropertyStartsRange, - * set);
                  - * In Java :
                  + * a subclass of TrieIterator, override the extract method and iterate, e.g.
                  + * {@code utrie_enum(&normTrie, _enumPropertyStartsValue, _enumPropertyStartsRange, + * set);}
                  + * In Java:
                  *

                    * class TrieIteratorImpl extends TrieIterator{
                    *     public TrieIteratorImpl(Trie data){
                  @@ -90,17 +89,17 @@ package sun.text.normalizer;
                    *     // port the implementation of _enumPropertyStartsRange
                    * }
                    * 
                  - *

                  + * *

                  3) UTrieEnumRange is the only implemented callback then just implement * the while loop, when utrie_enum is called - *

                  + * 
                  {@code
                    * // utrie_enum(&fcdTrie, NULL, _enumPropertyStartsRange, set);
                    * TrieIterator fcdIter  = new TrieIterator(fcdTrieImpl.fcdTrie);
                    * while(fcdIter.next(result)){
                    *     set.add(result.start);
                    * }
                  - * 
                  - *

                  + * }
                  + * * @author synwee * @see com.ibm.icu.impl.Trie * @see com.ibm.icu.lang.UCharacterTypeIterator diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/UCharacter.java b/jdk/src/java.base/share/classes/sun/text/normalizer/UCharacter.java index 2992eed9146..5382d16012d 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/UCharacter.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/UCharacter.java @@ -128,7 +128,7 @@ import java.util.MissingResourceException; * Annex C: Compatibility Properties of UTS #18 Unicode Regular Expressions * (http://www.unicode.org/reports/tr18/#Compatibility_Properties). *

                  - *

                  + *

                  {@code
                    * API access for C/POSIX character classes is as follows:
                    * - alpha:     isUAlphabetic(c) or hasBinaryProperty(c, UProperty.ALPHABETIC)
                    * - lower:     isULowercase(c) or hasBinaryProperty(c, UProperty.LOWERCASE)
                  @@ -142,7 +142,7 @@ import java.util.MissingResourceException;
                    * - cntrl:     getType(c)==CONTROL
                    * - graph:     hasBinaryProperty(c, UProperty.POSIX_GRAPH)
                    * - print:     hasBinaryProperty(c, UProperty.POSIX_PRINT)
                  - * 

                  + * }
                  *

                  * The C/POSIX character classes are also available in UnicodeSet patterns, * using patterns like [:graph:] or \p{graph}. diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/UCharacterIterator.java b/jdk/src/java.base/share/classes/sun/text/normalizer/UCharacterIterator.java index e5059d7b8ee..f8c41831aeb 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/UCharacterIterator.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/UCharacterIterator.java @@ -200,8 +200,7 @@ public abstract class UCharacterIterator * iterator obtained by calling getLength(). * Usage: * - * - *

                  +     * 
                  {@code
                        *         UChacterIterator iter = new UCharacterIterator.getInstance(text);
                        *         char[] buf = new char[iter.getLength()];
                        *         iter.getText(buf);
                  @@ -217,15 +216,14 @@ public abstract class UCharacterIterator
                        *                 buf = new char[iter.getLength()];
                        *             }
                        *         }
                  -     * 
                  - *
                  + * }
                  * * @param fillIn an array of chars to fill with the underlying UTF-16 code * units. * @param offset the position within the array to start putting the data. * @return the number of code units added to fillIn, as a convenience * @exception IndexOutOfBounds exception if there is not enough - * room after offset in the array, or if offset < 0. + * room after offset in the array, or if offset {@literal <} 0. * @stable ICU 2.4 */ public abstract int getText(char[] fillIn, int offset); diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/UTF16.java b/jdk/src/java.base/share/classes/sun/text/normalizer/UTF16.java index 0342a55648c..f705364b1c8 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/UTF16.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/UTF16.java @@ -38,26 +38,26 @@ package sun.text.normalizer; /** *

                  Standalone utility class providing UTF16 character conversions and - * indexing conversions.

                  + * indexing conversions. *

                  Code that uses strings alone rarely need modification. * By design, UTF-16 does not allow overlap, so searching for strings is a safe * operation. Similarly, concatenation is always safe. Substringing is safe if * the start and end are both on UTF-32 boundaries. In normal code, the values * for start and end are on those boundaries, since they arose from operations * like searching. If not, the nearest UTF-32 boundaries can be determined - * using bounds().

                  + * using bounds(). * Examples: *

                  The following examples illustrate use of some of these methods. - *

                  + * 
                  {@code
                    * // iteration forwards: Original
                  - * for (int i = 0; i < s.length(); ++i) {
                  + * for (int i = 0; i < s.length(); ++i) {
                    *     char ch = s.charAt(i);
                    *     doSomethingWith(ch);
                    * }
                    *
                    * // iteration forwards: Changes for UTF-32
                    * int ch;
                  - * for (int i = 0; i < s.length(); i+=UTF16.getCharCount(ch)) {
                  + * for (int i = 0; i < s.length(); i+=UTF16.getCharCount(ch)) {
                    *     ch = UTF16.charAt(s,i);
                    *     doSomethingWith(ch);
                    * }
                  @@ -74,7 +74,7 @@ package sun.text.normalizer;
                    *     ch = UTF16.charAt(s,i);
                    *     doSomethingWith(ch);
                    * }
                  - * 
                  + * }
                  * Notes: *
                    *
                  • @@ -515,12 +515,12 @@ public final class UTF16 /** *

                    Converts argument code point and returns a String object representing - * the code point's value in UTF16 format.

                    + * the code point's value in UTF16 format. *

                    This method does not check for the validity of the codepoint, the * results are not guaranteed if a invalid codepoint is passed as - * argument.

                    + * argument. *

                    The result is a string whose length is 1 for non-supplementary code - * points, 2 otherwise.

                    + * points, 2 otherwise. * @param ch code point * @return string representation of the code point */ diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeMatcher.java b/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeMatcher.java index d1815c21ca7..52808c9860f 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeMatcher.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeMatcher.java @@ -45,7 +45,8 @@ package sun.text.normalizer; public interface UnicodeMatcher { /** - * The character at index i, where i < contextStart || i >= contextLimit, + * The character at index {@code i}, where + * {@code i < contextStart || i >= contextLimit}, * is ETHER. This allows explicit matching by rules and UnicodeSets * of text outside the context. In traditional terms, this allows anchoring * at the start and/or end. diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeSet.java b/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeSet.java index a1784652be8..f3ee71aa969 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeSet.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeSet.java @@ -107,8 +107,8 @@ import java.util.TreeSet; * * * [a{ab}{ac}] - * The character 'a' and the multicharacter strings "ab" and - * "ac" + * The character 'a' and the multicharacter strings "ab" and + * "ac" * * * [\p{Lu}] @@ -148,10 +148,10 @@ import java.util.TreeSet; * literal. Thus "[a\\-b]", "[-ab]", and "[ab-]" all indicate the same * set of three characters, 'a', 'b', and '-'. * - *

                    Sets may be intersected using the '&' operator or the asymmetric + *

                    Sets may be intersected using the {@literal '&'} operator or the asymmetric * set difference may be taken using the '-' operator, for example, - * "[[:L:]&[\\u0000-\\u0FFF]]" indicates the set of all Unicode letters - * with values less than 4096. Operators ('&' and '|') have equal + * "{@code [[:L:]&[\\u0000-\\u0FFF]]}" indicates the set of all Unicode letters + * with values less than 4096. Operators ({@literal '&'} and '|') have equal * precedence and bind left-to-right. Thus * "[[:L:]-[a-z]-[\\u0100-\\u01FF]]" is equivalent to * "[[[:L:]-[a-z]]-[\\u0100-\\u01FF]]". This only really matters for @@ -166,7 +166,7 @@ import java.util.TreeSet; * that is, U+0000 through 'a'-1 and 'z'+1 through U+10FFFF * [[pat1][pat2]] * The union of sets specified by pat1 and pat2 - * [[pat1]&[pat2]] + * [[pat1]&[pat2]] * The intersection of sets specified by pat1 and pat2 * [[pat1]-[pat2]] * The asymmetric difference of sets specified by pat1 and @@ -227,7 +227,7 @@ import java.util.TreeSet; * * * property :=  - * a Unicode property set pattern + * a Unicode property set pattern * * *
                    @@ -337,8 +337,8 @@ public class UnicodeSet implements UnicodeMatcher { } /** - * Constructs a set containing the given range. If end > - * start then an empty set is created. + * Constructs a set containing the given range. + * If {@code end > start} then an empty set is created. * * @param start first character, inclusive, of range * @param end last character, inclusive, of range @@ -651,7 +651,7 @@ public class UnicodeSet implements UnicodeMatcher { * Adds the specified multicharacter to this set if it is not already * present. If this set already contains the multicharacter, * the call leaves this set unchanged. - * Thus "ch" => {"ch"} + * Thus {@code "ch" => {"ch"}} *
                    Warning: you cannot add an empty string ("") to a UnicodeSet. * @param s the source string * @return this object, for chaining @@ -691,7 +691,7 @@ public class UnicodeSet implements UnicodeMatcher { /** * Complements the specified range in this set. Any character in * the range will be removed if it is in this set, or will be - * added if it is not in this set. If end > start + * added if it is not in this set. If {@code end > start} * then an empty range is complemented, leaving the set unchanged. * * @param start first character, inclusive, of range to be removed @@ -1698,8 +1698,8 @@ public class UnicodeSet implements UnicodeMatcher { * Modifies this set to contain those code points which have the * given value for the given property. Prior contents of this * set are lost. - * @param propertyAlias - * @param valueAlias + * @param propertyAlias the property alias + * @param valueAlias the value alias * @param symbols if not null, then symbols are first called to see if a property * is available. If true, then everything else is skipped. * @return this set diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeSetIterator.java b/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeSetIterator.java index 770745226c8..98544705349 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeSetIterator.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/UnicodeSetIterator.java @@ -73,35 +73,35 @@ import java.util.Iterator; public class UnicodeSetIterator { /** - * Value of codepoint if the iterator points to a string. - * If codepoint == IS_STRING, then examine - * string for the current iteration result. + * Value of {@code codepoint} if the iterator points to a string. + * If {@code codepoint == IS_STRING}, then examine + * {@code string} for the current iteration result. * @stable ICU 2.0 */ public static int IS_STRING = -1; /** - * Current code point, or the special value IS_STRING, if + * Current code point, or the special value {@code IS_STRING}, if * the iterator points to a string. * @stable ICU 2.0 */ public int codepoint; /** - * When iterating over ranges using nextRange(), - * codepointEnd contains the inclusive end of the - * iteration range, if codepoint != IS_STRING. If - * iterating over code points using next(), or if - * codepoint == IS_STRING, then the value of - * codepointEnd is undefined. + * When iterating over ranges using {@code nextRange()}, + * {@code codepointEnd} contains the inclusive end of the + * iteration range, if {@code codepoint != IS_STRING}. If + * iterating over code points using {@code next()}, or if + * {@code codepoint == IS_STRING}, then the value of + * {@code codepointEnd} is undefined. * @stable ICU 2.0 */ public int codepointEnd; /** - * If codepoint == IS_STRING, then string points - * to the current string. If codepoint != IS_STRING, the - * value of string is undefined. + * If {@code codepoint == IS_STRING}, then {@code string} points + * to the current string. If {@code codepoint != IS_STRING}, the + * value of {@code string} is undefined. * @stable ICU 2.0 */ public String string; @@ -118,17 +118,17 @@ public class UnicodeSetIterator { /** * Returns the next element in the set, either a code point range * or a string. If there are no more elements in the set, return - * false. If codepoint == IS_STRING, the value is a - * string in the string field. Otherwise the value is a - * range of one or more code points from codepoint to - * codepointeEnd inclusive. + * false. If {@code codepoint == IS_STRING}, the value is a + * string in the {@code string} field. Otherwise the value is a + * range of one or more code points from {@code codepoint} to + * {@code codepointeEnd} inclusive. * *

                    The order of iteration is all code points ranges in sorted * order, followed by all strings sorted order. Ranges are - * disjoint and non-contiguous. string is undefined - * unless codepoint == IS_STRING. Do not mix calls to - * next() and nextRange() without calling - * reset() between them. The results of doing so are + * disjoint and non-contiguous. {@code string} is undefined + * unless {@code codepoint == IS_STRING}. Do not mix calls to + * {@code next()} and {@code nextRange()} without calling + * {@code reset()} between them. The results of doing so are * undefined. * * @return true if there was another element in the set and this @@ -162,8 +162,8 @@ public class UnicodeSetIterator { /** * Sets this iterator to visit the elements of the given set and * resets it to the start of that set. The iterator is valid only - * so long as set is valid. - * @param set the set to iterate over. + * so long as {@code set} is valid. + * @param uset the set to iterate over. * @stable ICU 2.0 */ public void reset(UnicodeSet uset) { diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/Utility.java b/jdk/src/java.base/share/classes/sun/text/normalizer/Utility.java index 841e2119f93..59fb57189c0 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/Utility.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/Utility.java @@ -227,7 +227,7 @@ public final class Utility { /** * Convert a integer to size width hex uppercase digits. - * E.g., hex('a', 4, str) => "0041". + * E.g., {@code hex('a', 4, str) => "0041"}. * Append the output to the given StringBuffer. * If width is too small to fit, nothing will be appended to output. */ @@ -237,7 +237,7 @@ public final class Utility { /** * Convert a integer to size width (minimum) hex uppercase digits. - * E.g., hex('a', 4, str) => "0041". If the integer requires more + * E.g., {@code hex('a', 4, str) => "0041"}. If the integer requires more * than width digits, more will be used. */ public static String hex(int ch, int width) { @@ -334,8 +334,8 @@ public final class Utility { } /** - * Escape unprintable characters using uxxxx notation - * for U+0000 to U+FFFF and Uxxxxxxxx for U+10000 and + * Escape unprintable characters using {@code uxxxx} notation + * for U+0000 to U+FFFF and {@code Uxxxxxxxx} for U+10000 and * above. If the character is printable ASCII, then do nothing * and return FALSE. Otherwise, append the escaped notation and * return TRUE. diff --git a/jdk/src/java.base/share/classes/sun/text/normalizer/VersionInfo.java b/jdk/src/java.base/share/classes/sun/text/normalizer/VersionInfo.java index 09f13b9ceca..d55fe0b996c 100644 --- a/jdk/src/java.base/share/classes/sun/text/normalizer/VersionInfo.java +++ b/jdk/src/java.base/share/classes/sun/text/normalizer/VersionInfo.java @@ -53,7 +53,7 @@ public final class VersionInfo * @param version version String in the format of "major.minor.milli.micro" * or "major.minor.milli" or "major.minor" or "major", * where major, minor, milli, micro are non-negative numbers - * <= 255. If the trailing version numbers are + * {@literal <=} 255. If the trailing version numbers are * not specified they are taken as 0s. E.g. Version "3.1" is * equivalent to "3.1.0.0". * @return an instance of VersionInfo with the argument version. @@ -98,12 +98,12 @@ public final class VersionInfo /** * Returns an instance of VersionInfo with the argument version. - * @param major major version, non-negative number <= 255. - * @param minor minor version, non-negative number <= 255. - * @param milli milli version, non-negative number <= 255. - * @param micro micro version, non-negative number <= 255. + * @param major major version, non-negative number {@literal <=} 255. + * @param minor minor version, non-negative number {@literal <=} 255. + * @param milli milli version, non-negative number {@literal <=} 255. + * @param micro micro version, non-negative number {@literal <=} 255. * @exception throws an IllegalArgumentException when either arguments are - * negative or > 255 + * negative or {@literal >} 255 * @stable ICU 2.6 */ public static VersionInfo getInstance(int major, int minor, int milli, diff --git a/jdk/src/java.management/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java b/jdk/src/java.management/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java index 63ec9cc347d..740732b2f82 100644 --- a/jdk/src/java.management/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java +++ b/jdk/src/java.management/share/classes/com/sun/jmx/mbeanserver/DefaultMXBeanMappingFactory.java @@ -79,44 +79,46 @@ import sun.reflect.misc.ReflectUtil; /** *

                    A converter between Java types and the limited set of classes - * defined by Open MBeans.

                    + * defined by Open MBeans. * - *

                    A Java type is an instance of java.lang.reflect.Type. For our + *

                    A Java type is an instance of java.lang.reflect.Type. For our * purposes, it is either a Class, such as String.class or int.class; - * or a ParameterizedType, such as List or Map. On J2SE 1.4 and earlier, it can only be a Class.

                    + * or a ParameterizedType, such as {@code List} or + * {@code Map}. + * On J2SE 1.4 and earlier, it can only be a Class. * - *

                    Each Type is associated with an DefaultMXBeanMappingFactory. The - * DefaultMXBeanMappingFactory defines an OpenType corresponding to the Type, plus a - * Java class corresponding to the OpenType. For example:

                    + *

                    Each Type is associated with an DefaultMXBeanMappingFactory. The + * DefaultMXBeanMappingFactory defines an + * OpenType corresponding to the Type, plus a + * Java class corresponding to the OpenType. For example: * - *

                    + *   
                    {@code
                      *   Type                     Open class     OpenType
                      *   ----                     ----------     --------
                    - *   Integer                Integer        SimpleType.INTEGER
                    - *   int                            int            SimpleType.INTEGER
                    - *   Integer[]              Integer[]      ArrayType(1, SimpleType.INTEGER)
                    - *   int[]                  Integer[]      ArrayType(SimpleType.INTEGER, true)
                    - *   String[][]             String[][]     ArrayType(2, SimpleType.STRING)
                    - *   List                   String[]       ArrayType(1, SimpleType.STRING)
                    + *   Integer                  Integer        SimpleType.INTEGER
                    + *   int                      int            SimpleType.INTEGER
                    + *   Integer[]                Integer[]      ArrayType(1, SimpleType.INTEGER)
                    + *   int[]                    Integer[]      ArrayType(SimpleType.INTEGER, true)
                    + *   String[][]               String[][]     ArrayType(2, SimpleType.STRING)
                    + *   List             String[]       ArrayType(1, SimpleType.STRING)
                      *   ThreadState (an Enum)    String         SimpleType.STRING
                    - *   Map   TabularData          TabularType(
                    + *   Map   TabularData    TabularType(
                      *                                           CompositeType(
                      *                                             {"key", SimpleType.INTEGER},
                      *                                             {"value",
                      *                                               ArrayType(1,
                      *                                                SimpleType.STRING)}),
                      *                                           indexNames={"key"})
                    - *   
                    + * }
                    * *

                    Apart from simple types, arrays, and collections, Java types are * converted through introspection into CompositeType. The Java type * must have at least one getter (method such as "int getSize()" or * "boolean isBig()"), and we must be able to deduce how to * reconstruct an instance of the Java class from the values of the - * getters using one of various heuristics.

                    + * getters using one of various heuristics. * - * @since 1.6 + * @since 1.6 */ public class DefaultMXBeanMappingFactory extends MXBeanMappingFactory { static abstract class NonNullMXBeanMapping extends MXBeanMapping { @@ -148,8 +150,8 @@ public class DefaultMXBeanMappingFactory extends MXBeanMappingFactory { throws OpenDataException; /** - *

                    True if and only if this MXBeanMapping's toOpenValue and - * fromOpenValue methods are the identity function.

                    + * True if and only if this MXBeanMapping's toOpenValue and + * fromOpenValue methods are the identity function. */ boolean isIdentity() { return false; diff --git a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerCommunicatorAdmin.java b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerCommunicatorAdmin.java index f943bf5ce68..6df86f5931b 100644 --- a/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerCommunicatorAdmin.java +++ b/jdk/src/java.management/share/classes/com/sun/jmx/remote/internal/ServerCommunicatorAdmin.java @@ -57,8 +57,8 @@ public abstract class ServerCommunicatorAdmin { * rspOutgoing to inform that a response is sent out * for the received request. * @return the value of the termination flag: - *
                      true if the connection is already being terminated, - *
                      false otherwise.
                    + * true if the connection is already being terminated, + * false otherwise. */ public boolean reqIncoming() { if (logger.traceOn()) { @@ -80,8 +80,8 @@ public abstract class ServerCommunicatorAdmin { /** * Tells that a response is sent out for a received request. * @return the value of the termination flag: - *
                      true if the connection is already being terminated, - *
                      false otherwise.
                    + * true if the connection is already being terminated, + * false otherwise. */ public boolean rspOutgoing() { if (logger.traceOn()) { diff --git a/jdk/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java b/jdk/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java index bf951df715f..b92ecc847b2 100644 --- a/jdk/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java +++ b/jdk/src/java.management/share/classes/com/sun/jmx/remote/util/EnvHelp.java @@ -55,17 +55,17 @@ import javax.management.remote.JMXConnectorServer; public class EnvHelp { /** - *

                    Name of the attribute that specifies a default class loader + * Name of the attribute that specifies a default class loader * object. - * The value associated with this attribute is a ClassLoader object

                    + * The value associated with this attribute is a ClassLoader object. */ private static final String DEFAULT_CLASS_LOADER = JMXConnectorFactory.DEFAULT_CLASS_LOADER; /** - *

                    Name of the attribute that specifies a default class loader - * ObjectName. - * The value associated with this attribute is an ObjectName object

                    + * Name of the attribute that specifies a default class loader + * ObjectName. + * The value associated with this attribute is an ObjectName object. */ private static final String DEFAULT_CLASS_LOADER_NAME = JMXConnectorServerFactory.DEFAULT_CLASS_LOADER_NAME; @@ -74,7 +74,6 @@ public class EnvHelp { * Get the Connector Server default class loader. *

                    * Returns: - *

                    *

                      *
                    • * The ClassLoader object found in env for @@ -114,6 +113,7 @@ public class EnvHelp { * jmx.remote.default.class.loader.name is specified * but mbs is null. *
                    • + *
                    * @exception InstanceNotFoundException if * jmx.remote.default.class.loader.name is specified * and the ClassLoader MBean is not found in mbs. @@ -172,7 +172,6 @@ public class EnvHelp { * Get the Connector Client default class loader. *

                    * Returns: - *

                    *

                      *
                    • * The ClassLoader object found in env for @@ -232,7 +231,7 @@ public class EnvHelp { /** * Returns the cause field of a {@code Throwable} object. * The cause field can be got only if t has an - * {@link Throwable#getCause()} method (JDK Version >= 1.4) + * {@link Throwable#getCause()} method (JDK Version {@literal >=} 1.4) * @param t {@code Throwable} on which the cause must be set. * @return the cause if getCause() succeeded and the got value is not * null, otherwise return the t. @@ -254,7 +253,7 @@ public class EnvHelp { /** - *

                      Name of the attribute that specifies the size of a notification + * Name of the attribute that specifies the size of a notification * buffer for a connector server. The default value is 1000. */ public static final String BUFFER_SIZE_PROPERTY = @@ -316,10 +315,10 @@ public class EnvHelp { } /** - *

                      Name of the attribute that specifies the maximum number of - * notifications that a client will fetch from its server.. The + * Name of the attribute that specifies the maximum number of + * notifications that a client will fetch from its server. The * value associated with this attribute should be an - * Integer object. The default value is 1000.

                      + * {@code Integer} object. The default value is 1000. */ public static final String MAX_FETCH_NOTIFS = "jmx.remote.x.notification.fetch.max"; @@ -334,10 +333,10 @@ public class EnvHelp { } /** - *

                      Name of the attribute that specifies the timeout for a + * Name of the attribute that specifies the timeout for a * client to fetch notifications from its server. The value * associated with this attribute should be a Long - * object. The default value is 60000 milliseconds.

                      + * object. The default value is 60000 milliseconds. */ public static final String FETCH_TIMEOUT = "jmx.remote.x.notification.fetch.timeout"; @@ -351,11 +350,12 @@ public class EnvHelp { } /** - *

                      Name of the attribute that specifies an object that will check + * Name of the attribute that specifies an object that will check * accesses to add/removeNotificationListener and also attempts to * receive notifications. The value associated with this attribute * should be a NotificationAccessController object. - * The default value is null.

                      + * The default value is null. + *

                      * This field is not public because of its com.sun dependency. */ public static final String NOTIF_ACCESS_CONTROLLER = @@ -630,9 +630,9 @@ public class EnvHelp { } /** - *

                      Name of the attribute that specifies the timeout to keep a + * Name of the attribute that specifies the timeout to keep a * server side connection after answering last client request. - * The default value is 120000 milliseconds.

                      + * The default value is 120000 milliseconds. */ public static final String SERVER_CONNECTION_TIMEOUT = "jmx.remote.x.server.connection.timeout"; @@ -646,9 +646,9 @@ public class EnvHelp { } /** - *

                      Name of the attribute that specifies the period in - * millisecond for a client to check its connection. The default - * value is 60000 milliseconds.

                      + * Name of the attribute that specifies the period in + * millisecond for a client to check its connection. The default + * value is 60000 milliseconds. */ public static final String CLIENT_CONNECTION_CHECK_PERIOD = "jmx.remote.x.client.connection.check.period"; @@ -741,13 +741,13 @@ public class EnvHelp { } /** - *

                      Name of the attribute that specifies whether a connector server + * Name of the attribute that specifies whether a connector server * should not prevent the VM from exiting */ public static final String JMX_SERVER_DAEMON = "jmx.remote.x.daemon"; /** - * Returns true if {@value SERVER_DAEMON} is specified in the {@code env} + * Returns true if {@value JMX_SERVER_DAEMON} is specified in the {@code env} * as a key and its value is a String and it is equal to true ignoring case. * * @param env diff --git a/jdk/src/java.management/share/classes/sun/management/HotspotRuntimeMBean.java b/jdk/src/java.management/share/classes/sun/management/HotspotRuntimeMBean.java index a38a9b230a0..5d99b21fb64 100644 --- a/jdk/src/java.management/share/classes/sun/management/HotspotRuntimeMBean.java +++ b/jdk/src/java.management/share/classes/sun/management/HotspotRuntimeMBean.java @@ -64,7 +64,7 @@ public interface HotspotRuntimeMBean { * Returns a list of internal counters maintained in the Java * virtual machine for the runtime system. * - * @return a List of internal counters maintained in the VM + * @return a {@code List} of internal counters maintained in the VM * for the runtime system. */ public java.util.List getInternalRuntimeCounters(); diff --git a/jdk/src/java.management/share/classes/sun/management/HotspotThreadMBean.java b/jdk/src/java.management/share/classes/sun/management/HotspotThreadMBean.java index 4af0546b375..e69e2377086 100644 --- a/jdk/src/java.management/share/classes/sun/management/HotspotThreadMBean.java +++ b/jdk/src/java.management/share/classes/sun/management/HotspotThreadMBean.java @@ -40,12 +40,11 @@ public interface HotspotThreadMBean { public int getInternalThreadCount(); /** - * Returns a Map of the name of all VM internal threads + * Returns a {@code Map} of the name of all VM internal threads * to the thread CPU time in nanoseconds. The returned value is * of nanoseconds precision but not necessarily nanoseconds accuracy. - *

                      * - * @return a Map object of the name of all VM internal threads + * @return a {@code Map} object of the name of all VM internal threads * to the thread CPU time in nanoseconds. * * @throws java.lang.UnsupportedOperationException if the Java virtual diff --git a/jdk/src/java.management/share/classes/sun/management/MappedMXBeanType.java b/jdk/src/java.management/share/classes/sun/management/MappedMXBeanType.java index 85cdfdf1833..2de0e00758b 100644 --- a/jdk/src/java.management/share/classes/sun/management/MappedMXBeanType.java +++ b/jdk/src/java.management/share/classes/sun/management/MappedMXBeanType.java @@ -45,13 +45,15 @@ import static javax.management.openmbean.SimpleType.*; * A mapped mxbean type maps a Java type to an open type. * Only the following Java types are mappable * (currently required by the platform MXBeans): - * 1. Primitive types - * 2. Wrapper classes such java.lang.Integer, etc - * 3. Classes with only getter methods and with a static "from" method - * that takes a CompositeData argument. - * 4. E[] where E is a type of 1-4 (can be multi-dimensional array) - * 5. List where E is a type of 1-3 - * 6. Map where K and V are a type of 1-4 + *

                        + *
                      1. Primitive types
                      2. + *
                      3. Wrapper classes such java.lang.Integer, etc
                      4. + *
                      5. Classes with only getter methods and with a static "from" method + * that takes a CompositeData argument.
                      6. + *
                      7. {@code E[]} where {@code E} is a type of 1-4 (can be multi-dimensional array)
                      8. + *
                      9. {@code List} where E is a type of 1-3
                      10. + *
                      11. {@code Map} where {@code K} and {@code V} are a type of 1-4
                      12. + *
                      * * OpenDataException will be thrown if a Java type is not supported. */ diff --git a/jdk/src/java.management/share/classes/sun/management/Sensor.java b/jdk/src/java.management/share/classes/sun/management/Sensor.java index 44ff29ad1c6..8b82b859d25 100644 --- a/jdk/src/java.management/share/classes/sun/management/Sensor.java +++ b/jdk/src/java.management/share/classes/sun/management/Sensor.java @@ -34,12 +34,12 @@ import java.util.HashMap; * An abstract sensor. * *

                      - * A AbstractSensor object consists of two attributes: + * A {@code AbstractSensor} object consists of two attributes: *

                        - *
                      • on is a boolean flag indicating if a sensor is + *
                      • {@code on} is a boolean flag indicating if a sensor is * triggered. This flag will be set or cleared by the * component that owns the sensor.
                      • - *
                      • count is the total number of times that a sensor + *
                      • {@code count} is the total number of times that a sensor * has been triggered.
                      • *
                      * @@ -54,7 +54,7 @@ public abstract class Sensor { private boolean on; /** - * Constructs a Sensor object. + * Constructs a {@code Sensor} object. * * @param name The name of this sensor. */ @@ -88,8 +88,8 @@ public abstract class Sensor { /** * Tests if this sensor is currently on. * - * @return true if the sensor is currently on; - * false otherwise. + * @return {@code true} if the sensor is currently on; + * {@code false} otherwise. * */ public boolean isOn() { @@ -112,7 +112,7 @@ public abstract class Sensor { /** * Triggers this sensor. This method sets this sensor on - * and increments the count with the input increment. + * and increments the count with the input {@code increment}. */ public void trigger(int increment) { synchronized (lock) { @@ -126,7 +126,7 @@ public abstract class Sensor { /** * Triggers this sensor piggybacking a memory usage object. * This method sets this sensor on - * and increments the count with the input increment. + * and increments the count with the input {@code increment}. */ public void trigger(int increment, MemoryUsage usage) { synchronized (lock) { @@ -150,7 +150,7 @@ public abstract class Sensor { /** * Clears this sensor - * and increments the count with the input increment. + * and increments the count with the input {@code increment}. */ public void clear(int increment) { synchronized (lock) { diff --git a/jdk/src/java.management/share/classes/sun/management/counter/Counter.java b/jdk/src/java.management/share/classes/sun/management/counter/Counter.java index 00d9d35f7f2..01ac36b3e70 100644 --- a/jdk/src/java.management/share/classes/sun/management/counter/Counter.java +++ b/jdk/src/java.management/share/classes/sun/management/counter/Counter.java @@ -63,7 +63,7 @@ public interface Counter extends java.io.Serializable { public Object getValue(); /** - * Returns true if this counter is an internal counter. + * Returns {@code true} if this counter is an internal counter. */ public boolean isInternal(); diff --git a/jdk/src/java.management/share/classes/sun/management/counter/perf/InstrumentationException.java b/jdk/src/java.management/share/classes/sun/management/counter/perf/InstrumentationException.java index 80685a1fdc1..e5c3e1f9930 100644 --- a/jdk/src/java.management/share/classes/sun/management/counter/perf/InstrumentationException.java +++ b/jdk/src/java.management/share/classes/sun/management/counter/perf/InstrumentationException.java @@ -27,14 +27,14 @@ package sun.management.counter.perf; public class InstrumentationException extends RuntimeException { /** - * Constructs a InstrumentationException with no + * Constructs a {@code InstrumentationException} with no * detail message. */ public InstrumentationException() { } /** - * Constructs a InstrumentationException with a specified + * Constructs a {@code InstrumentationException} with a specified * detail message. * * @param message the detail message diff --git a/jdk/src/java.management/share/classes/sun/management/jdp/JdpController.java b/jdk/src/java.management/share/classes/sun/management/jdp/JdpController.java index a90705d577a..344d2db2b9e 100644 --- a/jdk/src/java.management/share/classes/sun/management/jdp/JdpController.java +++ b/jdk/src/java.management/share/classes/sun/management/jdp/JdpController.java @@ -37,19 +37,18 @@ import sun.management.VMManagement; import sun.misc.ManagedLocalsThread; /** - * JdpController is responsible to create and manage a broadcast loop + * JdpController is responsible to create and manage a broadcast loop. * *

                      Other part of code has no access to broadcast loop and have to use * provided static methods * {@link #startDiscoveryService(InetAddress,int,String,String) startDiscoveryService} - * and {@link #stopDiscoveryService() stopDiscoveryService}

                      + * and {@link #stopDiscoveryService() stopDiscoveryService} *

                      {@link #startDiscoveryService(InetAddress,int,String,String) startDiscoveryService} could be called multiple - * times as it stops the running service if it is necessary. Call to {@link #stopDiscoveryService() stopDiscoveryService} - * ignored if service isn't run

                      + * times as it stops the running service if it is necessary. + * Call to {@link #stopDiscoveryService() stopDiscoveryService} + * ignored if service isn't run. * * - *

                      - * *

                      System properties below could be used to control broadcast loop behavior. * Property below have to be set explicitly in command line. It's not possible to * set it in management.config file. Careless changes of these properties could @@ -59,9 +58,9 @@ import sun.misc.ManagedLocalsThread; *

                    • com.sun.management.jdp.pause - set broadcast interval in seconds
                    • *
                    • com.sun.management.jdp.source_addr - an address of interface to use for broadcast
                    • *
                    -

                    + * *

                    null parameters values are filtered out on {@link JdpPacketWriter} level and - * corresponding keys are not placed to packet.

                    + * corresponding keys are not placed to packet. */ public final class JdpController { diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/BasicControl.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/BasicControl.java index a7599d2f368..ba2a5543f6c 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/BasicControl.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/BasicControl.java @@ -28,7 +28,7 @@ package com.sun.jndi.ldap; import javax.naming.ldap.*; /** - * This class provides a basic implementation of the Control + * This class provides a basic implementation of the {@code Control} * interface. It represents an LDAPv3 Control as defined in RFC-2251. * * @author Vincent Ryan diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/BerDecoder.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/BerDecoder.java index 9feefb47feb..ef03ca4d587 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/BerDecoder.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/BerDecoder.java @@ -295,7 +295,7 @@ public final class BerDecoder extends Ber { * the relative parsed position is not returned. * @return A non-null array containing the octet string. * @throws DecodeException If the next byte in the BER buffer is not - * tag, or if length specified in the BER buffer exceeds the + * {@code tag}, or if length specified in the BER buffer exceeds the * number of bytes left in the buffer. */ public byte[] parseOctetString(int tag, int rlen[]) throws DecodeException { diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/EventQueue.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/EventQueue.java index 85bc38076f5..3df7dc6063c 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/EventQueue.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/EventQueue.java @@ -73,16 +73,16 @@ final class EventQueue implements Runnable { // package private; /** * Enqueue an event. - * @param event Either a NamingExceptionEvent or a subclass - * of NamingEvent or - * UnsolicitedNotificationEvent. - * If it is a subclass of NamingEvent, all listeners must implement - * the corresponding subinterface of NamingListener. - * For example, for a ObjectAddedEvent, all listeners must - * implement the ObjectAddedListener interface. + * @param event Either a {@code NamingExceptionEvent} or a subclass + * of {@code NamingEvent} or + * {@code UnsolicitedNotificationEvent}. + * If it is a subclass of {@code NamingEvent}, all listeners must implement + * the corresponding subinterface of {@code NamingListener}. + * For example, for a {@code ObjectAddedEvent}, all listeners must + * implement the {@code ObjectAddedListener} interface. * The current implementation does not check this before dispatching * the event. - * If the event is a NamingExceptionEvent, then all listeners + * If the event is a {@code NamingExceptionEvent}, then all listeners * are notified. * @param vector List of NamingListeners that will be notified of event. */ diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/EventSupport.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/EventSupport.java index 5edf4eaadd6..de78c1f11ab 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/EventSupport.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/EventSupport.java @@ -55,14 +55,14 @@ import javax.naming.ldap.UnsolicitedNotification; *
                  • The filter (default is "(objectclass=*)"). *
                  • The search controls (default is null SearchControls). *
                  • The events that the listener is interested in. This is determined by - * finding out which NamingListener interface the listener supports. + * finding out which {@code NamingListener} interface the listener supports. *
                  *

                  - *A notifier (NamingEventNotifier) is a worker thread that is responsible + *A notifier ({@code NamingEventNotifier}) is a worker thread that is responsible *for gathering information for generating events requested by its listeners. *Each notifier maintains its own list of listeners; these listeners have *all made the same registration request (at different times) and implements - *the same NamingListener interfaces. + *the same {@code NamingListener} interfaces. *

                  *For unsolicited listeners, this class maintains a vector, unsolicited. *When an unsolicited listener is registered, this class adds itself @@ -93,7 +93,7 @@ import javax.naming.ldap.UnsolicitedNotification; *The notifiers are responsible for gather information for generating events *requested by their respective listeners. When a notifier gets sufficient *information to generate an event, it creates invokes the - *appropriate fireXXXEvent on this class with the information and list of + *appropriate {@code fireXXXEvent} on this class with the information and list of *listeners. This causes an event and the list of listeners to be added *to the event queue. *This class maintains an event queue and a dispatching thread that dequeues @@ -138,7 +138,7 @@ final class EventSupport { } /** - * Adds l to list of listeners interested in nm. + * Adds {@code l} to list of listeners interested in {@code nm}. */ /* * Make the add/removeNamingListeners synchronized to: @@ -173,7 +173,7 @@ final class EventSupport { } /** - * Adds l to list of listeners interested in nm + * Adds {@code l} to list of listeners interested in {@code nm} * and filter. */ synchronized void addNamingListener(String nm, String filter, @@ -201,7 +201,7 @@ final class EventSupport { } /** - * Removes l from all notifiers in this context. + * Removes {@code l} from all notifiers in this context. */ synchronized void removeNamingListener(NamingListener l) { if (debug) System.err.println("EventSupport removing listener"); diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapName.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapName.java index b3f76d9ab0b..896ffd280d7 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapName.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapName.java @@ -336,7 +336,7 @@ public final class LdapName implements Name { * characters: *

                    *
                  • leading and trailing whitespace - *
                  • , = + < > # ; " \
                    + *
                  • {@literal , = + < > # ; " \}
                    *
                  * If the value is a byte array, it is converted to hex * notation (such as "#CEB1DF80"). diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapReferralException.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapReferralException.java index 5adffa441d9..4b3e06d9285 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapReferralException.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/LdapReferralException.java @@ -35,7 +35,7 @@ import java.util.Vector; * This exception is raised when a referral to an alternative context * is encountered. *

                  - * An LdapReferralException object contains one or more referrals. + * An {@code LdapReferralException} object contains one or more referrals. * Each referral is an alternative location for the same target entry. * For example, a referral may be an LDAP URL. * The referrals are attempted in sequence until one is successful or @@ -46,20 +46,20 @@ import java.util.Vector; * of an authentication error, a referral may be retried with different * environment properties. *

                  - * An LdapReferralException object may also contain a reference - * to a chain of unprocessed LdapReferralException objects. + * An {@code LdapReferralException} object may also contain a reference + * to a chain of unprocessed {@code LdapReferralException} objects. * Once the current set of referrals have been exhausted and unprocessed - * LdapReferralException objects remain, then the - * LdapReferralException object referenced by the current + * {@code LdapReferralException} objects remain, then the + * {@code LdapReferralException} object referenced by the current * object is thrown and the cycle continues. *

                  - * If new LdapReferralException objects are generated while + * If new {@code LdapReferralException} objects are generated while * following an existing referral then these new objects are appended - * to the end of the chain of unprocessed LdapReferralException + * to the end of the chain of unprocessed {@code LdapReferralException} * objects. *

                  * If an exception was recorded while processing a chain of - * LdapReferralException objects then it is throw once + * {@code LdapReferralException} objects then it is throw once * processing has completed. * * @author Vincent Ryan diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/UnsolicitedResponseImpl.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/UnsolicitedResponseImpl.java index cb03114593d..500ff35a52a 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/UnsolicitedResponseImpl.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/UnsolicitedResponseImpl.java @@ -65,7 +65,7 @@ final class UnsolicitedResponseImpl implements UnsolicitedNotification { * Retrieves the object identifier of the response. * * @return A possibly null object identifier string representing the LDAP - * ExtendedResponse.responseName component. + * {@code ExtendedResponse.responseName} component. */ public String getID() { return oid; @@ -79,7 +79,7 @@ final class UnsolicitedResponseImpl implements UnsolicitedNotification { * the response value. It does not include the response OID. * * @return A possibly null byte array representing the ASN.1 BER encoded - * contents of the LDAP ExtendedResponse.response + * contents of the LDAP {@code ExtendedResponse.response} * component. */ public byte[] getEncodedValue() { diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/ext/StartTlsResponseImpl.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/ext/StartTlsResponseImpl.java index 53d197c5e62..c7f73337cc8 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/ext/StartTlsResponseImpl.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/ext/StartTlsResponseImpl.java @@ -52,10 +52,10 @@ import com.sun.jndi.ldap.Connection; * The object identifier for StartTLS is 1.3.6.1.4.1.1466.20037 * and no extended response value is defined. * - *

                  + *

                  * The Start TLS extended request and response are used to establish * a TLS connection over the existing LDAP connection associated with - * the JNDI context on which extendedOperation() is invoked. + * the JNDI context on which {@code extendedOperation()} is invoked. * * @see StartTlsRequest * @author Vincent Ryan @@ -124,7 +124,7 @@ final public class StartTlsResponseImpl extends StartTlsResponse { /** * Overrides the default list of cipher suites enabled for use on the * TLS connection. The cipher suites must have already been listed by - * SSLSocketFactory.getSupportedCipherSuites() as being supported. + * {@code SSLSocketFactory.getSupportedCipherSuites()} as being supported. * Even if a suite has been enabled, it still might not be used because * the peer does not support it, or because the requisite certificates * (and private keys) are not available. @@ -140,12 +140,12 @@ final public class StartTlsResponseImpl extends StartTlsResponse { } /** - * Overrides the default hostname verifier used by negotiate() + * Overrides the default hostname verifier used by {@code negotiate()} * after the TLS handshake has completed. If - * setHostnameVerifier() has not been called before - * negotiate() is invoked, negotiate() + * {@code setHostnameVerifier()} has not been called before + * {@code negotiate()} is invoked, {@code negotiate()} * will perform a simple case ignore match. If called after - * negotiate(), this method does not do anything. + * {@code negotiate()}, this method does not do anything. * * @param verifier The non-null hostname verifier callback. * @see #negotiate @@ -157,10 +157,10 @@ final public class StartTlsResponseImpl extends StartTlsResponse { /** * Negotiates a TLS session using the default SSL socket factory. *

                  - * This method is equivalent to negotiate(null). + * This method is equivalent to {@code negotiate(null)}. * * @return The negotiated SSL session - * @throw IOException If an IO error was encountered while establishing + * @throws IOException If an IO error was encountered while establishing * the TLS session. * @see #setEnabledCipherSuites * @see #setHostnameVerifier @@ -177,7 +177,7 @@ final public class StartTlsResponseImpl extends StartTlsResponse { * attaches it to the existing connection. Performs the TLS handshake * and returns the negotiated session information. *

                  - * If cipher suites have been set via setEnabledCipherSuites + * If cipher suites have been set via {@code setEnabledCipherSuites} * then they are enabled before the TLS handshake begins. *

                  * Hostname verification is performed after the TLS handshake completes. @@ -186,7 +186,7 @@ final public class StartTlsResponseImpl extends StartTlsResponse { * hostname is extracted from the subjectAltName in the server's * certificate (if present). Otherwise the value of the common name * attribute of the subject name is used. If a callback has - * been set via setHostnameVerifier then that verifier is used if + * been set via {@code setHostnameVerifier} then that verifier is used if * the default check fails. *

                  * If an error occurs then the SSL socket is closed and an IOException @@ -195,7 +195,7 @@ final public class StartTlsResponseImpl extends StartTlsResponse { * @param factory The possibly null SSL socket factory to use. * If null, the default SSL socket factory is used. * @return The negotiated SSL session - * @throw IOException If an IO error was encountered while establishing + * @throws IOException If an IO error was encountered while establishing * the TLS session. * @see #setEnabledCipherSuites * @see #setHostnameVerifier @@ -252,7 +252,7 @@ final public class StartTlsResponseImpl extends StartTlsResponse { * Closes the TLS connection gracefully and reverts back to the underlying * connection. * - * @throw IOException If an IO error was encountered while closing the + * @throws IOException If an IO error was encountered while closing the * TLS connection */ public void close() throws IOException { diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/LdapSasl.java b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/LdapSasl.java index ef527370e62..ee85dd7bf66 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/LdapSasl.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/ldap/sasl/LdapSasl.java @@ -72,12 +72,12 @@ final public class LdapSasl { * property has not been set, Context.SECURITY_PRINCIPAL is used. * If SASL_CALLBACK has been set, use that instead of the default * CallbackHandler. - *

                  + *

                  * If bind is successful and the selected SASL mechanism has a security * layer, set inStream and outStream to be filter streams that use * the security layer. These will be used for subsequent communication * with the server. - *

                  + * * @param conn The non-null connection to use for sending an LDAP BIND * @param server Non-null string name of host to connect to * @param dn Non-null DN to bind as; also used as authentication ID diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/Continuation.java b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/Continuation.java index 44bc245bad4..595f9303e72 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/Continuation.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/Continuation.java @@ -329,7 +329,7 @@ public class Continuation extends ResolveResult { *

                  * After this method is called, isContinuing() returns true. * - * @param resObj The possibly null resolved object. + * @param obj The possibly null resolved object. * @param relResName The non-null resolved name relative to currCtx. * @param currCtx The non-null context from which relResName is to be resolved. */ @@ -349,7 +349,7 @@ public class Continuation extends ResolveResult { *

                  * After this method is called, isContinuing() returns true. * - * @param resObj The possibly null resolved object. + * @param obj The possibly null resolved object. * @param relResName The non-null resolved name relative to currCtx. * @param currCtx The non-null context from which relResName is to be resolved. * @param remain The non-null remaining name. @@ -366,7 +366,7 @@ public class Continuation extends ResolveResult { /** * String overload. * - * @param resObj The possibly null resolved object. + * @param obj The possibly null resolved object. * @param relResName The non-null resolved name relative to currCtx. * @param currCtx The non-null context from which relResName is to be resolved. * @param remain The non-null remaining name. diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java index 891a8621b29..e2d9d4ae2ad 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/ctx/PartialCompositeContext.java @@ -452,14 +452,14 @@ public abstract class PartialCompositeContext implements Context, Resolver { * nonempty component, and if 'prefix' ends with an empty component or * 'name' starts with one, then one empty component is dropped. * For example: - *

                  +     * 
                  {@code
                        *                            elideEmpty=false     elideEmpty=true
                        * {"a"} + {"b"}          =>  {"a", "b"}           {"a", "b"}
                        * {"a"} + {""}           =>  {"a", ""}            {"a", ""}
                        * {"a"} + {"", "b"}      =>  {"a", "", "b"}       {"a", "b"}
                        * {"a", ""} + {"b", ""}  =>  {"a", "", "b", ""}   {"a", "b", ""}
                        * {"a", ""} + {"", "b"}  =>  {"a", "", "", "b"}   {"a", "", "b"}
                  -     * 
                  + * }
                  */ public Name composeName(Name name, Name prefix) throws NamingException { Name res = (Name)prefix.clone(); diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/dir/HierMemDirCtx.java b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/dir/HierMemDirCtx.java index 35895db2395..e4059bfc688 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/dir/HierMemDirCtx.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/dir/HierMemDirCtx.java @@ -32,8 +32,8 @@ import java.util.*; /** * A sample service provider that implements a hierarchical directory in memory. * Every operation begins by doing a lookup on the name passed to it and then - * calls a corresponding "do" on the result of the lookup. The - * "do" does the work without any further resolution (it assumes + * calls a corresponding "{@code do}" on the result of the lookup. The + * "{@code do}" does the work without any further resolution (it assumes * that it is the target context). */ diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java index 695238309f3..bc56d4a6174 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/dir/SearchFilter.java @@ -548,8 +548,8 @@ public class SearchFilter implements AttrFilter { /** - * Finds the first occurrence of ch in val starting - * from position start. It doesn't count if ch + * Finds the first occurrence of {@code ch} in {@code val} starting + * from position {@code start}. It doesn't count if {@code ch} * has been escaped by a backslash (\) */ public static int findUnescaped(char ch, String val, int start) { @@ -568,8 +568,8 @@ public class SearchFilter implements AttrFilter { } /** - * Formats the expression expr using arguments from the array - * args. + * Formats the expression {@code expr} using arguments from the array + * {@code args}. * * {i} specifies the i'th element from * the array args is to be substituted for the diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/url/GenericURLContext.java b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/url/GenericURLContext.java index 8493330135b..3fbd5eb9782 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/url/GenericURLContext.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/url/GenericURLContext.java @@ -107,12 +107,14 @@ abstract public class GenericURLContext implements Context { * the subclass must override getURLSuffix() to get the correct behavior. * Remember, the behavior must match getRootURLContext(). * + *
                  {@code
                         * URL                                     Suffix
                         * foo://host:port                         
                         * foo://host:port/rest/of/name            rest/of/name
                         * foo:///rest/of/name                     rest/of/name
                         * foo:/rest/of/name                       rest/of/name
                         * foo:rest/of/name                        rest/of/name
                  +      * }
                  */ protected Name getURLSuffix(String prefix, String url) throws NamingException { String suffix = url.substring(prefix.length()); diff --git a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/url/Uri.java b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/url/Uri.java index da5771ae318..aaeb0eab6c7 100644 --- a/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/url/Uri.java +++ b/jdk/src/java.naming/share/classes/com/sun/jndi/toolkit/url/Uri.java @@ -47,7 +47,7 @@ import java.net.MalformedURLException; * still run on pre-1.4 platforms not containing that class. * *

                  The format of an absolute URI (see the RFCs mentioned above) is: - *

                  + * 
                  {@code
                    *      absoluteURI   = scheme ":" ( hier_part | opaque_part )
                    *
                    *      scheme        = alpha *( alpha | digit | "+" | "-" | "." )
                  @@ -94,12 +94,12 @@ import java.net.MalformedURLException;
                    *      mark          = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")"
                    *      escaped       = "%" hex hex
                    *      unwise        = "{" | "}" | "|" | "\" | "^" | "`"
                  - * 
                  + * }
                  * - *

                  Currently URIs containing userinfo or reg_name + *

                  Currently URIs containing {@code userinfo} or {@code reg_name} * are not supported. - * The opaque_part of a non-hierarchical URI is treated as if - * if were a path without a leading slash. + * The {@code opaque_part} of a non-hierarchical URI is treated as if + * if were a {@code path} without a leading slash. */ diff --git a/jdk/src/java.rmi/share/classes/com/sun/rmi/rmid/ExecOptionPermission.java b/jdk/src/java.rmi/share/classes/com/sun/rmi/rmid/ExecOptionPermission.java index 28119ef169f..587915877e4 100644 --- a/jdk/src/java.rmi/share/classes/com/sun/rmi/rmid/ExecOptionPermission.java +++ b/jdk/src/java.rmi/share/classes/com/sun/rmi/rmid/ExecOptionPermission.java @@ -32,7 +32,6 @@ import java.util.*; /** * The ExecOptionPermission class represents permission for rmid to use * a specific command-line option when launching an activation group. - *

                  * * @author Ann Wollrath * @@ -68,9 +67,9 @@ public final class ExecOptionPermission extends Permission * Checks if the specified permission is "implied" by * this object. *

                  - * More specifically, this method returns true if:

                  + * More specifically, this method returns true if: *

                    - *
                  • p's class is the same as this object's class, and

                    + *

                  • p's class is the same as this object's class, and *
                  • p's name equals or (in the case of wildcards) * is implied by this object's * name. For example, "a.b.*" implies "a.b.c", and @@ -111,7 +110,7 @@ public final class ExecOptionPermission extends Permission * Checks two ExecOptionPermission objects for equality. * Checks that obj's class is the same as this object's class * and has the same name as this object. - *

                    + * * @param obj the object we are testing for equality with this object. * @return true if obj is an ExecOptionPermission, and has the same * name as this ExecOptionPermission object, false otherwise. @@ -154,7 +153,7 @@ public final class ExecOptionPermission extends Permission * Returns a new PermissionCollection object for storing * ExecOptionPermission objects. *

                    - * A ExecOptionPermissionCollection stores a collection of + * An ExecOptionPermissionCollection stores a collection of * ExecOptionPermission permissions. * *

                    ExecOptionPermission objects must be stored in a manner that allows diff --git a/jdk/src/java.rmi/share/classes/com/sun/rmi/rmid/ExecPermission.java b/jdk/src/java.rmi/share/classes/com/sun/rmi/rmid/ExecPermission.java index 3c119e80c10..e445542f9a8 100644 --- a/jdk/src/java.rmi/share/classes/com/sun/rmi/rmid/ExecPermission.java +++ b/jdk/src/java.rmi/share/classes/com/sun/rmi/rmid/ExecPermission.java @@ -40,14 +40,13 @@ import java.util.*; * all the files and directories contained in that directory. A pathname * that ends with "/-" indicates (recursively) all files * and subdirectories contained in that directory. A pathname consisting of - * the special token "<<ALL FILES>>" matches any file. + * the special token "{@code <>}" matches any file. *

                    * Note: A pathname consisting of a single "*" indicates all the files * in the current directory, while a pathname consisting of a single "-" * indicates all the files in the current directory and * (recursively) all files and subdirectories contained in the current * directory. - *

                    * * * @author Ann Wollrath @@ -72,7 +71,7 @@ public final class ExecPermission extends Permission * a directory and all the files contained in that directory. A pathname * that ends with "/-" indicates a directory and (recursively) all files * and subdirectories contained in that directory. The special pathname - * "<<ALL FILES>>" matches all files. + * "{@code <>}" matches all files. * *

                    A pathname consisting of a single "*" indicates all the files * in the current directory, while a pathname consisting of a single "-" @@ -96,7 +95,7 @@ public final class ExecPermission extends Permission * a directory and all the files contained in that directory. A pathname * that ends with "/-" indicates a directory and (recursively) all files * and subdirectories contained in that directory. The special pathname - * "<<ALL FILES>>" matches all files. + * "{@code <>}" matches all files. * *

                    A pathname consisting of a single "*" indicates all the files * in the current directory, while a pathname consisting of a single "-" @@ -114,9 +113,9 @@ public final class ExecPermission extends Permission /** * Checks if this ExecPermission object "implies" the specified permission. *

                    - * More specifically, this method returns true if:

                    + * More specifically, this method returns true if: *

                      - *
                    • p is an instanceof ExecPermission,

                      and + *

                    • p is an instanceof ExecPermission, and *
                    • p's pathname is implied by this object's * pathname. For example, "/tmp/*" implies "/tmp/foo", since * "/tmp/*" encompasses the "/tmp" directory and all files in that @@ -140,7 +139,7 @@ public final class ExecPermission extends Permission * Checks two ExecPermission objects for equality. * Checks that obj's class is the same as this object's class * and has the same name as this object. - *

                      + * * @param obj the object we are testing for equality with this object. * @return true if obj is an ExecPermission, and has the same * pathname as this ExecPermission object, false otherwise. diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/log/LogInputStream.java b/jdk/src/java.rmi/share/classes/sun/rmi/log/LogInputStream.java index e0bf5c8767a..319e9741155 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/log/LogInputStream.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/log/LogInputStream.java @@ -35,7 +35,7 @@ class LogInputStream extends InputStream { /** * Creates a log input file with the specified system dependent * file descriptor. - * @param fd the system dependent file descriptor + * @param in the system dependent file descriptor * @param length the total number of bytes allowed to be read * @exception IOException If an I/O error has occurred. */ diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/log/LogOutputStream.java b/jdk/src/java.rmi/share/classes/sun/rmi/log/LogOutputStream.java index 7d8ebdc6515..15cea2b1c9b 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/log/LogOutputStream.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/log/LogOutputStream.java @@ -35,7 +35,7 @@ class LogOutputStream extends OutputStream { /** * Creates an output file with the specified system dependent * file descriptor. - * @param fd the system dependent file descriptor + * @param raf the system dependent file descriptor. * @exception IOException If an I/O error has occurred. */ public LogOutputStream(RandomAccessFile raf) throws IOException { diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java b/jdk/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java index 3c097c4c44a..9e9372eb9d3 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/log/ReliableLog.java @@ -124,7 +124,7 @@ public class ReliableLog { * stable storage directory. * * @param dirPath path to the stable storage directory - * @param logCl the closure object containing callbacks for logging and + * @param handler the closure object containing callbacks for logging and * recovery * @param pad ignored * @exception IOException If a directory creation error has @@ -170,8 +170,8 @@ public class ReliableLog { * stable storage directory. * * @param dirPath path to the stable storage directory - * @param logCl the closure object containing callbacks for logging and - * recovery + * @param handler the closure object containing callbacks for logging and + * recovery * @exception IOException If a directory creation error has * occurred or if initialSnapshot callback raises an exception */ diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java b/jdk/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java index 7fd4d5b55ad..9db17967a18 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/registry/RegistryImpl.java @@ -155,7 +155,7 @@ public class RegistryImpl extends java.rmi.server.RemoteServer /** * Returns the remote object for specified name in the registry. * @exception RemoteException If remote operation failed. - * @exception NotBound If name is not currently bound. + * @exception NotBoundException If name is not currently bound. */ public Remote lookup(String name) throws RemoteException, NotBoundException @@ -188,7 +188,7 @@ public class RegistryImpl extends java.rmi.server.RemoteServer /** * Unbind the name. * @exception RemoteException If remote operation failed. - * @exception NotBound If name is not currently bound. + * @exception NotBoundException If name is not currently bound. */ public void unbind(String name) throws RemoteException, NotBoundException, AccessException diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/runtime/Log.java b/jdk/src/java.rmi/share/classes/sun/rmi/runtime/Log.java index 9a152b69e2c..9ba58a55539 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/runtime/Log.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/runtime/Log.java @@ -96,7 +96,7 @@ public abstract class Log { * care to interpret a range of values between BRIEF, VERBOSE and * SILENT. * - * An override < 0 is interpreted to mean that the logging + * An override {@literal <} 0 is interpreted to mean that the logging * configuration should not be overridden. The level passed to the * factories createLog method will be null in this case. * diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/server/ActivationGroupImpl.java b/jdk/src/java.rmi/share/classes/sun/rmi/server/ActivationGroupImpl.java index 118de821e3b..110bb11941c 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/server/ActivationGroupImpl.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/server/ActivationGroupImpl.java @@ -345,7 +345,7 @@ public class ActivationGroupImpl extends ActivationGroup { * request. * * @param id the object's activation identifier - * @returns true if the operation succeeds (the operation will + * @return true if the operation succeeds (the operation will * succeed if the object in currently known to be active and is * either already unexported or is currently exported and has no * pending/executing calls); false is returned if the object has @@ -430,7 +430,7 @@ public class ActivationGroupImpl extends ActivationGroup { * hasn't already done so. * * @param id the object's identifier - * @param obj the remote object implementation + * @param impl the remote object implementation * @exception UnknownObjectException if object is not registered * @exception RemoteException if call informing monitor fails */ diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/server/ActivationGroupInit.java b/jdk/src/java.rmi/share/classes/sun/rmi/server/ActivationGroupInit.java index 3e1d9672153..2947069fda3 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/server/ActivationGroupInit.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/server/ActivationGroupInit.java @@ -36,7 +36,7 @@ import java.rmi.activation.ActivationGroup; * The activator spawns (as a child process) an activation group as needed * and directs activation requests to the appropriate activation * group. After spawning the VM, the activator passes some - * information to the bootstrap code via its stdin:

                      + * information to the bootstrap code via its stdin: *

                        *
                      • the activation group's id, *
                      • the activation group's descriptor (an instance of the class diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/transport/Channel.java b/jdk/src/java.rmi/share/classes/sun/rmi/transport/Channel.java index f34cd7c0507..09701886e6b 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/transport/Channel.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/transport/Channel.java @@ -42,7 +42,7 @@ public interface Channel { /** * Free the connection generated by this channel. - * @param c The connection + * @param conn The connection. * @param reuse If true, the connection is in a state in which it * can be reused for another method call. */ diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/transport/LiveRef.java b/jdk/src/java.rmi/share/classes/sun/rmi/transport/LiveRef.java index e6c4fdd891a..7b1da512a13 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/transport/LiveRef.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/transport/LiveRef.java @@ -56,7 +56,7 @@ public class LiveRef implements Cloneable { /** * Construct a "well-known" live reference to a remote object - * @param isLocalServer If true, indicates this ref specifies a local + * @param isLocal If true, indicates this ref specifies a local * server in this address space; if false, the ref is for a remote * object (hence a surrogate or proxy) in another address space. */ diff --git a/jdk/src/java.rmi/share/classes/sun/rmi/transport/proxy/CGIHandler.java b/jdk/src/java.rmi/share/classes/sun/rmi/transport/proxy/CGIHandler.java index 343810da8ae..546ccd8ea10 100644 --- a/jdk/src/java.rmi/share/classes/sun/rmi/transport/proxy/CGIHandler.java +++ b/jdk/src/java.rmi/share/classes/sun/rmi/transport/proxy/CGIHandler.java @@ -81,7 +81,7 @@ interface CGICommandHandler { /** * The CGIHandler class contains methods for executing as a CGI program. * The main function interprets the query string as a command of the form - * "=". + * "{@code =}". * * This class depends on the CGI 1.0 environment variables being set as * properties of the same name in this Java VM. diff --git a/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/FilteredRowSetImpl.java b/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/FilteredRowSetImpl.java index 8d72277cd00..32ef3cf4081 100644 --- a/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/FilteredRowSetImpl.java +++ b/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/FilteredRowSetImpl.java @@ -466,7 +466,7 @@ public class FilteredRowSetImpl extends WebRowSetImpl implements Serializable, C * passed to the evaluate function. * 2. updateXXXstream() - here it would suffice to pass the stream handle * to the evaluate function and the implementation - * of the evaluate function can do the comparision + * of the evaluate function can do the comparison * based on the stream and also type of data. */ diff --git a/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/JoinRowSetImpl.java b/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/JoinRowSetImpl.java index 93386b1ea30..1da997d6905 100644 --- a/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/JoinRowSetImpl.java +++ b/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/JoinRowSetImpl.java @@ -4063,14 +4063,16 @@ public class JoinRowSetImpl extends WebRowSetImpl implements JoinRowSet { } /** - * Provide interface coverage for getURL(int) in ResultSet->RowSet + * Provide interface coverage for getURL(int) in + * ResultSet{@literal ->}RowSet */ public java.net.URL getURL(int columnIndex) throws SQLException { return crsInternal.getURL(columnIndex); } /** - * Provide interface coverage for getURL(String) in ResultSet->RowSet + * Provide interface coverage for getURL(String) in + * ResultSet{@literal ->}RowSet */ public java.net.URL getURL(String columnName) throws SQLException { return crsInternal.getURL(columnName); diff --git a/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/providers/RIOptimisticProvider.java b/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/providers/RIOptimisticProvider.java index 0d8dff3232f..b990d6fbba3 100644 --- a/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/providers/RIOptimisticProvider.java +++ b/jdk/src/java.sql.rowset/share/classes/com/sun/rowset/providers/RIOptimisticProvider.java @@ -36,7 +36,7 @@ import com.sun.rowset.internal.*; * The reference implementation of a JDBC Rowset synchronization provider * providing optimistic synchronization with a relational datastore * using any JDBC technology-enabled driver. - *

                        + * *

                        1.0 Backgroud

                        * This synchronization provider is registered with the * SyncFactory by default as the diff --git a/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/RMIGenerator.java b/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/RMIGenerator.java index 4dc745ff8ab..9725872a373 100644 --- a/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/RMIGenerator.java +++ b/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/RMIGenerator.java @@ -79,7 +79,7 @@ public class RMIGenerator implements RMIConstants, Generator { * Examine and consume command line arguments. * @param argv The command line arguments. Ignore null * and unknown arguments. Set each consumed argument to null. - * @param error Report any errors using the main.error() methods. + * @param main Report any errors using the main.error() methods. * @return true if no errors, false otherwise. */ public boolean parseArgs(String argv[], Main main) { diff --git a/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/RemoteClass.java b/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/RemoteClass.java index e9ec3fa67ea..6187d5ca866 100644 --- a/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/RemoteClass.java +++ b/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/RemoteClass.java @@ -111,7 +111,7 @@ public class RemoteClass implements sun.rmi.rmic.RMIConstants { * the remote methods implemented by this class, i.e. all of the * methods in the class's remote interfaces. * - * The methods in the array are ordered according to the comparision + * The methods in the array are ordered according to the comparison * of the strings consisting of their method name followed by their * type signature, so each method's index in the array corresponds * to its "operation number" in the JDK 1.1 version of the From a6ad9cd49a9599b38ad0be8797b013e63ee307ce Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Tue, 19 May 2015 07:12:10 -0700 Subject: [PATCH 54/70] 8080629: (fs) Re-enable ability to fsync() on directories even though read()s on those directories may fail Revert fix applied to resolve JDK-8066915. Reviewed-by: alanb --- .../classes/sun/nio/fs/UnixChannelFactory.java | 16 ---------------- jdk/test/java/nio/file/Files/SBC.java | 18 +----------------- 2 files changed, 1 insertion(+), 33 deletions(-) diff --git a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixChannelFactory.java b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixChannelFactory.java index 90a9c787ff0..bc194f960ae 100644 --- a/jdk/src/java.base/unix/classes/sun/nio/fs/UnixChannelFactory.java +++ b/jdk/src/java.base/unix/classes/sun/nio/fs/UnixChannelFactory.java @@ -270,22 +270,6 @@ class UnixChannelFactory { throw x; } - // fail if the file is a directory - if (flags.read) { - UnixException exc = null; - try { - if (UnixFileAttributes.get(fd).isDirectory()) { - exc = new UnixException(EISDIR); - } - } catch (UnixException x) { - exc = x; - } - if (exc != null) { - close(fd); - throw exc; - } - } - // unlink file immediately if delete on close. The spec is clear that // an implementation cannot guarantee to unlink the correct file when // replaced by an attacker after it is opened. diff --git a/jdk/test/java/nio/file/Files/SBC.java b/jdk/test/java/nio/file/Files/SBC.java index 64672d27947..d26428d5f60 100644 --- a/jdk/test/java/nio/file/Files/SBC.java +++ b/jdk/test/java/nio/file/Files/SBC.java @@ -22,7 +22,7 @@ */ /* @test - * @bug 4313887 8066915 + * @bug 4313887 * @summary Unit test for java.nio.file.Files.newByteChannel * @library .. */ @@ -59,7 +59,6 @@ public class SBC { dosSharingOptionTests(dir); // misc. tests - directoryOpenTests(dir); badCombinations(dir); unsupportedOptions(dir); nullTests(dir); @@ -279,21 +278,6 @@ public class SBC { } } - // test opening a directory for read or write - static void directoryOpenTests(Path dir) throws Exception { - try (SeekableByteChannel sbc = Files.newByteChannel(dir, READ)) { - throw new RuntimeException("Opened directory for read"); - } catch (IOException expected) { } - - try (SeekableByteChannel sbc = Files.newByteChannel(dir, WRITE)) { - throw new RuntimeException("Opened directory for write"); - } catch (IOException expected) { } - - try (SeekableByteChannel sbc = Files.newByteChannel(dir, APPEND)) { - throw new RuntimeException("Opened directory for append "); - } catch (IOException expected) { } - } - // Windows specific options for the use by applications that really want // to use legacy DOS sharing options static void dosSharingOptionTests(Path dir) throws Exception { From 5dc10dc50689a6e545ce0a500fcad4fe77024dde Mon Sep 17 00:00:00 2001 From: Amy Lu Date: Tue, 19 May 2015 11:05:52 -0400 Subject: [PATCH 55/70] 8080658: Update sun/nio/cs/FindDecoderBugs.java to use random number generator library Reviewed-by: rriggs --- jdk/test/sun/nio/cs/FindDecoderBugs.java | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/jdk/test/sun/nio/cs/FindDecoderBugs.java b/jdk/test/sun/nio/cs/FindDecoderBugs.java index df8afd18960..f4add2a4ca0 100644 --- a/jdk/test/sun/nio/cs/FindDecoderBugs.java +++ b/jdk/test/sun/nio/cs/FindDecoderBugs.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2008, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2008, 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 @@ -24,16 +24,19 @@ /* * @test * @bug 6380723 - * @summary Decode many byte sequences in many ways + * @summary Decode many byte sequences in many ways (use -Dseed=X to set PRNG seed) + * @library /lib/testlibrary + * @build jdk.testlibrary.* * @run main/timeout=1800 FindDecoderBugs * @author Martin Buchholz - * @key randomness + * @key intermittent randomness */ import java.util.*; import java.util.regex.*; import java.nio.*; import java.nio.charset.*; +import jdk.testlibrary.RandomFactory; public class FindDecoderBugs { @@ -322,7 +325,7 @@ public class FindDecoderBugs { } } - private final static Random rnd = new Random(); + private final static Random rnd = RandomFactory.getRandom(); private static byte randomByte() { return (byte) rnd.nextInt(0x100); } From 8f509d71e6072daec1ab89ede5ac490aa22cea52 Mon Sep 17 00:00:00 2001 From: Igor Ignatyev Date: Tue, 19 May 2015 20:04:29 +0300 Subject: [PATCH 56/70] 8055269: java/lang/invoke/MethodHandles/CatchExceptionTest.java fails intermittently Reviewed-by: vlivanov --- .../MethodHandles/CatchExceptionTest.java | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/jdk/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java b/jdk/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java index 1d3cbeb64d1..45284277fcb 100644 --- a/jdk/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java +++ b/jdk/test/java/lang/invoke/MethodHandles/CatchExceptionTest.java @@ -72,12 +72,6 @@ public class CatchExceptionTest { final int catchDrops) { this.testCase = testCase; this.dropped = catchDrops; - if (Helper.IS_VERBOSE) { - System.out.printf("CatchException::CatchException(%s, isVararg=%b " + - "argsCount=%d catchDrops=%d)%n", - testCase, isVararg, argsCount, catchDrops - ); - } MethodHandle thrower = testCase.thrower; int throwerLen = thrower.type().parameterCount(); List> classes; @@ -97,9 +91,11 @@ public class CatchExceptionTest { } public static void main(String[] args) throws Throwable { + System.out.println("classes = " + ARGS_CLASSES); + TestFactory factory = new TestFactory(); long timeout = Helper.IS_THOROUGH ? 0L : Utils.adjustTimeout(Utils.DEFAULT_TEST_TIMEOUT); - // substract vm init time and reserve time for vm exit + // subtract vm init time and reserve time for vm exit timeout *= 0.9; TimeLimitedRunner runner = new TimeLimitedRunner(timeout, 2.0d, () -> { @@ -131,6 +127,12 @@ public class CatchExceptionTest { } private void runTest() { + if (Helper.IS_VERBOSE) { + System.out.printf("CatchException(%s, isVararg=%b argsCount=%d " + + "dropped=%d)%n", + testCase, thrower.isVarargsCollector(), argsCount, dropped); + } + Helper.clear(); Object[] args = Helper.randomArgs( @@ -212,10 +214,7 @@ class TestFactory { args = 1; } - if (Helper.IS_VERBOSE) { - System.out.printf("maxArgs = %d%nmaxDrops = %d%n", - maxArgs, maxDrops); - } + System.out.printf("maxArgs = %d%nmaxDrops = %d%n", maxArgs, maxDrops); constructorSize = TestCase.CONSTRUCTORS.size(); } @@ -243,7 +242,7 @@ class TestFactory { /** * @return next test from test matrix: - * {varArgs, noVarArgs} x TestCase.rtypes x TestCase.THROWABLES x {1, .., maxArgs } x {1, .., maxDrops} + * {varArgs, noVarArgs} x TestCase.rtypes x TestCase.THROWABLES x {1, .., maxArgs } x {0, .., maxDrops} */ public CatchExceptionTest nextTest() { if (constructor < constructorSize) { @@ -256,7 +255,7 @@ class TestFactory { return null; } if (dropArgs <= currentMaxDrops) { - if (dropArgs == 1) { + if (dropArgs == 0) { if (Helper.IS_THOROUGH || Helper.RNG.nextBoolean()) { ++dropArgs; return createTest(); @@ -271,8 +270,8 @@ class TestFactory { } } - if (args <= maxArgs) { - dropArgs = 1; + if (args < maxArgs) { + dropArgs = 0; currentMaxDrops = Math.min(args, maxDrops); ++args; return createTest(); From 589957695509a420932311b207fa3d759168e7e2 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 19 May 2015 13:30:03 -0700 Subject: [PATCH 57/70] 8075284: fix up miscellaneous TM constructions Reviewed-by: lancea --- jdk/src/demo/share/applets.html | 3 +-- jdk/src/demo/share/jvmti/index.html | 2 +- .../share/classes/java/lang/Boolean.java | 13 +++++------ .../javax/crypto/interfaces/package.html | 6 ++--- .../classes/javax/crypto/spec/package.html | 5 ++-- .../share/classes/javax/net/ssl/package.html | 3 +-- .../classes/java/util/logging/package.html | 3 +-- .../classes/javax/management/package.html | 5 ++-- .../javax/management/remote/package.html | 2 +- .../javax/management/remote/rmi/package.html | 5 ++-- .../javax/naming/directory/package.html | 2 +- .../classes/javax/naming/event/package.html | 2 +- .../classes/javax/naming/ldap/package.html | 2 +- .../share/classes/javax/naming/package.html | 2 +- .../classes/javax/naming/spi/package.html | 2 +- .../share/classes/javax/script/package.html | 2 +- .../share/classes/java/sql/package.html | 23 +++++++++---------- .../share/classes/javax/sql/package.html | 6 ++--- .../com/sun/tools/attach/package-info.java | 3 +-- .../share/classes/com/sun/jdi/Accessible.java | 4 ++-- .../com/sun/jdi/ClassNotLoadedException.java | 2 +- .../share/classes/com/sun/jdi/Locatable.java | 8 +++---- .../jdi/request/AccessWatchpointRequest.java | 3 +-- .../ModificationWatchpointRequest.java | 2 +- .../jdk.jdi/share/classes/jdi-overview.html | 5 ++-- .../sample/share/jmx/jmx-scandir/index.html | 14 +++++------ 26 files changed, 58 insertions(+), 71 deletions(-) diff --git a/jdk/src/demo/share/applets.html b/jdk/src/demo/share/applets.html index 2d93ce26982..6f861d6082e 100644 --- a/jdk/src/demo/share/applets.html +++ b/jdk/src/demo/share/applets.html @@ -56,8 +56,7 @@ -JAVATM -PLUG-IN   +JAVA™ PLUG-IN  
                        Demonstration Applets 
                        diff --git a/jdk/src/demo/share/jvmti/index.html b/jdk/src/demo/share/jvmti/index.html index 4b479c12468..25440a104d9 100644 --- a/jdk/src/demo/share/jvmti/index.html +++ b/jdk/src/demo/share/jvmti/index.html @@ -5,7 +5,7 @@

                        The -JavaTM Virtual Machine Tools Interface (JVM TI) +Java™ Virtual Machine Tools Interface (JVM TI) is a native tool interface provided in JDK 5.0 and newer. Native libraries that use JVM TI and are loaded into the Java Virtual Machine diff --git a/jdk/src/java.base/share/classes/java/lang/Boolean.java b/jdk/src/java.base/share/classes/java/lang/Boolean.java index 4e9f6e4328c..1e3a9d7cd05 100644 --- a/jdk/src/java.base/share/classes/java/lang/Boolean.java +++ b/jdk/src/java.base/share/classes/java/lang/Boolean.java @@ -230,13 +230,12 @@ public final class Boolean implements java.io.Serializable, } /** - * Returns {@code true} if and only if the system property - * named by the argument exists and is equal to the string - * {@code "true"}. (Beginning with version 1.0.2 of the - * JavaTM platform, the test of - * this string is case insensitive.) A system property is accessible - * through {@code getProperty}, a method defined by the - * {@code System} class. + * Returns {@code true} if and only if the system property named + * by the argument exists and is equal to the string {@code + * "true"}. (Beginning with version 1.0.2 of the Java™ + * platform, the test of this string is case insensitive.) A + * system property is accessible through {@code getProperty}, a + * method defined by the {@code System} class. *

                        * If there is no property with the specified name, or if the specified * name is empty or null, then {@code false} is returned. diff --git a/jdk/src/java.base/share/classes/javax/crypto/interfaces/package.html b/jdk/src/java.base/share/classes/javax/crypto/interfaces/package.html index 8b18ce2df87..c43000e80a7 100644 --- a/jdk/src/java.base/share/classes/javax/crypto/interfaces/package.html +++ b/jdk/src/java.base/share/classes/javax/crypto/interfaces/package.html @@ -47,8 +47,7 @@ cryptographic provider developer guide:

                        @@ -66,8 +65,7 @@ For further documentation, please see:
                      • - JavaTM - Cryptography Architecture API Specification and Reference + Java™ Cryptography Architecture API Specification and Reference
                      diff --git a/jdk/src/java.base/share/classes/javax/crypto/spec/package.html b/jdk/src/java.base/share/classes/javax/crypto/spec/package.html index b8fd80724de..7f563fbb372 100644 --- a/jdk/src/java.base/share/classes/javax/crypto/spec/package.html +++ b/jdk/src/java.base/share/classes/javax/crypto/spec/package.html @@ -62,14 +62,13 @@ and key specifications, please see:
                    • - JavaTM - Cryptography Architecture API Specification and Reference + Java™ Cryptography Architecture API Specification and Reference
                    • How to Implement a Provider for the - JavaTM Cryptography Architecture + Java™ Cryptography Architecture
                    diff --git a/jdk/src/java.base/share/classes/javax/net/ssl/package.html b/jdk/src/java.base/share/classes/javax/net/ssl/package.html index 52131379bd2..d75e1d397a0 100644 --- a/jdk/src/java.base/share/classes/javax/net/ssl/package.html +++ b/jdk/src/java.base/share/classes/javax/net/ssl/package.html @@ -38,8 +38,7 @@ and to optionally encrypt the data and/or authenticate the communicating peers. diff --git a/jdk/src/java.logging/share/classes/java/util/logging/package.html b/jdk/src/java.logging/share/classes/java/util/logging/package.html index 46385de5cdc..761baa7a083 100644 --- a/jdk/src/java.logging/share/classes/java/util/logging/package.html +++ b/jdk/src/java.logging/share/classes/java/util/logging/package.html @@ -30,8 +30,7 @@ questions.

                    Provides the classes and interfaces of -the JavaTM 2 - platform's core logging facilities. +the Java™ 2 platform's core logging facilities. The central goal of the logging APIs is to support maintaining and servicing software at customer sites. diff --git a/jdk/src/java.management/share/classes/javax/management/package.html b/jdk/src/java.management/share/classes/javax/management/package.html index 71c3c790f2f..c079b338e34 100644 --- a/jdk/src/java.management/share/classes/javax/management/package.html +++ b/jdk/src/java.management/share/classes/javax/management/package.html @@ -30,7 +30,7 @@ questions.

                    Provides the core classes for the Java Management Extensions.

                    The Java Management Extensions - (JMXTM) API is a standard + (JMX™) API is a standard API for management and monitoring. Typical uses include:

                      @@ -87,8 +87,7 @@ questions. notion of Standard MBeans. A Standard MBean is one whose attributes and operations are deduced from a Java interface using certain naming patterns, similar to those used - by JavaBeansTM. For - example, consider an interface like this:

                      + by JavaBeans™. For example, consider an interface like this:

                           public interface ConfigurationMBean {
                      diff --git a/jdk/src/java.management/share/classes/javax/management/remote/package.html b/jdk/src/java.management/share/classes/javax/management/remote/package.html
                      index a545d36fcbf..a38712db15c 100644
                      --- a/jdk/src/java.management/share/classes/javax/management/remote/package.html
                      +++ b/jdk/src/java.management/share/classes/javax/management/remote/package.html
                      @@ -1,6 +1,6 @@
                       
                       
                      -    JMX<sup><font size="-2">TM</font></sup> Remote API.
                      +    JMX™ Remote API.
                       
                       
                      -    JMX(TM) "scandir" Example
                      +    JMX™ "scandir" Example
                         
                         
                       
                      -  

                      JavaTM Management Extensions (JMXTM) scandir Example

                      +

                      Java™ Management Extensions (JMX™) scandir Example

                      Introduction

                        @@ -1197,7 +1197,7 @@ href="http://www.netbeans.org"

                        Another common best practice when you want to improve interoperability is to use directly the Notification base classes provided in the - JMXTM API. Do not create your own + JMX™ API. Do not create your own subclasses of these standard classes.

                        Indeed, if you code your own subclass, a generic @@ -1974,7 +1974,7 @@ java More information on SSL authentication can be obtained from the JavaTM Secure Socket Extension (JSSE) Reference Guide. + >Java™ Secure Socket Extension (JSSE) Reference Guide.

                        To start jconsole with our provided keystore and truststore, go to the scandir example root directory and @@ -2202,13 +2202,13 @@ href="http://java.sun.com/javase/6/docs/technotes/guides/management/jconsole.htm

                      • JavaTM Secure Socket Extension (JSSE) Reference Guide: - comprehensive documentation about the JavaTM Secure Socket + >Java™ Secure Socket Extension (JSSE) Reference Guide: + comprehensive documentation about the Java™ Secure Socket Extension (JSSE)
                      • Java SE 6 Documentation Index: This document covers the - JavaTM Platform, Standard Edition 6 JDK.
                      • + Java™ Platform, Standard Edition 6 JDK.


                        From 8931c0d3b2424a30f986c60f2ec8002c8a060210 Mon Sep 17 00:00:00 2001 From: Joe Darcy Date: Tue, 19 May 2015 18:33:08 -0700 Subject: [PATCH 58/70] 8080711: Prepare sun/nio/cs/FindEncoderBugs.java to find intermittent failures Reviewed-by: rriggs --- jdk/test/sun/nio/cs/FindEncoderBugs.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/jdk/test/sun/nio/cs/FindEncoderBugs.java b/jdk/test/sun/nio/cs/FindEncoderBugs.java index bfef4037ec4..19c1621856f 100644 --- a/jdk/test/sun/nio/cs/FindEncoderBugs.java +++ b/jdk/test/sun/nio/cs/FindEncoderBugs.java @@ -25,15 +25,18 @@ * @test * @bug 6233345 6381699 6381702 6381705 6381706 * @summary Encode many char sequences in many ways + * @library /lib/testlibrary/ + * @build jdk.testlibrary.* * @run main/timeout=1200 FindEncoderBugs * @author Martin Buchholz - * @key randomness + * @key randomness intermittent */ import java.util.*; import java.util.regex.*; import java.nio.*; import java.nio.charset.*; +import jdk.testlibrary.RandomFactory; public class FindEncoderBugs { @@ -456,7 +459,7 @@ public class FindEncoderBugs { } } - private final static Random rnd = new Random(); + private final static Random rnd = RandomFactory.getRandom(); private static char randomChar() { return (char) rnd.nextInt(Character.MAX_VALUE); } From 216d24980d6d24cf7afe3acf27cfd14bdae0f4f7 Mon Sep 17 00:00:00 2001 From: Athijegannathan Sundararajan Date: Wed, 20 May 2015 08:58:14 +0530 Subject: [PATCH 59/70] 8072002: The spec on javax.script.Compilable contains a typo and confusing inconsistency Reviewed-by: lagergren, attila --- .../java.scripting/share/classes/javax/script/Compilable.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/jdk/src/java.scripting/share/classes/javax/script/Compilable.java b/jdk/src/java.scripting/share/classes/javax/script/Compilable.java index c4620cb9831..d355167cc49 100644 --- a/jdk/src/java.scripting/share/classes/javax/script/Compilable.java +++ b/jdk/src/java.scripting/share/classes/javax/script/Compilable.java @@ -42,7 +42,7 @@ public interface Compilable { * * @param script The source of the script, represented as a String. * - * @return An subclass of CompiledScript to be executed later using one + * @return An instance of a subclass of CompiledScript to be executed later using one * of the eval methods of CompiledScript. * * @throws ScriptException if compilation fails. @@ -61,7 +61,7 @@ public interface Compilable { * * @param script The reader from which the script source is obtained. * - * @return An implementation of CompiledScript to be executed + * @return An instance of a subclass of CompiledScript to be executed * later using one of its eval methods of CompiledScript. * * @throws ScriptException if compilation fails. From 8654e36410c788d9430eafa3b4f74d7ce16a56cd Mon Sep 17 00:00:00 2001 From: Doug Lea Date: Wed, 20 May 2015 14:50:57 +0200 Subject: [PATCH 60/70] 8080623: CPU overhead in FJ due to spinning in awaitWork Reviewed-by: chegar, dholmes --- .../java/util/concurrent/ForkJoinPool.java | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java b/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java index 0029322cfc2..58f80866140 100644 --- a/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java +++ b/jdk/src/java.base/share/classes/java/util/concurrent/ForkJoinPool.java @@ -1328,13 +1328,16 @@ public class ForkJoinPool extends AbstractExecutorService { /** * Number of times to spin-wait before blocking. The spins (in * awaitRunStateLock and awaitWork) currently use randomized - * spins. If/when MWAIT-like intrinsics becomes available, they - * may allow quieter spinning. The value of SPINS must be a power - * of two, at least 4. The current value causes spinning for a - * small fraction of typical context-switch times, well worthwhile - * given the typical likelihoods that blocking is not necessary. + * spins. Currently set to zero to reduce CPU usage. + * + * If greater than zero the value of SPINS must be a power + * of two, at least 4. A value of 2048 causes spinning for a + * small fraction of typical context-switch times. + * + * If/when MWAIT-like intrinsics becomes available, they + * may allow quieter spinning. */ - private static final int SPINS = 1 << 11; + private static final int SPINS = 0; /** * Increment for seed generators. See class ThreadLocal for From a3ea97f915c8bffeff38f0225d6c11e6a7beefb8 Mon Sep 17 00:00:00 2001 From: Amy Lu Date: Wed, 20 May 2015 17:16:58 +0300 Subject: [PATCH 61/70] 8080680: sun/nio/cs/TestCompoundTest.java should be removed from TEST.groups Reviewed-by: igerasim --- jdk/test/TEST.groups | 1 - 1 file changed, 1 deletion(-) diff --git a/jdk/test/TEST.groups b/jdk/test/TEST.groups index 73ac408f90e..d6af5fa5799 100644 --- a/jdk/test/TEST.groups +++ b/jdk/test/TEST.groups @@ -534,7 +534,6 @@ needs_charsets = \ sun/nio/cs/OLD/TestIBMDB.java \ sun/nio/cs/SJISCanEncode.java \ sun/nio/cs/Test6254467.java \ - sun/nio/cs/TestCompoundTest.java \ sun/nio/cs/TestCp834_SBCS.java \ sun/nio/cs/TestEUC_TW.java \ sun/nio/cs/TestISO2022CNDecoder.java \ From b7d8c579080f84b0b166dc9b05e2fcb4a91727e9 Mon Sep 17 00:00:00 2001 From: Roger Riggs Date: Wed, 20 May 2015 11:17:09 -0400 Subject: [PATCH 62/70] 8078582: java/lang/Runtime/exec/LotsOfOutput.java fails intermittently with Process consumes memory Small allocations may bump total memory, raise THRESHOLD to 2Mb Reviewed-by: martin --- .../java/lang/Runtime/exec/LotsOfOutput.java | 35 +++++++++++++------ 1 file changed, 24 insertions(+), 11 deletions(-) diff --git a/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java b/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java index b75f8e89eb1..8d0c9514486 100644 --- a/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java +++ b/jdk/test/java/lang/Runtime/exec/LotsOfOutput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2002, 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 @@ -23,12 +23,22 @@ /** * @test - * @bug 4369826 + * @bug 4369826 8078582 * @summary Process with lots of output should not crash VM + * @key intermittent * @author kladko */ public class LotsOfOutput { + static final Runtime runtime = Runtime.getRuntime(); + + // Allow memory to grow by up to 1Mb total + static final int THRESHOLD = 1048576; + + // Compute used memory + static long usedMemory() { + return runtime.totalMemory() - runtime.freeMemory(); + } public static void main(String[] args) throws Exception { if (! UnixCommands.isUnix) { @@ -37,18 +47,21 @@ public class LotsOfOutput { } UnixCommands.ensureCommandsAvailable("cat"); - Process p = Runtime.getRuntime().exec(UnixCommands.cat() + " /dev/zero"); - long initMemory = Runtime.getRuntime().totalMemory(); - for (int i=1; i< 10; i++) { + Process p = runtime.exec(UnixCommands.cat() + " /dev/zero"); + long initMemory = usedMemory(); + boolean growing = false; + for (int i = 1; i < 10; i++) { Thread.sleep(100); - long totalMemory = Runtime.getRuntime().totalMemory(); - if (totalMemory != initMemory) { - System.out.printf("consuming memory: i: %d, initial: %d, total: %d, delta: %d%n", - i, initMemory, totalMemory, totalMemory - initMemory); + long used = usedMemory(); + if (used != initMemory) { + System.out.printf("consuming memory: i: %d, initial: %d, used: %d, delta: %d%n", + i, initMemory, used, used - initMemory); } - if (totalMemory > initMemory + 1000000) - throw new Exception("Process consumes memory."); + if (used > initMemory + THRESHOLD) + growing = true; } + if (growing) + throw new Exception("Process consumes memory."); } } From 9cecb7f70a79c05843b6d0f51d3f1bc41aaee312 Mon Sep 17 00:00:00 2001 From: Rob McKenna Date: Wed, 20 May 2015 18:03:56 +0100 Subject: [PATCH 63/70] 8077822: javac does not recognize '*.java' as file if '-J' option is specified Reviewed-by: ksrini --- .../java.base/windows/native/libjli/java_md.c | 34 ++++++++++++++++--- jdk/test/tools/launcher/Arrrghs.java | 12 ++++++- 2 files changed, 40 insertions(+), 6 deletions(-) diff --git a/jdk/src/java.base/windows/native/libjli/java_md.c b/jdk/src/java.base/windows/native/libjli/java_md.c index fcf1a4932fc..27b87dfdfb9 100644 --- a/jdk/src/java.base/windows/native/libjli/java_md.c +++ b/jdk/src/java.base/windows/native/libjli/java_md.c @@ -990,6 +990,26 @@ ProcessPlatformOption(const char *arg) return JNI_FALSE; } +int +filterArgs(StdArg *stdargs, const int nargc, StdArg **pargv) { + StdArg* argv = NULL; + int nargs = 0; + int i; + + /* Copy the non-vm args */ + for (i = 0; i < nargc ; i++) { + const char *arg = stdargs[i].arg; + if (arg[0] == '-' && arg[1] == 'J') + continue; + argv = (StdArg*) JLI_MemRealloc(argv, (nargs+1) * sizeof(StdArg)); + argv[nargs].arg = JLI_StringDup(arg); + argv[nargs].has_wildcard = stdargs[i].has_wildcard; + nargs++; + } + *pargv = argv; + return nargs; +} + /* * At this point we have the arguments to the application, and we need to * check with original stdargs in order to compare which of these truly @@ -1005,8 +1025,9 @@ CreateApplicationArgs(JNIEnv *env, char **strv, int argc) char *ostart, *astart, **nargv; jboolean needs_expansion = JNI_FALSE; jmethodID mid; - int stdargc; + int filteredargc, stdargc; StdArg *stdargs; + StdArg *filteredargs; jclass cls = GetLauncherHelperClass(env); NULL_CHECK0(cls); @@ -1017,6 +1038,8 @@ CreateApplicationArgs(JNIEnv *env, char **strv, int argc) stdargs = JLI_GetStdArgs(); stdargc = JLI_GetStdArgc(); + filteredargc = filterArgs(stdargs, stdargc, &filteredargs); + // sanity check, this should never happen if (argc > stdargc) { JLI_TraceLauncher("Warning: app args is larger than the original, %d %d\n", argc, stdargc); @@ -1025,8 +1048,8 @@ CreateApplicationArgs(JNIEnv *env, char **strv, int argc) } // sanity check, match the args we have, to the holy grail - idx = stdargc - argc; - ostart = stdargs[idx].arg; + idx = filteredargc - argc; + ostart = filteredargs[idx].arg; astart = strv[0]; // sanity check, ensure that the first argument of the arrays are the same if (JLI_StrCmp(ostart, astart) != 0) { @@ -1039,8 +1062,8 @@ CreateApplicationArgs(JNIEnv *env, char **strv, int argc) // make a copy of the args which will be expanded in java if required. nargv = (char **)JLI_MemAlloc(argc * sizeof(char*)); for (i = 0, j = idx; i < argc; i++, j++) { - jboolean arg_expand = (JLI_StrCmp(stdargs[j].arg, strv[i]) == 0) - ? stdargs[j].has_wildcard + jboolean arg_expand = (JLI_StrCmp(filteredargs[j].arg, strv[i]) == 0) + ? filteredargs[j].has_wildcard : JNI_FALSE; if (needs_expansion == JNI_FALSE) needs_expansion = arg_expand; @@ -1077,5 +1100,6 @@ CreateApplicationArgs(JNIEnv *env, char **strv, int argc) JLI_MemFree(nargv[i]); } JLI_MemFree(nargv); + JLI_MemFree(filteredargs); return outArray; } diff --git a/jdk/test/tools/launcher/Arrrghs.java b/jdk/test/tools/launcher/Arrrghs.java index c7f53d3251d..cb36d2dfe8a 100644 --- a/jdk/test/tools/launcher/Arrrghs.java +++ b/jdk/test/tools/launcher/Arrrghs.java @@ -24,7 +24,7 @@ /** * @test * @bug 5030233 6214916 6356475 6571029 6684582 6742159 4459600 6758881 6753938 - * 6894719 6968053 7151434 7146424 8007333 + * 6894719 6968053 7151434 7146424 8007333 8077822 * @summary Argument parsing validation. * @compile -XDignore.symbol.file Arrrghs.java * @run main/othervm Arrrghs @@ -304,6 +304,16 @@ public class Arrrghs extends TestHelper { throw new RuntimeException("Error: compiling java wildcards"); } + // test if javac (the command) can compile *.java with a vmoption + tr = doExec(javacCmd, "-cp", ".", + "-J-showversion", "-J-Dsomeproperty=foo", + libDir.getName() + File.separator + "*.java"); + if (!tr.isOK()) { + System.out.println(tr); + throw new RuntimeException("Error: compiling java wildcards with vmoptions"); + } + + // use the jar cmd to create jars using the ? wildcard File jarFoo = new File(libDir, "Foo.jar"); tr = doExec(jarCmd, "cvf", jarFoo.getAbsolutePath(), "lib" + File.separator + "F?o.class"); From efc37c5e71f41bdb3f53e980a3ec5804acdf3fb9 Mon Sep 17 00:00:00 2001 From: Rob McKenna Date: Wed, 20 May 2015 18:06:31 +0100 Subject: [PATCH 64/70] 8077155: LoginContext Subject ignored by jdk8 sun.net.www.protocol.http.HttpURLConnection Reviewed-by: michaelm --- .../www/protocol/http/HttpURLConnection.java | 8 +- .../krb5/auto/HttpNegotiateServer.java | 160 +++++++++++++++++- 2 files changed, 161 insertions(+), 7 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java index a012c3b6a1c..b9d594b0316 100644 --- a/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java +++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/http/HttpURLConnection.java @@ -983,7 +983,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { SocketPermission p = URLtoSocketPermission(this.url); if (p != null) { try { - AccessController.doPrivileged( + AccessController.doPrivilegedWithCombiner( new PrivilegedExceptionAction<>() { public Void run() throws IOException { plainConnect0(); @@ -1244,7 +1244,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (p != null) { try { - return AccessController.doPrivileged( + return AccessController.doPrivilegedWithCombiner( new PrivilegedExceptionAction<>() { public OutputStream run() throws IOException { return getOutputStream0(); @@ -1422,7 +1422,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (p != null) { try { - return AccessController.doPrivileged( + return AccessController.doPrivilegedWithCombiner( new PrivilegedExceptionAction<>() { public InputStream run() throws IOException { return getInputStream0(); @@ -2565,7 +2565,7 @@ public class HttpURLConnection extends java.net.HttpURLConnection { if (p != null) { try { - return AccessController.doPrivileged( + return AccessController.doPrivilegedWithCombiner( new PrivilegedExceptionAction<>() { public Boolean run() throws IOException { return followRedirect0(loc, stat, locUrl0); diff --git a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java index fea76c829f9..9d3b44e0057 100644 --- a/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java +++ b/jdk/test/sun/security/krb5/auto/HttpNegotiateServer.java @@ -40,21 +40,34 @@ import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; +import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.PasswordAuthentication; import java.net.Proxy; import java.net.URL; -import java.security.PrivilegedExceptionAction; +import java.net.URLConnection; +import java.security.*; import java.util.HashMap; import java.util.Map; import javax.security.auth.Subject; +import javax.security.auth.callback.Callback; +import javax.security.auth.callback.CallbackHandler; +import javax.security.auth.callback.NameCallback; +import javax.security.auth.callback.PasswordCallback; +import javax.security.auth.callback.UnsupportedCallbackException; +import javax.security.auth.login.AppConfigurationEntry; +import javax.security.auth.login.Configuration; +import javax.security.auth.login.LoginContext; +import javax.security.auth.login.LoginException; +import javax.security.auth.login.AppConfigurationEntry.LoginModuleControlFlag; import org.ietf.jgss.GSSContext; import org.ietf.jgss.GSSCredential; import org.ietf.jgss.GSSManager; import sun.security.jgss.GSSUtil; import sun.security.krb5.Config; +import java.util.Base64; import sun.util.logging.PlatformLogger; import java.util.Base64; @@ -197,7 +210,7 @@ public class HttpNegotiateServer { proxyUrl = new URL("http://nosuchplace/a/b/c"); try { - Exception e1 = null, e2 = null; + Exception e1 = null, e2 = null, e3 = null; try { test6578647(); } catch (Exception e) { @@ -210,7 +223,14 @@ public class HttpNegotiateServer { e2 = e; e.printStackTrace(); } - if (e1 != null || e2 != null) { + try { + test8077155(); + } catch (Exception e) { + e3 = e; + e.printStackTrace(); + } + + if (e1 != null || e2 != null || e3 != null) { throw new RuntimeException("Test error"); } } finally { @@ -254,6 +274,121 @@ public class HttpNegotiateServer { } } + static void testConnect() { + InputStream inputStream = null; + try { + URL url = webUrl; + + URLConnection conn = url.openConnection(); + conn.connect(); + inputStream = conn.getInputStream(); + byte[] b = new byte[inputStream.available()]; + for (int j = 0; j < b.length; j++) { + b[j] = (byte) inputStream.read(); + } + String s = new String(b); + System.out.println("Length: " + s.length()); + System.out.println(s); + } catch (Exception ex) { + throw new RuntimeException(ex); + } finally { + if (inputStream != null) { + try { + inputStream.close(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + } + + static void test8077155() throws Exception { + final String username = WEB_USER; + final char[] password = WEB_PASS; + + SecurityManager security = new SecurityManager(); + Policy.setPolicy(new SecurityPolicy()); + System.setSecurityManager(security); + + CallbackHandler callback = new CallbackHandler() { + @Override + public void handle(Callback[] pCallbacks) throws IOException, UnsupportedCallbackException { + for (Callback cb : pCallbacks) { + if (cb instanceof NameCallback) { + NameCallback ncb = (NameCallback)cb; + ncb.setName(username); + + } else if (cb instanceof PasswordCallback) { + PasswordCallback pwdcb = (PasswordCallback) cb; + pwdcb.setPassword(password); + } + } + } + + }; + + final String jaasConfigName = "oracle.test.kerberos.login"; + final String krb5LoginModule = "com.sun.security.auth.module.Krb5LoginModule"; + + Configuration loginConfig = new Configuration() { + @Override + public AppConfigurationEntry[] getAppConfigurationEntry(String name) { + if (! jaasConfigName.equals(name)) { + return new AppConfigurationEntry[0]; + } + + Map options = new HashMap(); + options.put("useTicketCache", Boolean.FALSE.toString()); + options.put("useKeyTab", Boolean.FALSE.toString()); + + return new AppConfigurationEntry[] { + new AppConfigurationEntry(krb5LoginModule, + LoginModuleControlFlag.REQUIRED, + options) + }; + } + }; + + // oracle context/subject/login + LoginContext context = null; + try { + context = new LoginContext("oracle.test.kerberos.login", null, callback, loginConfig); + context.login(); + + } catch (LoginException ex) { + ex.printStackTrace(); + throw new RuntimeException(ex); + } + + + Subject subject = context.getSubject(); + + final PrivilegedExceptionAction test_action = new PrivilegedExceptionAction() { + public Object run() throws Exception { + testConnect(); + return null; + } + }; + + System.err.println("\n\nExpecting to succeed when executing with the the logged in subject."); + + try { + Subject.doAs(subject, test_action); + System.err.println("\n\nConnection succeed when executing with the the logged in subject."); + } catch (PrivilegedActionException e) { + System.err.println("\n\nFailure unexpected when executing with the the logged in subject."); + e.printStackTrace(); + throw new RuntimeException("Failed to login as subject"); + } + + try { + System.err.println("\n\nExpecting to fail when running with the current user's login."); + testConnect(); + } catch (Exception ex) { + System.err.println("\nConnect failed when running with the current user's login:\n" + ex.getMessage()); + } + } + /** * Creates and starts an HTTP or proxy server that requires * Negotiate authentication. @@ -366,3 +501,22 @@ public class HttpNegotiateServer { } } } + +class SecurityPolicy extends Policy { + + private static Permissions perms; + + public SecurityPolicy() { + super(); + if (perms == null) { + perms = new Permissions(); + perms.add(new AllPermission()); + } + } + + @Override + public PermissionCollection getPermissions(CodeSource codesource) { + return perms; + } + +} From c7c5826bb2c5080f853418384153133f0f9599ab Mon Sep 17 00:00:00 2001 From: Zaiyao Liu Date: Thu, 21 May 2015 09:35:26 +0000 Subject: [PATCH 65/70] 8048599: Tests for key wrap and unwrap operations Reviewed-by: xuelei --- .../KeyWrap/TestCipherKeyWrapperTest.java | 316 ++++++++++++++++++ 1 file changed, 316 insertions(+) create mode 100644 jdk/test/com/sun/crypto/provider/Cipher/KeyWrap/TestCipherKeyWrapperTest.java diff --git a/jdk/test/com/sun/crypto/provider/Cipher/KeyWrap/TestCipherKeyWrapperTest.java b/jdk/test/com/sun/crypto/provider/Cipher/KeyWrap/TestCipherKeyWrapperTest.java new file mode 100644 index 00000000000..363d21d0c27 --- /dev/null +++ b/jdk/test/com/sun/crypto/provider/Cipher/KeyWrap/TestCipherKeyWrapperTest.java @@ -0,0 +1,316 @@ +/* + * Copyright (c) 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. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please 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 static java.lang.System.out; + +import java.lang.Integer; +import java.lang.String; +import java.lang.System; +import java.security.AlgorithmParameters; +import java.security.InvalidAlgorithmParameterException; +import java.security.InvalidKeyException; +import java.security.Key; +import java.security.KeyPair; +import java.security.NoSuchAlgorithmException; +import java.security.KeyPairGenerator; +import java.security.Provider; +import java.security.Security; +import java.security.spec.AlgorithmParameterSpec; +import java.security.spec.InvalidKeySpecException; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Random; + +import javax.crypto.IllegalBlockSizeException; +import javax.crypto.NoSuchPaddingException; +import javax.crypto.SecretKey; +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKeyFactory; +import javax.crypto.spec.PBEKeySpec; +import javax.crypto.spec.PBEParameterSpec; + +/* + * @test + * @bug 8048599 + * @summary Tests for key wrap and unwrap operations + */ + +public class TestCipherKeyWrapperTest { + private static final String SUN_JCE = "SunJCE"; + // Blowfish Variable key length: 32 bits to 448 bits + private static final int BLOWFISH_MIN_KEYSIZE = 32; + private static final int BLOWFISH_MAX_KEYSIZE = 448; + private static final int LINIMITED_KEYSIZE = 128; + private static final String NOPADDING = "NoPaDDing"; + private static final String[] PBE_ALGORITHM_AR = { "pbeWithMD5ANDdes", + "PBEWithMD5AndDES/CBC/PKCS5Padding", "PBEWithMD5AndTripleDES", + "PBEWithMD5AndTripleDES/CBC/PKCS5Padding", "PBEwithSHA1AndDESede", + "PBEwithSHA1AndDESede/CBC/PKCS5Padding", "PBEwithSHA1AndRC2_40", + "PBEwithSHA1Andrc2_40/CBC/PKCS5Padding", "PBEWithSHA1AndRC2_128", + "PBEWithSHA1andRC2_128/CBC/PKCS5Padding", "PBEWithSHA1AndRC4_40", + "PBEWithsha1AndRC4_40/ECB/NoPadding", "PBEWithSHA1AndRC4_128", + "pbeWithSHA1AndRC4_128/ECB/NoPadding", "PBEWithHmacSHA1AndAES_128", + "PBEWithHmacSHA224AndAES_128", "PBEWithHmacSHA256AndAES_128", + "PBEWithHmacSHA384AndAES_128", "PBEWithHmacSHA512AndAES_128", + "PBEWithHmacSHA1AndAES_256", "PBEWithHmacSHA224AndAES_256", + "PBEWithHmacSHA256AndAES_256", "PBEWithHmacSHA384AndAES_256", + "PBEWithHmacSHA512AndAES_256" }; + private static final String[] MODEL_AR = { "ECb", "pCbC", "cbC", "cFB", + "cFB24", "cFB40", "OfB48", "OFB64" }; + private static final String[] PADDING_AR = { NOPADDING, "PKCS5Padding" }; + + private enum AlgorithmWrapper { + AESWrap("AES", "AESWrap", -1), + AESWrap_128("AES", "AESWrap_128", 128), + AESWrap_192("AES", "AESWrap_192", 192), + AESWrap_256("AES", "AESWrap_256", 256), + DESedeWrap("desede", "DESedeWrap", -1), + NegtiveWrap("AES", "DESedeWrap", -1); + + private final String algorithm; + private final String wrapper; + private final int keySize; + + private AlgorithmWrapper(String algorithm, String wrapper, int kSize) { + this.algorithm = algorithm; + this.wrapper = wrapper; + this.keySize = kSize; + } + + public String getAlgorithm() { + return algorithm; + } + + public String getWrapper() { + return wrapper; + } + + public int getKeySize() { + return keySize; + } + + }; + + public static void main(String[] args) throws Exception { + + TestCipherKeyWrapperTest test = new TestCipherKeyWrapperTest(); + // AESWrap and DESedeWrap test + for (AlgorithmWrapper algoWrapper : AlgorithmWrapper.values()) { + String algo = algoWrapper.getAlgorithm(); + String wrapper = algoWrapper.getWrapper(); + try { + int keySize = algoWrapper.getKeySize(); + // only run the tests on longer key lengths if unlimited + // version of JCE jurisdiction policy files are installed + if (!(Cipher.getMaxAllowedKeyLength(algo) == Integer.MAX_VALUE) + && keySize > LINIMITED_KEYSIZE) { + out.println(algo + " will not run if unlimited version of" + + " JCE jurisdiction policy files are installed"); + continue; + } + test.wrapperAesDESedeKeyTest(algo, wrapper, keySize); + if (algoWrapper == AlgorithmWrapper.NegtiveWrap) { + throw new RuntimeException("Expected not throw when algo" + + " and wrapAlgo are not match:" + algo); + } + } catch (InvalidKeyException e) { + if (algoWrapper == AlgorithmWrapper.NegtiveWrap) { + out.println("Expepted exception when algo" + + " and wrapAlgo are not match:" + algo); + } else { + throw e; + } + } + } + test.wrapperBlowfishKeyTest(); + // PBE and public wrapper test. + String[] publicPrivateAlgos = new String[] { "DiffieHellman", "DSA", + "RSA" }; + Provider provider = Security.getProvider(SUN_JCE); + if (provider == null) { + throw new RuntimeException("SUN_JCE provider not exist"); + } + + test.wrapperPBEKeyTest(provider); + // Public and private key wrap test + test.wrapperPublicPriviteKeyTest(provider, publicPrivateAlgos); + } + + private void wrapperAesDESedeKeyTest(String algo, String wrapAlgo, + int keySize) throws InvalidKeyException, NoSuchAlgorithmException, + NoSuchPaddingException, IllegalBlockSizeException, + InvalidAlgorithmParameterException { + // Initialization + KeyGenerator kg = KeyGenerator.getInstance(algo); + if (keySize != -1) { + kg.init(keySize); + } + SecretKey key = kg.generateKey(); + wrapTest(algo, wrapAlgo, key, key, Cipher.SECRET_KEY, false); + } + + private void wrapperBlowfishKeyTest() throws InvalidKeyException, + NoSuchAlgorithmException, NoSuchPaddingException, + IllegalBlockSizeException, InvalidAlgorithmParameterException { + // how many kinds of padding mode + int padKinds; + // Keysize should be multiple of 8 bytes. + int KeyCutter = 8; + int kSize = BLOWFISH_MIN_KEYSIZE; + String algorithm = "Blowfish"; + int maxAllowKeyLength = Cipher.getMaxAllowedKeyLength(algorithm); + boolean unLimitPolicy = maxAllowKeyLength == Integer.MAX_VALUE; + SecretKey key = null; + while (kSize <= BLOWFISH_MAX_KEYSIZE) { + for (String mode : MODEL_AR) { + // PKCS5padding is meaningful only for ECB, CBC, PCBC + if (mode.equalsIgnoreCase(MODEL_AR[0]) + || mode.equalsIgnoreCase(MODEL_AR[1]) + || mode.equalsIgnoreCase(MODEL_AR[2])) { + padKinds = PADDING_AR.length; + } else { + padKinds = 1; + } + // Initialization + KeyGenerator kg = KeyGenerator.getInstance(algorithm); + for (int k = 0; k < padKinds; k++) { + String transformation = algorithm + "/" + mode + "/" + + PADDING_AR[k]; + if (NOPADDING.equals(PADDING_AR[k]) && kSize % 64 != 0) { + out.println(transformation + + " will not run if input length not multiple" + + " of 8 bytes when padding is " + NOPADDING); + continue; + } + kg.init(kSize); + key = kg.generateKey(); + // only run the tests on longer key lengths if unlimited + // version of JCE jurisdiction policy files are installed + if (!unLimitPolicy && kSize > LINIMITED_KEYSIZE) { + out.println("keyStrength > 128 within " + algorithm + + " will not run under global policy"); + } else { + wrapTest(transformation, transformation, key, key, + Cipher.SECRET_KEY, false); + } + } + } + if (kSize <= LINIMITED_KEYSIZE) { + KeyCutter = 8; + } else { + KeyCutter = 48; + } + kSize += KeyCutter; + } + } + + private void wrapperPBEKeyTest(Provider p) throws InvalidKeySpecException, + InvalidKeyException, NoSuchPaddingException, + IllegalBlockSizeException, InvalidAlgorithmParameterException, + NoSuchAlgorithmException { + for (String alg : PBE_ALGORITHM_AR) { + String baseAlgo = alg.split("/")[0].toUpperCase(); + // only run the tests on longer key lengths if unlimited version + // of JCE jurisdiction policy files are installed + + if (Cipher.getMaxAllowedKeyLength(alg) < Integer.MAX_VALUE + && (baseAlgo.endsWith("TRIPLEDES") || alg + .endsWith("AES_256"))) { + out.println("keyStrength > 128 within " + alg + + " will not run under global policy"); + continue; + } + SecretKeyFactory skf = SecretKeyFactory.getInstance(baseAlgo, p); + SecretKey key = skf.generateSecret(new PBEKeySpec("Secret Lover" + .toCharArray())); + wrapTest(alg, alg, key, key, Cipher.SECRET_KEY, true); + } + } + + private void wrapperPublicPriviteKeyTest(Provider p, String[] algorithms) + throws NoSuchAlgorithmException, InvalidKeyException, + NoSuchPaddingException, IllegalBlockSizeException, + InvalidAlgorithmParameterException { + for (String algo : algorithms) { + // Key pair generated + System.out.println("Generate key pair (algorithm: " + algo + + ", provider: " + p.getName() + ")"); + KeyPairGenerator kpg = KeyPairGenerator.getInstance(algo); + kpg.initialize(512); + KeyPair kp = kpg.genKeyPair(); + // key generated + String algoWrap = "DES"; + KeyGenerator kg = KeyGenerator.getInstance(algoWrap, p); + Key key = kg.generateKey(); + wrapTest(algo, algoWrap, key, kp.getPrivate(), Cipher.PRIVATE_KEY, + false); + wrapTest(algo, algoWrap, key, kp.getPublic(), Cipher.PUBLIC_KEY, + false); + } + } + + private void wrapTest(String transformation, String wrapAlgo, Key initKey, + Key wrapKey, int keyType, boolean isPBE) + throws NoSuchAlgorithmException, NoSuchPaddingException, + InvalidKeyException, IllegalBlockSizeException, + InvalidAlgorithmParameterException { + String algo = transformation.split("/")[0]; + boolean isAESBlowfish = algo.indexOf("AES") != -1 + || algo.indexOf("Blowfish") != -1; + AlgorithmParameters aps = null; + AlgorithmParameterSpec pbeParams = null; + if (isPBE) { + byte[] salt = new byte[8]; + int iterCnt = 1000; + new Random().nextBytes(salt); + pbeParams = new PBEParameterSpec(salt, iterCnt); + } + // Wrap & UnWrap operation + Cipher wrapCI = Cipher.getInstance(wrapAlgo); + if (isPBE && !isAESBlowfish) { + wrapCI.init(Cipher.WRAP_MODE, initKey, pbeParams); + } else if (isAESBlowfish) { + wrapCI.init(Cipher.WRAP_MODE, initKey); + aps = wrapCI.getParameters(); + } else { + wrapCI.init(Cipher.WRAP_MODE, initKey); + } + out.println("keysize : " + wrapKey.getEncoded().length); + byte[] keyWrapper = wrapCI.wrap(wrapKey); + if (isPBE && !isAESBlowfish) { + wrapCI.init(Cipher.UNWRAP_MODE, initKey, pbeParams); + } else if (isAESBlowfish) { + wrapCI.init(Cipher.UNWRAP_MODE, initKey, aps); + } else { + wrapCI.init(Cipher.UNWRAP_MODE, initKey); + } + Key unwrappedKey = wrapCI.unwrap(keyWrapper, algo, keyType); + // Comparison + if (!Arrays.equals(wrapKey.getEncoded(), unwrappedKey.getEncoded())) { + throw new RuntimeException("Comparation failed testing " + + transformation + ":" + wrapAlgo + ":" + keyType); + } + } +} From d29a80d711e1f9791969c89ef7041fbe14124c1d Mon Sep 17 00:00:00 2001 From: Sean Mullan Date: Thu, 21 May 2015 07:17:36 -0400 Subject: [PATCH 66/70] 8055753: Use ConcurrentHashMap to map ProtectionDomain to PermissionCollection Reviewed-by: weijun --- .../java/security/ProtectionDomain.java | 147 ++++++++++++++---- 1 file changed, 114 insertions(+), 33 deletions(-) diff --git a/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java b/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java index 3dd5933fb06..786d63ce73f 100644 --- a/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java +++ b/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java @@ -25,23 +25,24 @@ package java.security; +import java.lang.ref.Reference; +import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.ArrayList; import java.util.Enumeration; import java.util.List; import java.util.Map; import java.util.WeakHashMap; +import java.util.concurrent.ConcurrentHashMap; +import sun.misc.JavaSecurityAccess; import sun.misc.JavaSecurityProtectionDomainAccess; import static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache; +import sun.misc.SharedSecrets; import sun.security.util.Debug; import sun.security.util.SecurityConstants; -import sun.misc.JavaSecurityAccess; -import sun.misc.SharedSecrets; /** - * - *

                        - * This ProtectionDomain class encapsulates the characteristics of a domain, + * The ProtectionDomain class encapsulates the characteristics of a domain, * which encloses a set of classes whose instances are granted a set * of permissions when being executed on behalf of a given set of Principals. *

                        @@ -58,6 +59,7 @@ import sun.misc.SharedSecrets; */ public class ProtectionDomain { + private static class JavaSecurityAccessImpl implements JavaSecurityAccess { private JavaSecurityAccessImpl() { @@ -86,18 +88,33 @@ public class ProtectionDomain { AccessController.getContext(), context); } - private static AccessControlContext getCombinedACC(AccessControlContext context, AccessControlContext stack) { - AccessControlContext acc = new AccessControlContext(context, stack.getCombiner(), true); + private static AccessControlContext getCombinedACC( + AccessControlContext context, AccessControlContext stack) { + AccessControlContext acc = + new AccessControlContext(context, stack.getCombiner(), true); return new AccessControlContext(stack.getContext(), acc).optimize(); } } static { - // Set up JavaSecurityAccess in SharedSecrets + // setup SharedSecrets to allow access to doIntersectionPrivilege + // methods and ProtectionDomain cache SharedSecrets.setJavaSecurityAccess(new JavaSecurityAccessImpl()); + SharedSecrets.setJavaSecurityProtectionDomainAccess( + new JavaSecurityProtectionDomainAccess() { + @Override + public ProtectionDomainCache getProtectionDomainCache() { + return new PDCache(); + } + }); } + /** + * Used for storing ProtectionDomains as keys in a Map. + */ + static final class Key {} + /* CodeSource */ private CodeSource codesource ; @@ -451,40 +468,104 @@ public class ProtectionDomain { } /** - * Used for storing ProtectionDomains as keys in a Map. + * A cache of ProtectionDomains and their Permissions. + * + * This class stores ProtectionDomains as weak keys in a ConcurrentHashMap + * with additional support for checking and removing weak keys that are no + * longer in use. */ - final static class Key {} - - // A cache of ProtectionDomains and their Permissions private static class PDCache implements ProtectionDomainCache { - // We must wrap the PermissionCollection in a WeakReference as there - // are some PermissionCollections which contain strong references - // back to a ProtectionDomain and otherwise would never be removed - // from the WeakHashMap - private final Map> - map = new WeakHashMap<>(); + private final ConcurrentHashMap + pdMap = new ConcurrentHashMap<>(); + private final ReferenceQueue queue = new ReferenceQueue<>(); @Override - public synchronized void put(ProtectionDomain pd, - PermissionCollection pc) { - map.put(pd == null ? null : pd.key, new WeakReference<>(pc)); + public void put(ProtectionDomain pd, PermissionCollection pc) { + processQueue(queue, pdMap); + WeakProtectionDomainKey weakPd = + new WeakProtectionDomainKey(pd, queue); + pdMap.putIfAbsent(weakPd, pc); } @Override - public synchronized PermissionCollection get(ProtectionDomain pd) { - WeakReference ref = - map.get(pd == null ? null : pd.key); - return ref == null ? null : ref.get(); + public PermissionCollection get(ProtectionDomain pd) { + processQueue(queue, pdMap); + WeakProtectionDomainKey weakPd = + new WeakProtectionDomainKey(pd, queue); + return pdMap.get(weakPd); + } + + /** + * Removes weak keys from the map that have been enqueued + * on the reference queue and are no longer in use. + */ + private static void processQueue(ReferenceQueue queue, + ConcurrentHashMap, ?> pdMap) { + Reference ref; + while ((ref = queue.poll()) != null) { + pdMap.remove(ref); + } } } - static { - SharedSecrets.setJavaSecurityProtectionDomainAccess( - new JavaSecurityProtectionDomainAccess() { - @Override - public ProtectionDomainCache getProtectionDomainCache() { - return new PDCache(); - } - }); + /** + * A weak key for a ProtectionDomain. + */ + private static class WeakProtectionDomainKey extends WeakReference { + /** + * Saved value of the referent's identity hash code, to maintain + * a consistent hash code after the referent has been cleared + */ + private final int hash; + + /** + * A key representing a null ProtectionDomain. + */ + private static final Key NULL_KEY = new Key(); + + /** + * Create a new WeakProtectionDomain with the specified domain and + * registered with a queue. + */ + WeakProtectionDomainKey(ProtectionDomain pd, ReferenceQueue rq) { + this((pd == null ? NULL_KEY : pd.key), rq); + } + + private WeakProtectionDomainKey(Key key, ReferenceQueue rq) { + super(key, rq); + hash = key.hashCode(); + } + + /** + * Returns the identity hash code of the original referent. + */ + @Override + public int hashCode() { + return hash; + } + + /** + * Returns true if the given object is an identical + * WeakProtectionDomainKey instance, or, if this object's referent + * has not been cleared and the given object is another + * WeakProtectionDomainKey instance with an identical non-null + * referent as this one. + */ + @Override + public boolean equals(Object obj) { + if (obj == this) { + return true; + } + + if (obj instanceof WeakProtectionDomainKey) { + Object referent = get(); + return (referent != null) && + (referent == ((WeakProtectionDomainKey)obj).get()); + } else { + return false; + } + } } } From 6deb69ac50f30795817455db74654ca94b7c57d2 Mon Sep 17 00:00:00 2001 From: Vinnie Ryan Date: Thu, 21 May 2015 17:42:15 +0100 Subject: [PATCH 67/70] 8072578: ProbeKeystores.java creates files in test.src Reviewed-by: weijun --- .../security/KeyStore/ProbeKeystores.java | 38 +++++-------------- 1 file changed, 9 insertions(+), 29 deletions(-) diff --git a/jdk/test/java/security/KeyStore/ProbeKeystores.java b/jdk/test/java/security/KeyStore/ProbeKeystores.java index 10a005316fe..f97c416cfe4 100644 --- a/jdk/test/java/security/KeyStore/ProbeKeystores.java +++ b/jdk/test/java/security/KeyStore/ProbeKeystores.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2014, 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 @@ -41,15 +41,6 @@ public class ProbeKeystores { private static final String CERT_FILE = "trusted.pem"; public static final void main(String[] args) throws Exception { - try { - test(); - } finally { - cleanup(); - } - } - - private static final void test() throws Exception { - cleanup(); // Testing empty keystores @@ -129,22 +120,11 @@ public class ProbeKeystores { System.out.println("OK."); } - private static void cleanup() { - new File("empty.jks").delete(); - new File("empty.jceks").delete(); - new File("empty.p12").delete(); - new File("onecert.jks").delete(); - new File("onecert.jceks").delete(); - new File("onecert.p12").delete(); - new File("onekey.jceks").delete(); - new File("onekey.p12").delete(); - } - // Instantiate an empty keystore using the supplied keystore type private static void init(String file, String type) throws Exception { KeyStore ks = KeyStore.getInstance(type); ks.load(null, null); - try (OutputStream stream = new FileOutputStream(DIR + "/" + file)) { + try (OutputStream stream = new FileOutputStream(file)) { ks.store(stream, PASSWORD); } System.out.println("Created a " + type + " keystore named '" + file + "'"); @@ -156,7 +136,7 @@ public class ProbeKeystores { KeyStore ks = KeyStore.getInstance(type); ks.load(null, null); ks.setEntry("mycert", new KeyStore.TrustedCertificateEntry(cert), null); - try (OutputStream stream = new FileOutputStream(DIR + "/" + file)) { + try (OutputStream stream = new FileOutputStream(file)) { ks.store(stream, PASSWORD); } System.out.println("Created a " + type + " keystore named '" + file + "'"); @@ -169,7 +149,7 @@ public class ProbeKeystores { ks.load(null, null); ks.setEntry("mykey", new KeyStore.SecretKeyEntry(key), new PasswordProtection(PASSWORD)); - try (OutputStream stream = new FileOutputStream(DIR + "/" + file)) { + try (OutputStream stream = new FileOutputStream(file)) { ks.store(stream, PASSWORD); } System.out.println("Created a " + type + " keystore named '" + file + "'"); @@ -178,7 +158,7 @@ public class ProbeKeystores { // Instantiate a keystore by probing the supplied file for the keystore type private static void probe(String file, String type) throws Exception { // First try with the correct password - KeyStore ks = KeyStore.getInstance(new File(DIR, file), PASSWORD); + KeyStore ks = KeyStore.getInstance(new File(file), PASSWORD); if (!type.equalsIgnoreCase(ks.getType())) { throw new Exception("ERROR: expected a " + type + " keystore, " + "got a " + ks.getType() + " keystore instead"); @@ -188,7 +168,7 @@ public class ProbeKeystores { // Next try with an incorrect password try { - ks = KeyStore.getInstance(new File(DIR, file), BAD_PASSWORD); + ks = KeyStore.getInstance(new File(file), BAD_PASSWORD); throw new Exception("ERROR: expected an exception but got success"); } catch (IOException e) { System.out.println("Failed to load a " + type + " keystore named '" + file + "' (as expected)"); @@ -201,10 +181,10 @@ public class ProbeKeystores { Builder builder; if (usePassword) { - builder = Builder.newInstance(new File(DIR, file), + builder = Builder.newInstance(new File(file), new PasswordProtection(PASSWORD)); } else { - builder = Builder.newInstance(new File(DIR, file), + builder = Builder.newInstance(new File(file), new CallbackHandlerProtection(new DummyHandler())); } KeyStore ks = builder.getKeyStore(); @@ -219,7 +199,7 @@ public class ProbeKeystores { // Load the keystore entries private static void load(String file, String type) throws Exception { KeyStore ks = KeyStore.getInstance(type); - try (InputStream stream = new FileInputStream(DIR + "/" + file)) { + try (InputStream stream = new FileInputStream(file)) { ks.load(stream, PASSWORD); } if (!type.equalsIgnoreCase(ks.getType())) { From 457be276d829dfa9f9756778ab153ccaa9247eaf Mon Sep 17 00:00:00 2001 From: Brian Burkhalter Date: Thu, 21 May 2015 09:57:59 -0700 Subject: [PATCH 68/70] 8080589: (fs) FileChannel.force should use fcntl(F_FULLFSYNC) instead of fsync on OS X Replace f[data]sync(fd) with fcntl(fd, F_FULLSYNC) on OS X. Reviewed-by: alanb --- .../unix/native/libnio/ch/FileDispatcherImpl.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/jdk/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c b/jdk/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c index 403c15cad06..8738d5f9f68 100644 --- a/jdk/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c +++ b/jdk/src/java.base/unix/native/libnio/ch/FileDispatcherImpl.c @@ -148,6 +148,13 @@ Java_sun_nio_ch_FileDispatcherImpl_force0(JNIEnv *env, jobject this, jint fd = fdval(env, fdo); int result = 0; +#ifdef MACOSX + result = fcntl(fd, F_FULLFSYNC); + if (result == -1 && errno == ENOTSUP) { + /* Try fsync() in case F_FULLSYUNC is not implemented on the file system. */ + result = fsync(fd); + } +#else /* end MACOSX, begin not-MACOSX */ if (md == JNI_FALSE) { result = fdatasync(fd); } else { @@ -163,9 +170,10 @@ Java_sun_nio_ch_FileDispatcherImpl_force0(JNIEnv *env, jobject this, if (getfl >= 0 && (getfl & O_ACCMODE) == O_RDONLY) { return 0; } -#endif +#endif /* _AIX */ result = fsync(fd); } +#endif /* not-MACOSX */ return handle(env, result, "Force failed"); } From 8ddcf2aab04755816ef41d68a90ced6e6410f622 Mon Sep 17 00:00:00 2001 From: Jason Uh Date: Thu, 21 May 2015 14:18:33 -0700 Subject: [PATCH 69/70] 8079693: Add support for ECDSA P-384 and P-521 curves to XML Signature Reviewed-by: mullan --- .../xml/dsig/internal/dom/DOMKeyValue.java | 105 ++++++++---- .../xml/crypto/dsig/GenerationTests.java | 154 ++++++++++++++---- .../xml/crypto/dsig/ValidationTests.java | 4 +- .../data/signature-enveloping-p384-sha1.xml | 3 + .../data/signature-enveloping-p521-sha1.xml | 5 + 5 files changed, 205 insertions(+), 66 deletions(-) create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-p384-sha1.xml create mode 100644 jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-p521-sha1.xml diff --git a/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java index 08aee02be10..63d514e588d 100644 --- a/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java +++ b/jdk/src/java.xml.crypto/share/classes/org/jcp/xml/dsig/internal/dom/DOMKeyValue.java @@ -326,32 +326,54 @@ public abstract class DOMKeyValue extends DOMStructure implements KeyValue { private KeyFactory eckf; private ECParameterSpec ecParams; - // The supported curve, secp256r1 - private static final Curve SECP256R1; - static { - final String name, oid, sfield, a, b, x, y, n; - name = "secp256r1 [NIST P-256, X9.62 prime256v1]"; - oid = "1.2.840.10045.3.1.7"; - sfield = - "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"; - a = - "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"; - b = - "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"; - x = - "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"; - y = - "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"; - n = - "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"; - final int h = 1; + /* Supported curve, secp256r1 */ + private static final Curve SECP256R1 = initializeCurve( + "secp256r1 [NIST P-256, X9.62 prime256v1]", + "1.2.840.10045.3.1.7", + "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", + "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", + "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", + "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", + 1 + ); + /* Supported curve secp384r1 */ + private static final Curve SECP384R1 = initializeCurve( + "secp384r1 [NIST P-384]", + "1.3.132.0.34", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", + "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", + "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", + "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", + 1 + ); + + /* Supported curve secp521r1 */ + private static final Curve SECP521R1 = initializeCurve( + "secp521r1 [NIST P-521]", + "1.3.132.0.35", + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", + "0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", + "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", + "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", + 1 + ); + + private static Curve initializeCurve(String name, String oid, + String sfield, String a, String b, + String x, String y, String n, int h) { BigInteger p = bigInt(sfield); ECField field = new ECFieldFp(p); EllipticCurve curve = new EllipticCurve(field, bigInt(a), bigInt(b)); ECPoint g = new ECPoint(bigInt(x), bigInt(y)); - SECP256R1 = new Curve(name, oid, curve, g, bigInt(n), h); + return new Curve(name, oid, curve, g, bigInt(n), h); } EC(PublicKey key) throws KeyException { @@ -413,24 +435,45 @@ public abstract class DOMKeyValue extends DOMStructure implements KeyValue { } private static String getCurveOid(ECParameterSpec params) { - // Check that the params represent the secp256r1 curve - // If so, return the object identifier of the curve - int fieldSize = params.getCurve().getField().getFieldSize(); - if (SECP256R1.getCurve().getField().getFieldSize() == fieldSize - && SECP256R1.getCurve().equals(params.getCurve()) - && SECP256R1.getGenerator().equals(params.getGenerator()) - && SECP256R1.getOrder().equals(params.getOrder()) - && SECP256R1.getCofactor() == params.getCofactor()) { - return SECP256R1.getObjectId(); + // Check that the params represent one of the supported + // curves. If there is a match, return the object identifier + // of the curve. + Curve match; + if (matchCurve(params, SECP256R1)) { + match = SECP256R1; + } else if (matchCurve(params, SECP384R1)) { + match = SECP384R1; + } else if (matchCurve(params, SECP521R1)) { + match = SECP521R1; + } else { + return null; + } + return match.getObjectId(); + } + + private static boolean matchCurve(ECParameterSpec params, Curve curve) { + int fieldSize = params.getCurve().getField().getFieldSize(); + if (curve.getCurve().getField().getFieldSize() == fieldSize + && curve.getCurve().equals(params.getCurve()) + && curve.getGenerator().equals(params.getGenerator()) + && curve.getOrder().equals(params.getOrder()) + && curve.getCofactor() == params.getCofactor()) { + return true; + } else { + return false; } - return null; } private static ECParameterSpec getECParameterSpec(String oid) { if (oid.equals(SECP256R1.getObjectId())) { return SECP256R1; + } else if (oid.equals(SECP384R1.getObjectId())) { + return SECP384R1; + } else if (oid.equals(SECP521R1.getObjectId())) { + return SECP521R1; + } else { + return null; } - return null; } void marshalPublicKey(Node parent, Document doc, String dsPrefix, diff --git a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java index 068cd2a86a2..945b1cdb802 100644 --- a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java +++ b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java @@ -24,7 +24,7 @@ /** * @test * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349 8046949 - * 8046724 + * 8046724 8079693 * @summary Basic unit tests for generating XML Signatures with JSR 105 * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java * X509KeySelector.java GenerationTests.java @@ -92,7 +92,8 @@ public class GenerationTests { rsaSha256, rsaSha384, rsaSha512, ecdsaSha1; private static DigestMethod sha1, sha256, sha384, sha512; - private static KeyInfo dsa1024, dsa2048, rsa, rsa1024, p256ki; + private static KeyInfo dsa1024, dsa2048, rsa, rsa1024, + p256ki, p384ki, p521ki; private static KeySelector kvks = new KeySelectors.KeyValueKeySelector(); private static KeySelector sks; private static Key signingKey; @@ -131,6 +132,8 @@ public class GenerationTests { test_create_signature_enveloping_hmac_sha512(); test_create_signature_enveloping_rsa(); test_create_signature_enveloping_p256_sha1(); + test_create_signature_enveloping_p384_sha1(); + test_create_signature_enveloping_p521_sha1(); test_create_signature_external_b64_dsa(); test_create_signature_external_dsa(); test_create_signature_keyname(); @@ -186,7 +189,11 @@ public class GenerationTests { rsa1024 = kifac.newKeyInfo(Collections.singletonList (kifac.newKeyValue(getPublicKey("RSA", 1024)))); p256ki = kifac.newKeyInfo(Collections.singletonList - (kifac.newKeyValue(getECPublicKey()))); + (kifac.newKeyValue(getECPublicKey("P256")))); + p384ki = kifac.newKeyInfo(Collections.singletonList + (kifac.newKeyValue(getECPublicKey("P384")))); + p521ki = kifac.newKeyInfo(Collections.singletonList + (kifac.newKeyValue(getECPublicKey("P521")))); rsaSha1 = fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null); rsaSha256 = fac.newSignatureMethod ("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null); @@ -359,7 +366,21 @@ public class GenerationTests { static void test_create_signature_enveloping_p256_sha1() throws Exception { System.out.println("* Generating signature-enveloping-p256-sha1.xml"); test_create_signature_enveloping(sha1, ecdsaSha1, p256ki, - getECPrivateKey(), kvks, false); + getECPrivateKey("P256"), kvks, false); + System.out.println(); + } + + static void test_create_signature_enveloping_p384_sha1() throws Exception { + System.out.println("* Generating signature-enveloping-p384-sha1.xml"); + test_create_signature_enveloping(sha1, ecdsaSha1, p384ki, + getECPrivateKey("P384"), kvks, false); + System.out.println(); + } + + static void test_create_signature_enveloping_p521_sha1() throws Exception { + System.out.println("* Generating signature-enveloping-p521-sha1.xml"); + test_create_signature_enveloping(sha1, ecdsaSha1, p521ki, + getECPrivateKey("P521"), kvks, false); System.out.println(); } @@ -1189,37 +1210,63 @@ public class GenerationTests { "237008997971129772408397621801631622129297063463868593083106979716" + "204903524890556839550490384015324575598723478554854070823335021842" + "210112348400928769"; - private static final String EC_X = + private static final String EC_P256_X = "335863644451761614592446380116804721648611739647823420286081723541" + "6166183710"; - private static final String EC_Y = + private static final String EC_P256_Y = "951559601159729477487064127150143688502130342917782252098602422796" + "95457910701"; - private static final String EC_S = + private static final String EC_P256_S = "425976209773168452211813225517384419928639977904006759709292218082" + "7440083936"; - private static final ECParameterSpec EC_PARAMS; + private static final ECParameterSpec EC_P256_PARAMS = initECParams( + "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", + "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", + "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", + "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", + "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", + "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", + 1 + ); + private static final String EC_P384_X = + "12144058647679082341340699736608428955270957565259459672517275506071643671835484144490620216582303669654008841724053"; + private static final String EC_P384_Y = + "18287745972107701566600963632634101287058332546756092926848497481238534346489545826483592906634896557151987868614320"; + private static final String EC_P384_S = + "10307785759830534742680442271492590599236624208247590184679565032330507874096079979152605984203102224450595283943382"; + private static final ECParameterSpec EC_P384_PARAMS = initECParams( + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", + "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", + "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", + "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", + "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", + 1 + ); + private static final String EC_P521_X = + "4157918188927862838251799402582135611021257663417126086145819679867926857146776190737187582274664373117054717389603317411991660346043842712448912355335343997"; + private static final String EC_P521_Y = + "4102838062751704796157456866854813794620023146924181568434486703918224542844053923233919899911519054998554969832861957437850996213216829205401947264294066288"; + private static final String EC_P521_S = + "4857798533181496041050215963883119936300918353498701880968530610687256097257307590162398707429640390843595868713096292822034014722985178583665959048714417342"; + private static final ECParameterSpec EC_P521_PARAMS = initECParams( + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", + "0051953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", + "00C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", + "011839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", + "01FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", + 1 + ); - static { - final String ec_sfield, ec_a, ec_b, ec_gx, ec_gy, ec_n; - ec_sfield = - "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF"; - ec_a = - "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC"; - ec_b = - "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B"; - ec_gx = - "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296"; - ec_gy = - "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5"; - ec_n = - "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"; - final int ec_h = 1; - final ECField ec_field = new ECFieldFp(bigInt(ec_sfield)); - final EllipticCurve ec_curve = new EllipticCurve(ec_field, - bigInt(ec_a), bigInt(ec_b)); - final ECPoint ec_g = new ECPoint(bigInt(ec_gx), bigInt(ec_gy)); - EC_PARAMS = new ECParameterSpec(ec_curve, ec_g, bigInt(ec_n), ec_h); + private static ECParameterSpec initECParams( + String sfield, String a, String b, String gx, String gy, + String n, int h) { + ECField field = new ECFieldFp(bigInt(sfield)); + EllipticCurve curve = new EllipticCurve(field, + bigInt(a), bigInt(b)); + ECPoint g = new ECPoint(bigInt(gx), bigInt(gy)); + return new ECParameterSpec(curve, g, bigInt(n), h); } private static BigInteger bigInt(String s) { @@ -1253,11 +1300,32 @@ public class GenerationTests { return kf.generatePublic(kspec); } - private static PublicKey getECPublicKey() throws Exception { + private static PublicKey getECPublicKey(String curve) throws Exception { KeyFactory kf = KeyFactory.getInstance("EC"); - KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(EC_X), - new BigInteger(EC_Y)), - EC_PARAMS); + String x, y; + ECParameterSpec params; + switch (curve) { + case "P256": + x = EC_P256_X; + y = EC_P256_Y; + params = EC_P256_PARAMS; + break; + case "P384": + x = EC_P384_X; + y = EC_P384_Y; + params = EC_P384_PARAMS; + break; + case "P521": + x = EC_P521_X; + y = EC_P521_Y; + params = EC_P521_PARAMS; + break; + default: + throw new Exception("Unsupported curve: " + curve); + } + KeySpec kspec = new ECPublicKeySpec(new ECPoint(new BigInteger(x), + new BigInteger(y)), + params); return kf.generatePublic(kspec); } @@ -1287,9 +1355,27 @@ public class GenerationTests { return kf.generatePrivate(kspec); } - private static PrivateKey getECPrivateKey() throws Exception { + private static PrivateKey getECPrivateKey(String curve) throws Exception { + String s; + ECParameterSpec params; + switch (curve) { + case "P256": + s = EC_P256_S; + params = EC_P256_PARAMS; + break; + case "P384": + s = EC_P384_S; + params = EC_P384_PARAMS; + break; + case "P521": + s = EC_P521_S; + params = EC_P521_PARAMS; + break; + default: + throw new Exception("Unsupported curve: " + curve); + } KeyFactory kf = KeyFactory.getInstance("EC"); - KeySpec kspec = new ECPrivateKeySpec(new BigInteger(EC_S), EC_PARAMS); + KeySpec kspec = new ECPrivateKeySpec(new BigInteger(s), params); return kf.generatePrivate(kspec); } diff --git a/jdk/test/javax/xml/crypto/dsig/ValidationTests.java b/jdk/test/javax/xml/crypto/dsig/ValidationTests.java index d7384815f44..5413d28d215 100644 --- a/jdk/test/javax/xml/crypto/dsig/ValidationTests.java +++ b/jdk/test/javax/xml/crypto/dsig/ValidationTests.java @@ -23,7 +23,7 @@ /** * @test - * @bug 4635230 6365103 6366054 6824440 7131084 8046724 + * @bug 4635230 6365103 6366054 6824440 7131084 8046724 8079693 * @summary Basic unit tests for validating XML Signatures with JSR 105 * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java * X509KeySelector.java ValidationTests.java @@ -100,6 +100,8 @@ public class ValidationTests { new Test("signature-enveloping-dsa.xml", KVKS), new Test("signature-enveloping-rsa.xml", KVKS), new Test("signature-enveloping-p256-sha1.xml", KVKS), + new Test("signature-enveloping-p384-sha1.xml", KVKS), + new Test("signature-enveloping-p521-sha1.xml", KVKS), new Test("signature-enveloping-hmac-sha1.xml", SKKS), new Test("signature-external-dsa.xml", KVKS), new Test("signature-external-b64-dsa.xml", KVKS), diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-p384-sha1.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-p384-sha1.xml new file mode 100644 index 00000000000..115a5ae5c0a --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-p384-sha1.xml @@ -0,0 +1,3 @@ +7/XTsHaBSOnJ/jXD5v0zL6VKYsk=s15F4ng4a+TfNHlK+y18igexSe3wRspeyQi8hwhyMUh6I6kyzxO1wcqRulFyBNwh/Dplht+WS9dO +GwL4xfDfozKss36ZsHACI3EYe0QI6pN7hcKp511muPI+cmoZzIN/BE7my2bSrGpZ3jNFQ1I6baGP9CE4AIMIyN/ugWhbsCQz8ntwXf15NStBt9MBXolglXbRYMqV8vYB +f7UJ1ixum8hzcEvgShn0L9l1VkWaU4bYr/Ss9ApimDvbF2g6Mw++sA==some text \ No newline at end of file diff --git a/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-p521-sha1.xml b/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-p521-sha1.xml new file mode 100644 index 00000000000..a4b60282cba --- /dev/null +++ b/jdk/test/javax/xml/crypto/dsig/data/signature-enveloping-p521-sha1.xml @@ -0,0 +1,5 @@ +7/XTsHaBSOnJ/jXD5v0zL6VKYsk=AaVkRumHXD0vVtkn2ogcAoByVge1KWGVWE6vph+xr/hcZTqNNaiIyXb7Itu0FBHD9M47T/CuM7y4 +m60zEssaaHl0AUNm7xGpZy7Heqaoibb/gMU1ErrfSNs7yuPG/TCqs8YAd3RGnc6ZbloitWpycGCU +LS4xxKms0KeRnbVpjk5OeVfKBAE2HJjBQRbl0sdGa1+1cJwxtPJXcnrRdmRXs6TEQmU97US+CK0vsoDQtlnXxDx37mawN7Sh4Atp +CUeYBbzvBmwPfQEyAO600W9xn4s5wSQvXod8v8brh5ISXhxYPFy3SCcGUxbQYqrVUnBrIXH8WEQX +K0/T+FdF4CzlQswJY0UZGeQYcA==some text \ No newline at end of file From 9e2b6dfd081da3e19f2e149827426573dec06cbe Mon Sep 17 00:00:00 2001 From: Xueming Shen Date: Thu, 21 May 2015 15:42:30 -0700 Subject: [PATCH 70/70] 8080248: Coding regression in HKSCS charsets To update the sp correctly when encoding supplementary characters Reviewed-by: martin --- .../java.base/share/classes/sun/nio/cs/HKSCS.java | 1 - jdk/test/sun/nio/cs/TestStringCoding.java | 13 ++++++++++++- 2 files changed, 12 insertions(+), 2 deletions(-) diff --git a/jdk/src/java.base/share/classes/sun/nio/cs/HKSCS.java b/jdk/src/java.base/share/classes/sun/nio/cs/HKSCS.java index ba22341ae85..773c7a08a36 100644 --- a/jdk/src/java.base/share/classes/sun/nio/cs/HKSCS.java +++ b/jdk/src/java.base/share/classes/sun/nio/cs/HKSCS.java @@ -378,7 +378,6 @@ public class HKSCS { dst[dp++] = repl[1]; continue; } - sp++; } if (bb > MAX_SINGLEBYTE) { // DoubleByte dst[dp++] = (byte)(bb >> 8); diff --git a/jdk/test/sun/nio/cs/TestStringCoding.java b/jdk/test/sun/nio/cs/TestStringCoding.java index 7c18a3596c6..95d273dd5cb 100644 --- a/jdk/test/sun/nio/cs/TestStringCoding.java +++ b/jdk/test/sun/nio/cs/TestStringCoding.java @@ -22,7 +22,7 @@ */ /* @test - @bug 6636323 6636319 7040220 7096080 7183053 + @bug 6636323 6636319 7040220 7096080 7183053 8080248 @summary Test if StringCoding and NIO result have the same de/encoding result * @run main/othervm/timeout=2000 TestStringCoding * @key randomness @@ -200,6 +200,17 @@ public class TestStringCoding { */ } + //encode mappable surrogates for hkscs + if (cs.name().equals("Big5-HKSCS") || cs.name().equals("x-MS950-HKSCS")) { + String str = "ab\uD840\uDD0Ccd"; + byte[] expected = new byte[] {(byte)'a', (byte)'b', + (byte)0x88, (byte)0x45, (byte)'c', (byte)'d' }; + if (!Arrays.equals(str.getBytes(cs.name()), expected) || + !Arrays.equals(str.getBytes(cs), expected)) { + throw new RuntimeException("encode(surrogates) failed -> " + + cs.name()); + } + } } static class PermissiveSecurityManger extends SecurityManager {