diff --git a/.hgtags b/.hgtags index 1e4981545c3..843dc9ea972 100644 --- a/.hgtags +++ b/.hgtags @@ -218,3 +218,7 @@ b72ae39e1329fefae50d4690db4fde43f3841a95 jdk8-b93 0d804e3b955dce406af6a79ac1cc35c696aff7fb jdk8-b94 49fe9c8049132647ad38837a877dd473e6c9b0e5 jdk8-b95 ea73f01b9053e7165e7ba80f242bafecbc6af712 jdk8-b96 +0a85476a0b9cb876d5666d45097dac68bef3fce1 jdk8-b97 +711eb4aa87de68de78250e0549980936bab53d54 jdk8-b98 +2d3875b0d18b3ad1c2bebf385a697e309e4005a4 jdk8-b99 +3d34036aae4ea90b2ca59712d5a69db3221f0875 jdk8-b100 diff --git a/.hgtags-top-repo b/.hgtags-top-repo index 03af8b5ef30..a19c8745350 100644 --- a/.hgtags-top-repo +++ b/.hgtags-top-repo @@ -218,3 +218,7 @@ cb51fb4789ac0b8be4056482077ddfb8f3bd3805 jdk8-b91 50d2bde060f2a9bbbe4da0c8986e20aca61f2e2e jdk8-b94 785d07fe38901ecc1b7e0145e53e1c3da9361fee jdk8-b95 c156084add486f941c12d886a0b1b2854795d557 jdk8-b96 +a1c1e8bf71f354f3aec0214cf13d6668811e021d jdk8-b97 +0d0c983a817bbe8518a5ff201306334a8de267f2 jdk8-b98 +59dc9da813794c924a0383c2a6241af94defdfed jdk8-b99 +d2dcb110e9dbaf9903c05b211df800e78e4b394e jdk8-b100 diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh index b9c2b38a47e..1f084da68c9 100644 --- a/common/autoconf/generated-configure.sh +++ b/common/autoconf/generated-configure.sh @@ -1,6 +1,6 @@ #! /bin/sh # Guess values for system-dependent variables and create Makefiles. -# Generated by GNU Autoconf 2.67 for OpenJDK jdk8. +# Generated by GNU Autoconf 2.68 for OpenJDK jdk8. # # Report bugs to . # @@ -91,6 +91,7 @@ fi IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. +as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -216,11 +217,18 @@ IFS=$as_save_IFS # We cannot yet assume a decent shell, so we have to provide a # neutralization value for shells without unset; and this also # works around shells that cannot unset nonexistent variables. + # Preserve -v and -x to the replacement shell. BASH_ENV=/dev/null ENV=/dev/null (unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV export CONFIG_SHELL - exec "$CONFIG_SHELL" "$as_myself" ${1+"$@"} + case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; + esac + exec "$CONFIG_SHELL" $as_opts "$as_myself" ${1+"$@"} fi if test x$as_have_required = xno; then : @@ -1461,7 +1469,7 @@ Try \`$0 --help' for more information" $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 - : ${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option} + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" ;; esac @@ -1897,7 +1905,7 @@ test -n "$ac_init_help" && exit $ac_status if $ac_init_version; then cat <<\_ACEOF OpenJDK configure jdk8 -generated by GNU Autoconf 2.67 +generated by GNU Autoconf 2.68 Copyright (C) 2010 Free Software Foundation, Inc. This configure script is free software; the Free Software Foundation @@ -1943,7 +1951,7 @@ sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_compile @@ -1981,7 +1989,7 @@ sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_compile @@ -2019,7 +2027,7 @@ sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_objc_try_compile @@ -2056,7 +2064,7 @@ sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_c_try_cpp @@ -2093,7 +2101,7 @@ sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=1 fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_cpp @@ -2106,10 +2114,10 @@ fi ac_fn_cxx_check_header_mongrel () { as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack - if eval "test \"\${$3+set}\"" = set; then : + if eval \${$3+:} false; then : { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } -if eval "test \"\${$3+set}\"" = set; then : +if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 fi eval ac_res=\$$3 @@ -2176,7 +2184,7 @@ $as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } -if eval "test \"\${$3+set}\"" = set; then : +if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else eval "$3=\$ac_header_compiler" @@ -2185,7 +2193,7 @@ eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_cxx_check_header_mongrel @@ -2226,7 +2234,7 @@ sed 's/^/| /' conftest.$ac_ext >&5 ac_retval=$ac_status fi rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_run @@ -2240,7 +2248,7 @@ ac_fn_cxx_check_header_compile () as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } -if eval "test \"\${$3+set}\"" = set; then : +if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -2258,7 +2266,7 @@ fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_cxx_check_header_compile @@ -2435,7 +2443,7 @@ rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ rm -f conftest.val fi - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_compute_int @@ -2481,7 +2489,7 @@ fi # interfere with the next link command; also delete a directory that is # left behind by Apple's compiler. We do this before executing the actions. rm -rf conftest.dSYM conftest_ipa8_conftest.oo - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno as_fn_set_status $ac_retval } # ac_fn_cxx_try_link @@ -2494,7 +2502,7 @@ ac_fn_cxx_check_func () as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } -if eval "test \"\${$3+set}\"" = set; then : +if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -2549,7 +2557,7 @@ fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_cxx_check_func @@ -2562,7 +2570,7 @@ ac_fn_c_check_header_compile () as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 $as_echo_n "checking for $2... " >&6; } -if eval "test \"\${$3+set}\"" = set; then : +if eval \${$3+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -2580,7 +2588,7 @@ fi eval ac_res=\$$3 { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 $as_echo "$ac_res" >&6; } - eval $as_lineno_stack; test "x$as_lineno_stack" = x && { as_lineno=; unset as_lineno;} + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno } # ac_fn_c_check_header_compile cat >config.log <<_ACEOF @@ -2588,7 +2596,7 @@ This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by OpenJDK $as_me jdk8, which was -generated by GNU Autoconf 2.67. Invocation command line was +generated by GNU Autoconf 2.68. Invocation command line was $ $0 $@ @@ -2846,7 +2854,7 @@ $as_echo "$as_me: loading site script $ac_site_file" >&6;} || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "failed to load site script $ac_site_file -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } fi done @@ -3786,7 +3794,7 @@ fi #CUSTOM_AUTOCONF_INCLUDE # Do not change or remove the following line, it is needed for consistency checks: -DATE_WHEN_GENERATED=1372770384 +DATE_WHEN_GENERATED=1373384053 ############################################################################### # @@ -3824,7 +3832,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_BASENAME+set}" = set; then : +if ${ac_cv_path_BASENAME+:} false; then : $as_echo_n "(cached) " >&6 else case $BASENAME in @@ -3883,7 +3891,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_BASH+set}" = set; then : +if ${ac_cv_path_BASH+:} false; then : $as_echo_n "(cached) " >&6 else case $BASH in @@ -3942,7 +3950,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CAT+set}" = set; then : +if ${ac_cv_path_CAT+:} false; then : $as_echo_n "(cached) " >&6 else case $CAT in @@ -4001,7 +4009,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CHMOD+set}" = set; then : +if ${ac_cv_path_CHMOD+:} false; then : $as_echo_n "(cached) " >&6 else case $CHMOD in @@ -4060,7 +4068,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CMP+set}" = set; then : +if ${ac_cv_path_CMP+:} false; then : $as_echo_n "(cached) " >&6 else case $CMP in @@ -4119,7 +4127,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_COMM+set}" = set; then : +if ${ac_cv_path_COMM+:} false; then : $as_echo_n "(cached) " >&6 else case $COMM in @@ -4178,7 +4186,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CP+set}" = set; then : +if ${ac_cv_path_CP+:} false; then : $as_echo_n "(cached) " >&6 else case $CP in @@ -4237,7 +4245,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CPIO+set}" = set; then : +if ${ac_cv_path_CPIO+:} false; then : $as_echo_n "(cached) " >&6 else case $CPIO in @@ -4296,7 +4304,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CUT+set}" = set; then : +if ${ac_cv_path_CUT+:} false; then : $as_echo_n "(cached) " >&6 else case $CUT in @@ -4355,7 +4363,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_DATE+set}" = set; then : +if ${ac_cv_path_DATE+:} false; then : $as_echo_n "(cached) " >&6 else case $DATE in @@ -4414,7 +4422,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_DIFF+set}" = set; then : +if ${ac_cv_path_DIFF+:} false; then : $as_echo_n "(cached) " >&6 else case $DIFF in @@ -4473,7 +4481,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_DIRNAME+set}" = set; then : +if ${ac_cv_path_DIRNAME+:} false; then : $as_echo_n "(cached) " >&6 else case $DIRNAME in @@ -4532,7 +4540,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ECHO+set}" = set; then : +if ${ac_cv_path_ECHO+:} false; then : $as_echo_n "(cached) " >&6 else case $ECHO in @@ -4591,7 +4599,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_EXPR+set}" = set; then : +if ${ac_cv_path_EXPR+:} false; then : $as_echo_n "(cached) " >&6 else case $EXPR in @@ -4650,7 +4658,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_FILE+set}" = set; then : +if ${ac_cv_path_FILE+:} false; then : $as_echo_n "(cached) " >&6 else case $FILE in @@ -4709,7 +4717,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_FIND+set}" = set; then : +if ${ac_cv_path_FIND+:} false; then : $as_echo_n "(cached) " >&6 else case $FIND in @@ -4768,7 +4776,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_HEAD+set}" = set; then : +if ${ac_cv_path_HEAD+:} false; then : $as_echo_n "(cached) " >&6 else case $HEAD in @@ -4827,7 +4835,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_LN+set}" = set; then : +if ${ac_cv_path_LN+:} false; then : $as_echo_n "(cached) " >&6 else case $LN in @@ -4886,7 +4894,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_LS+set}" = set; then : +if ${ac_cv_path_LS+:} false; then : $as_echo_n "(cached) " >&6 else case $LS in @@ -4945,7 +4953,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_MKDIR+set}" = set; then : +if ${ac_cv_path_MKDIR+:} false; then : $as_echo_n "(cached) " >&6 else case $MKDIR in @@ -5004,7 +5012,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_MKTEMP+set}" = set; then : +if ${ac_cv_path_MKTEMP+:} false; then : $as_echo_n "(cached) " >&6 else case $MKTEMP in @@ -5063,7 +5071,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_MV+set}" = set; then : +if ${ac_cv_path_MV+:} false; then : $as_echo_n "(cached) " >&6 else case $MV in @@ -5122,7 +5130,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_PRINTF+set}" = set; then : +if ${ac_cv_path_PRINTF+:} false; then : $as_echo_n "(cached) " >&6 else case $PRINTF in @@ -5181,7 +5189,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_RM+set}" = set; then : +if ${ac_cv_path_RM+:} false; then : $as_echo_n "(cached) " >&6 else case $RM in @@ -5240,7 +5248,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_SH+set}" = set; then : +if ${ac_cv_path_SH+:} false; then : $as_echo_n "(cached) " >&6 else case $SH in @@ -5299,7 +5307,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_SORT+set}" = set; then : +if ${ac_cv_path_SORT+:} false; then : $as_echo_n "(cached) " >&6 else case $SORT in @@ -5358,7 +5366,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_TAIL+set}" = set; then : +if ${ac_cv_path_TAIL+:} false; then : $as_echo_n "(cached) " >&6 else case $TAIL in @@ -5417,7 +5425,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_TAR+set}" = set; then : +if ${ac_cv_path_TAR+:} false; then : $as_echo_n "(cached) " >&6 else case $TAR in @@ -5476,7 +5484,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_TEE+set}" = set; then : +if ${ac_cv_path_TEE+:} false; then : $as_echo_n "(cached) " >&6 else case $TEE in @@ -5535,7 +5543,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_TOUCH+set}" = set; then : +if ${ac_cv_path_TOUCH+:} false; then : $as_echo_n "(cached) " >&6 else case $TOUCH in @@ -5594,7 +5602,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_TR+set}" = set; then : +if ${ac_cv_path_TR+:} false; then : $as_echo_n "(cached) " >&6 else case $TR in @@ -5653,7 +5661,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_UNAME+set}" = set; then : +if ${ac_cv_path_UNAME+:} false; then : $as_echo_n "(cached) " >&6 else case $UNAME in @@ -5712,7 +5720,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_UNIQ+set}" = set; then : +if ${ac_cv_path_UNIQ+:} false; then : $as_echo_n "(cached) " >&6 else case $UNIQ in @@ -5771,7 +5779,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_WC+set}" = set; then : +if ${ac_cv_path_WC+:} false; then : $as_echo_n "(cached) " >&6 else case $WC in @@ -5830,7 +5838,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_WHICH+set}" = set; then : +if ${ac_cv_path_WHICH+:} false; then : $as_echo_n "(cached) " >&6 else case $WHICH in @@ -5889,7 +5897,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_XARGS+set}" = set; then : +if ${ac_cv_path_XARGS+:} false; then : $as_echo_n "(cached) " >&6 else case $XARGS in @@ -5949,7 +5957,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_AWK+set}" = set; then : +if ${ac_cv_prog_AWK+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AWK"; then @@ -5999,7 +6007,7 @@ $as_echo "$as_me: Could not find $PROG_NAME!" >&6;} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 $as_echo_n "checking for grep that handles long lines and -e... " >&6; } -if test "${ac_cv_path_GREP+set}" = set; then : +if ${ac_cv_path_GREP+:} false; then : $as_echo_n "(cached) " >&6 else if test -z "$GREP"; then @@ -6074,7 +6082,7 @@ $as_echo "$as_me: Could not find $PROG_NAME!" >&6;} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 $as_echo_n "checking for egrep... " >&6; } -if test "${ac_cv_path_EGREP+set}" = set; then : +if ${ac_cv_path_EGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 @@ -6153,7 +6161,7 @@ $as_echo "$as_me: Could not find $PROG_NAME!" >&6;} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for fgrep" >&5 $as_echo_n "checking for fgrep... " >&6; } -if test "${ac_cv_path_FGREP+set}" = set; then : +if ${ac_cv_path_FGREP+:} false; then : $as_echo_n "(cached) " >&6 else if echo 'ab*c' | $GREP -F 'ab*c' >/dev/null 2>&1 @@ -6232,7 +6240,7 @@ $as_echo "$as_me: Could not find $PROG_NAME!" >&6;} { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a sed that does not truncate output" >&5 $as_echo_n "checking for a sed that does not truncate output... " >&6; } -if test "${ac_cv_path_SED+set}" = set; then : +if ${ac_cv_path_SED+:} false; then : $as_echo_n "(cached) " >&6 else ac_script=s/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb/ @@ -6318,7 +6326,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_NAWK+set}" = set; then : +if ${ac_cv_path_NAWK+:} false; then : $as_echo_n "(cached) " >&6 else case $NAWK in @@ -6382,7 +6390,7 @@ THEPWDCMD=pwd set dummy cygpath; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CYGPATH+set}" = set; then : +if ${ac_cv_path_CYGPATH+:} false; then : $as_echo_n "(cached) " >&6 else case $CYGPATH in @@ -6422,7 +6430,7 @@ fi set dummy readlink; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_READLINK+set}" = set; then : +if ${ac_cv_path_READLINK+:} false; then : $as_echo_n "(cached) " >&6 else case $READLINK in @@ -6462,7 +6470,7 @@ fi set dummy df; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_DF+set}" = set; then : +if ${ac_cv_path_DF+:} false; then : $as_echo_n "(cached) " >&6 else case $DF in @@ -6502,7 +6510,7 @@ fi set dummy SetFile; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_SETFILE+set}" = set; then : +if ${ac_cv_path_SETFILE+:} false; then : $as_echo_n "(cached) " >&6 else case $SETFILE in @@ -6548,7 +6556,7 @@ $SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || { $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 $as_echo_n "checking build system type... " >&6; } -if test "${ac_cv_build+set}" = set; then : +if ${ac_cv_build+:} false; then : $as_echo_n "(cached) " >&6 else ac_build_alias=$build_alias @@ -6564,7 +6572,7 @@ fi $as_echo "$ac_cv_build" >&6; } case $ac_cv_build in *-*-*) ;; -*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5 ;; +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; esac build=$ac_cv_build ac_save_IFS=$IFS; IFS='-' @@ -6582,7 +6590,7 @@ case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 $as_echo_n "checking host system type... " >&6; } -if test "${ac_cv_host+set}" = set; then : +if ${ac_cv_host+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$host_alias" = x; then @@ -6597,7 +6605,7 @@ fi $as_echo "$ac_cv_host" >&6; } case $ac_cv_host in *-*-*) ;; -*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5 ;; +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; esac host=$ac_cv_host ac_save_IFS=$IFS; IFS='-' @@ -6615,7 +6623,7 @@ case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac { $as_echo "$as_me:${as_lineno-$LINENO}: checking target system type" >&5 $as_echo_n "checking target system type... " >&6; } -if test "${ac_cv_target+set}" = set; then : +if ${ac_cv_target+:} false; then : $as_echo_n "(cached) " >&6 else if test "x$target_alias" = x; then @@ -6630,7 +6638,7 @@ fi $as_echo "$ac_cv_target" >&6; } case $ac_cv_target in *-*-*) ;; -*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5 ;; +*) as_fn_error $? "invalid value of canonical target" "$LINENO" 5;; esac target=$ac_cv_target ac_save_IFS=$IFS; IFS='-' @@ -8156,7 +8164,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_PKGHANDLER+set}" = set; then : +if ${ac_cv_prog_PKGHANDLER+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$PKGHANDLER"; then @@ -8521,7 +8529,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CHECK_GMAKE+set}" = set; then : +if ${ac_cv_path_CHECK_GMAKE+:} false; then : $as_echo_n "(cached) " >&6 else case $CHECK_GMAKE in @@ -8875,7 +8883,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CHECK_MAKE+set}" = set; then : +if ${ac_cv_path_CHECK_MAKE+:} false; then : $as_echo_n "(cached) " >&6 else case $CHECK_MAKE in @@ -9234,7 +9242,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CHECK_TOOLSDIR_GMAKE+set}" = set; then : +if ${ac_cv_path_CHECK_TOOLSDIR_GMAKE+:} false; then : $as_echo_n "(cached) " >&6 else case $CHECK_TOOLSDIR_GMAKE in @@ -9587,7 +9595,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CHECK_TOOLSDIR_MAKE+set}" = set; then : +if ${ac_cv_path_CHECK_TOOLSDIR_MAKE+:} false; then : $as_echo_n "(cached) " >&6 else case $CHECK_TOOLSDIR_MAKE in @@ -9983,7 +9991,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_UNZIP+set}" = set; then : +if ${ac_cv_path_UNZIP+:} false; then : $as_echo_n "(cached) " >&6 else case $UNZIP in @@ -10042,7 +10050,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ZIP+set}" = set; then : +if ${ac_cv_path_ZIP+:} false; then : $as_echo_n "(cached) " >&6 else case $ZIP in @@ -10101,7 +10109,7 @@ $as_echo "$as_me: Could not find $PROG_NAME!" >&6;} set dummy ldd; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_LDD+set}" = set; then : +if ${ac_cv_path_LDD+:} false; then : $as_echo_n "(cached) " >&6 else case $LDD in @@ -10147,7 +10155,7 @@ fi set dummy otool; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_OTOOL+set}" = set; then : +if ${ac_cv_path_OTOOL+:} false; then : $as_echo_n "(cached) " >&6 else case $OTOOL in @@ -10192,7 +10200,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_READELF+set}" = set; then : +if ${ac_cv_path_READELF+:} false; then : $as_echo_n "(cached) " >&6 else case $READELF in @@ -10235,7 +10243,7 @@ done set dummy hg; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_HG+set}" = set; then : +if ${ac_cv_path_HG+:} false; then : $as_echo_n "(cached) " >&6 else case $HG in @@ -10275,7 +10283,7 @@ fi set dummy stat; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_STAT+set}" = set; then : +if ${ac_cv_path_STAT+:} false; then : $as_echo_n "(cached) " >&6 else case $STAT in @@ -10315,7 +10323,7 @@ fi set dummy time; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_TIME+set}" = set; then : +if ${ac_cv_path_TIME+:} false; then : $as_echo_n "(cached) " >&6 else case $TIME in @@ -10368,7 +10376,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_COMM+set}" = set; then : +if ${ac_cv_path_COMM+:} false; then : $as_echo_n "(cached) " >&6 else case $COMM in @@ -10430,7 +10438,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_XATTR+set}" = set; then : +if ${ac_cv_path_XATTR+:} false; then : $as_echo_n "(cached) " >&6 else case $XATTR in @@ -10486,7 +10494,7 @@ $as_echo "$as_me: Could not find $PROG_NAME!" >&6;} set dummy codesign; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CODESIGN+set}" = set; then : +if ${ac_cv_path_CODESIGN+:} false; then : $as_echo_n "(cached) " >&6 else case $CODESIGN in @@ -10550,7 +10558,7 @@ if test "x$ac_cv_env_PKG_CONFIG_set" != "xset"; then set dummy ${ac_tool_prefix}pkg-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_PKG_CONFIG+set}" = set; then : +if ${ac_cv_path_PKG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $PKG_CONFIG in @@ -10593,7 +10601,7 @@ if test -z "$ac_cv_path_PKG_CONFIG"; then set dummy pkg-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_ac_pt_PKG_CONFIG+set}" = set; then : +if ${ac_cv_path_ac_pt_PKG_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else case $ac_pt_PKG_CONFIG in @@ -10766,7 +10774,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_BDEPS_UNZIP+set}" = set; then : +if ${ac_cv_prog_BDEPS_UNZIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$BDEPS_UNZIP"; then @@ -10812,7 +10820,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_BDEPS_FTP+set}" = set; then : +if ${ac_cv_prog_BDEPS_FTP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$BDEPS_FTP"; then @@ -12108,7 +12116,7 @@ $as_echo "$BOOT_JDK_VERSION" >&6; } set dummy javac; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_JAVAC_CHECK+set}" = set; then : +if ${ac_cv_path_JAVAC_CHECK+:} false; then : $as_echo_n "(cached) " >&6 else case $JAVAC_CHECK in @@ -12148,7 +12156,7 @@ fi set dummy java; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_JAVA_CHECK+set}" = set; then : +if ${ac_cv_path_JAVA_CHECK+:} false; then : $as_echo_n "(cached) " >&6 else case $JAVA_CHECK in @@ -16477,7 +16485,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_JTREGEXE+set}" = set; then : +if ${ac_cv_path_JTREGEXE+:} false; then : $as_echo_n "(cached) " >&6 else case $JTREGEXE in @@ -16545,7 +16553,7 @@ if test "x$OPENJDK_TARGET_OS" = "xwindows"; then set dummy link; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CYGWIN_LINK+set}" = set; then : +if ${ac_cv_path_CYGWIN_LINK+:} false; then : $as_echo_n "(cached) " >&6 else case $CYGWIN_LINK in @@ -17319,6 +17327,8 @@ $as_echo "ok" >&6; } # Remove any trailing \ from INCLUDE and LIB to avoid trouble in spec.gmk. VS_INCLUDE=`$ECHO "$INCLUDE" | $SED 's/\\\\$//'` VS_LIB=`$ECHO "$LIB" | $SED 's/\\\\$//'` + # Remove any paths containing # (typically F#) as that messes up make + PATH=`$ECHO "$PATH" | $SED 's/[^:#]*#[^:]*://g'` VS_PATH="$PATH" @@ -17986,7 +17996,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_BUILD_CC+set}" = set; then : +if ${ac_cv_path_BUILD_CC+:} false; then : $as_echo_n "(cached) " >&6 else case $BUILD_CC in @@ -18297,7 +18307,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_BUILD_CXX+set}" = set; then : +if ${ac_cv_path_BUILD_CXX+:} false; then : $as_echo_n "(cached) " >&6 else case $BUILD_CXX in @@ -18606,7 +18616,7 @@ $as_echo "$as_me: Rewriting BUILD_CXX to \"$new_complete\"" >&6;} set dummy ld; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_BUILD_LD+set}" = set; then : +if ${ac_cv_path_BUILD_LD+:} false; then : $as_echo_n "(cached) " >&6 else case $BUILD_LD in @@ -19113,7 +19123,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_TOOLS_DIR_CC+set}" = set; then : +if ${ac_cv_path_TOOLS_DIR_CC+:} false; then : $as_echo_n "(cached) " >&6 else case $TOOLS_DIR_CC in @@ -19165,7 +19175,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_POTENTIAL_CC+set}" = set; then : +if ${ac_cv_path_POTENTIAL_CC+:} false; then : $as_echo_n "(cached) " >&6 else case $POTENTIAL_CC in @@ -19578,7 +19588,7 @@ $as_echo "yes, trying to find proper $COMPILER_NAME compiler" >&6; } set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_PROPER_COMPILER_CC+set}" = set; then : +if ${ac_cv_prog_PROPER_COMPILER_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$PROPER_COMPILER_CC"; then @@ -19622,7 +19632,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_PROPER_COMPILER_CC+set}" = set; then : +if ${ac_cv_prog_ac_ct_PROPER_COMPILER_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_PROPER_COMPILER_CC"; then @@ -20072,7 +20082,7 @@ if test -n "$ac_tool_prefix"; then set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CC+set}" = set; then : +if ${ac_cv_prog_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CC"; then @@ -20116,7 +20126,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CC+set}" = set; then : +if ${ac_cv_prog_ac_ct_CC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CC"; then @@ -20169,7 +20179,7 @@ fi test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "no acceptable C compiler found in \$PATH -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } # Provide some information about the compiler. $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 @@ -20284,7 +20294,7 @@ sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "C compiler cannot create executables -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } else { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 $as_echo "yes" >&6; } @@ -20327,7 +20337,7 @@ else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of executables: cannot compile and link -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest conftest$ac_cv_exeext { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 @@ -20386,7 +20396,7 @@ $as_echo "$ac_try_echo"; } >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot run C compiled programs. If you meant to cross compile, use \`--host'. -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } fi fi fi @@ -20397,7 +20407,7 @@ rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out ac_clean_files=$ac_clean_files_save { $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 $as_echo_n "checking for suffix of object files... " >&6; } -if test "${ac_cv_objext+set}" = set; then : +if ${ac_cv_objext+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -20438,7 +20448,7 @@ sed 's/^/| /' conftest.$ac_ext >&5 { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "cannot compute suffix of object files: cannot compile -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } fi rm -f conftest.$ac_cv_objext conftest.$ac_ext fi @@ -20448,7 +20458,7 @@ OBJEXT=$ac_cv_objext ac_objext=$OBJEXT { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 $as_echo_n "checking whether we are using the GNU C compiler... " >&6; } -if test "${ac_cv_c_compiler_gnu+set}" = set; then : +if ${ac_cv_c_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -20485,7 +20495,7 @@ ac_test_CFLAGS=${CFLAGS+set} ac_save_CFLAGS=$CFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 $as_echo_n "checking whether $CC accepts -g... " >&6; } -if test "${ac_cv_prog_cc_g+set}" = set; then : +if ${ac_cv_prog_cc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_c_werror_flag=$ac_c_werror_flag @@ -20563,7 +20573,7 @@ else fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 $as_echo_n "checking for $CC option to accept ISO C89... " >&6; } -if test "${ac_cv_prog_cc_c89+set}" = set; then : +if ${ac_cv_prog_cc_c89+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_prog_cc_c89=no @@ -20686,7 +20696,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_TOOLS_DIR_CXX+set}" = set; then : +if ${ac_cv_path_TOOLS_DIR_CXX+:} false; then : $as_echo_n "(cached) " >&6 else case $TOOLS_DIR_CXX in @@ -20738,7 +20748,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_POTENTIAL_CXX+set}" = set; then : +if ${ac_cv_path_POTENTIAL_CXX+:} false; then : $as_echo_n "(cached) " >&6 else case $POTENTIAL_CXX in @@ -21151,7 +21161,7 @@ $as_echo "yes, trying to find proper $COMPILER_NAME compiler" >&6; } set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_PROPER_COMPILER_CXX+set}" = set; then : +if ${ac_cv_prog_PROPER_COMPILER_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$PROPER_COMPILER_CXX"; then @@ -21195,7 +21205,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_PROPER_COMPILER_CXX+set}" = set; then : +if ${ac_cv_prog_ac_ct_PROPER_COMPILER_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_PROPER_COMPILER_CXX"; then @@ -21649,7 +21659,7 @@ if test -z "$CXX"; then set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_CXX+set}" = set; then : +if ${ac_cv_prog_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$CXX"; then @@ -21693,7 +21703,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_CXX+set}" = set; then : +if ${ac_cv_prog_ac_ct_CXX+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_CXX"; then @@ -21771,7 +21781,7 @@ done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C++ compiler" >&5 $as_echo_n "checking whether we are using the GNU C++ compiler... " >&6; } -if test "${ac_cv_cxx_compiler_gnu+set}" = set; then : +if ${ac_cv_cxx_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -21808,7 +21818,7 @@ ac_test_CXXFLAGS=${CXXFLAGS+set} ac_save_CXXFLAGS=$CXXFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CXX accepts -g" >&5 $as_echo_n "checking whether $CXX accepts -g... " >&6; } -if test "${ac_cv_prog_cxx_g+set}" = set; then : +if ${ac_cv_prog_cxx_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_cxx_werror_flag=$ac_cxx_werror_flag @@ -21906,7 +21916,7 @@ if test -n "$ac_tool_prefix"; then set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_OBJC+set}" = set; then : +if ${ac_cv_prog_OBJC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJC"; then @@ -21950,7 +21960,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_OBJC+set}" = set; then : +if ${ac_cv_prog_ac_ct_OBJC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJC"; then @@ -22026,7 +22036,7 @@ done { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU Objective C compiler" >&5 $as_echo_n "checking whether we are using the GNU Objective C compiler... " >&6; } -if test "${ac_cv_objc_compiler_gnu+set}" = set; then : +if ${ac_cv_objc_compiler_gnu+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -22063,7 +22073,7 @@ ac_test_OBJCFLAGS=${OBJCFLAGS+set} ac_save_OBJCFLAGS=$OBJCFLAGS { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $OBJC accepts -g" >&5 $as_echo_n "checking whether $OBJC accepts -g... " >&6; } -if test "${ac_cv_prog_objc_g+set}" = set; then : +if ${ac_cv_prog_objc_g+:} false; then : $as_echo_n "(cached) " >&6 else ac_save_objc_werror_flag=$ac_objc_werror_flag @@ -22439,7 +22449,7 @@ if test "x$OPENJDK_TARGET_OS" != xwindows; then set dummy ${ac_tool_prefix}ar; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_AR+set}" = set; then : +if ${ac_cv_prog_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$AR"; then @@ -22479,7 +22489,7 @@ if test -z "$ac_cv_prog_AR"; then set dummy ar; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_AR+set}" = set; then : +if ${ac_cv_prog_ac_ct_AR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_AR"; then @@ -22821,7 +22831,7 @@ if test "x$OPENJDK_TARGET_OS" = xwindows; then : set dummy link; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_WINLD+set}" = set; then : +if ${ac_cv_prog_WINLD+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$WINLD"; then @@ -23160,7 +23170,7 @@ $as_echo "yes" >&6; } set dummy mt; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_MT+set}" = set; then : +if ${ac_cv_prog_MT+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$MT"; then @@ -23481,7 +23491,7 @@ $as_echo "$as_me: Rewriting MT to \"$new_complete\"" >&6;} set dummy rc; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_RC+set}" = set; then : +if ${ac_cv_prog_RC+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$RC"; then @@ -23873,7 +23883,7 @@ fi set dummy lib; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_WINAR+set}" = set; then : +if ${ac_cv_prog_WINAR+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$WINAR"; then @@ -24179,7 +24189,7 @@ $as_echo "$as_me: Rewriting WINAR to \"$new_complete\"" >&6;} set dummy dumpbin; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_DUMPBIN+set}" = set; then : +if ${ac_cv_prog_DUMPBIN+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$DUMPBIN"; then @@ -24498,7 +24508,7 @@ if test -n "$CPP" && test -d "$CPP"; then CPP= fi if test -z "$CPP"; then - if test "${ac_cv_prog_CPP+set}" = set; then : + if ${ac_cv_prog_CPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CPP needs to be expanded @@ -24614,7 +24624,7 @@ else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C preprocessor \"$CPP\" fails sanity check -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=cpp @@ -24898,7 +24908,7 @@ ac_compiler_gnu=$ac_cv_cxx_compiler_gnu { $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C++ preprocessor" >&5 $as_echo_n "checking how to run the C++ preprocessor... " >&6; } if test -z "$CXXCPP"; then - if test "${ac_cv_prog_CXXCPP+set}" = set; then : + if ${ac_cv_prog_CXXCPP+:} false; then : $as_echo_n "(cached) " >&6 else # Double quotes because CXXCPP needs to be expanded @@ -25014,7 +25024,7 @@ else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error $? "C++ preprocessor \"$CXXCPP\" fails sanity check -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } fi ac_ext=cpp @@ -25316,7 +25326,7 @@ if test "x$OPENJDK_TARGET_OS" = xsolaris; then set dummy as; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_AS+set}" = set; then : +if ${ac_cv_path_AS+:} false; then : $as_echo_n "(cached) " >&6 else case $AS in @@ -25628,7 +25638,7 @@ if test "x$OPENJDK_TARGET_OS" = xsolaris; then set dummy nm; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_NM+set}" = set; then : +if ${ac_cv_path_NM+:} false; then : $as_echo_n "(cached) " >&6 else case $NM in @@ -25934,7 +25944,7 @@ $as_echo "$as_me: Rewriting NM to \"$new_complete\"" >&6;} set dummy gnm; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_GNM+set}" = set; then : +if ${ac_cv_path_GNM+:} false; then : $as_echo_n "(cached) " >&6 else case $GNM in @@ -26240,7 +26250,7 @@ $as_echo "$as_me: Rewriting GNM to \"$new_complete\"" >&6;} set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_STRIP+set}" = set; then : +if ${ac_cv_path_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else case $STRIP in @@ -26546,7 +26556,7 @@ $as_echo "$as_me: Rewriting STRIP to \"$new_complete\"" >&6;} set dummy mcs; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_MCS+set}" = set; then : +if ${ac_cv_path_MCS+:} false; then : $as_echo_n "(cached) " >&6 else case $MCS in @@ -26854,7 +26864,7 @@ elif test "x$OPENJDK_TARGET_OS" != xwindows; then set dummy ${ac_tool_prefix}nm; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_NM+set}" = set; then : +if ${ac_cv_prog_NM+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$NM"; then @@ -26894,7 +26904,7 @@ if test -z "$ac_cv_prog_NM"; then set dummy nm; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_NM+set}" = set; then : +if ${ac_cv_prog_ac_ct_NM+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_NM"; then @@ -27214,7 +27224,7 @@ $as_echo "$as_me: Rewriting NM to \"$new_complete\"" >&6;} set dummy ${ac_tool_prefix}strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_STRIP+set}" = set; then : +if ${ac_cv_prog_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$STRIP"; then @@ -27254,7 +27264,7 @@ if test -z "$ac_cv_prog_STRIP"; then set dummy strip; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_STRIP+set}" = set; then : +if ${ac_cv_prog_ac_ct_STRIP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_STRIP"; then @@ -27579,7 +27589,7 @@ if test "x$OPENJDK_TARGET_OS" = xsolaris || test "x$OPENJDK_TARGET_OS" = xlinux; set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_OBJCOPY+set}" = set; then : +if ${ac_cv_prog_OBJCOPY+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJCOPY"; then @@ -27623,7 +27633,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_OBJCOPY+set}" = set; then : +if ${ac_cv_prog_ac_ct_OBJCOPY+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJCOPY"; then @@ -27950,7 +27960,7 @@ if test -n "$ac_tool_prefix"; then set dummy $ac_tool_prefix$ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_OBJDUMP+set}" = set; then : +if ${ac_cv_prog_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$OBJDUMP"; then @@ -27994,7 +28004,7 @@ do set dummy $ac_prog; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_ac_ct_OBJDUMP+set}" = set; then : +if ${ac_cv_prog_ac_ct_OBJDUMP+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$ac_ct_OBJDUMP"; then @@ -28318,7 +28328,7 @@ if test "x$OPENJDK_TARGET_OS" = "xmacosx"; then set dummy lipo; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_LIPO+set}" = set; then : +if ${ac_cv_path_LIPO+:} false; then : $as_echo_n "(cached) " >&6 else case $LIPO in @@ -28635,7 +28645,7 @@ PATH="$OLD_PATH" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 $as_echo_n "checking for ANSI C header files... " >&6; } -if test "${ac_cv_header_stdc+set}" = set; then : +if ${ac_cv_header_stdc+:} false; then : $as_echo_n "(cached) " >&6 else cat confdefs.h - <<_ACEOF >conftest.$ac_ext @@ -28812,7 +28822,7 @@ fi for ac_header in stdio.h do : ac_fn_cxx_check_header_mongrel "$LINENO" "stdio.h" "ac_cv_header_stdio_h" "$ac_includes_default" -if test "x$ac_cv_header_stdio_h" = x""yes; then : +if test "x$ac_cv_header_stdio_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_STDIO_H 1 _ACEOF @@ -28841,7 +28851,7 @@ done # This bug is HP SR number 8606223364. { $as_echo "$as_me:${as_lineno-$LINENO}: checking size of int *" >&5 $as_echo_n "checking size of int *... " >&6; } -if test "${ac_cv_sizeof_int_p+set}" = set; then : +if ${ac_cv_sizeof_int_p+:} false; then : $as_echo_n "(cached) " >&6 else if ac_fn_cxx_compute_int "$LINENO" "(long int) (sizeof (int *))" "ac_cv_sizeof_int_p" "$ac_includes_default"; then : @@ -28851,7 +28861,7 @@ else { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 $as_echo "$as_me: error: in \`$ac_pwd':" >&2;} as_fn_error 77 "cannot compute sizeof (int *) -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } else ac_cv_sizeof_int_p=0 fi @@ -28898,7 +28908,7 @@ $as_echo "$OPENJDK_TARGET_CPU_BITS bits" >&6; } # { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether byte ordering is bigendian" >&5 $as_echo_n "checking whether byte ordering is bigendian... " >&6; } -if test "${ac_cv_c_bigendian+set}" = set; then : +if ${ac_cv_c_bigendian+:} false; then : $as_echo_n "(cached) " >&6 else ac_cv_c_bigendian=unknown @@ -30074,8 +30084,8 @@ if test "x$with_x" = xno; then have_x=disabled else case $x_includes,$x_libraries in #( - *\'*) as_fn_error $? "cannot use X directory names containing '" "$LINENO" 5 ;; #( - *,NONE | NONE,*) if test "${ac_cv_have_x+set}" = set; then : + *\'*) as_fn_error $? "cannot use X directory names containing '" "$LINENO" 5;; #( + *,NONE | NONE,*) if ${ac_cv_have_x+:} false; then : $as_echo_n "(cached) " >&6 else # One or both of the vars are not set, and there is no cached value. @@ -30352,7 +30362,7 @@ if ac_fn_cxx_try_link "$LINENO"; then : else { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dnet_ntoa in -ldnet" >&5 $as_echo_n "checking for dnet_ntoa in -ldnet... " >&6; } -if test "${ac_cv_lib_dnet_dnet_ntoa+set}" = set; then : +if ${ac_cv_lib_dnet_dnet_ntoa+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -30386,14 +30396,14 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dnet_dnet_ntoa" >&5 $as_echo "$ac_cv_lib_dnet_dnet_ntoa" >&6; } -if test "x$ac_cv_lib_dnet_dnet_ntoa" = x""yes; then : +if test "x$ac_cv_lib_dnet_dnet_ntoa" = xyes; then : X_EXTRA_LIBS="$X_EXTRA_LIBS -ldnet" fi if test $ac_cv_lib_dnet_dnet_ntoa = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dnet_ntoa in -ldnet_stub" >&5 $as_echo_n "checking for dnet_ntoa in -ldnet_stub... " >&6; } -if test "${ac_cv_lib_dnet_stub_dnet_ntoa+set}" = set; then : +if ${ac_cv_lib_dnet_stub_dnet_ntoa+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -30427,7 +30437,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dnet_stub_dnet_ntoa" >&5 $as_echo "$ac_cv_lib_dnet_stub_dnet_ntoa" >&6; } -if test "x$ac_cv_lib_dnet_stub_dnet_ntoa" = x""yes; then : +if test "x$ac_cv_lib_dnet_stub_dnet_ntoa" = xyes; then : X_EXTRA_LIBS="$X_EXTRA_LIBS -ldnet_stub" fi @@ -30446,14 +30456,14 @@ rm -f core conftest.err conftest.$ac_objext \ # The functions gethostbyname, getservbyname, and inet_addr are # in -lbsd on LynxOS 3.0.1/i386, according to Lars Hecking. ac_fn_cxx_check_func "$LINENO" "gethostbyname" "ac_cv_func_gethostbyname" -if test "x$ac_cv_func_gethostbyname" = x""yes; then : +if test "x$ac_cv_func_gethostbyname" = xyes; then : fi if test $ac_cv_func_gethostbyname = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lnsl" >&5 $as_echo_n "checking for gethostbyname in -lnsl... " >&6; } -if test "${ac_cv_lib_nsl_gethostbyname+set}" = set; then : +if ${ac_cv_lib_nsl_gethostbyname+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -30487,14 +30497,14 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_nsl_gethostbyname" >&5 $as_echo "$ac_cv_lib_nsl_gethostbyname" >&6; } -if test "x$ac_cv_lib_nsl_gethostbyname" = x""yes; then : +if test "x$ac_cv_lib_nsl_gethostbyname" = xyes; then : X_EXTRA_LIBS="$X_EXTRA_LIBS -lnsl" fi if test $ac_cv_lib_nsl_gethostbyname = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gethostbyname in -lbsd" >&5 $as_echo_n "checking for gethostbyname in -lbsd... " >&6; } -if test "${ac_cv_lib_bsd_gethostbyname+set}" = set; then : +if ${ac_cv_lib_bsd_gethostbyname+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -30528,7 +30538,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_bsd_gethostbyname" >&5 $as_echo "$ac_cv_lib_bsd_gethostbyname" >&6; } -if test "x$ac_cv_lib_bsd_gethostbyname" = x""yes; then : +if test "x$ac_cv_lib_bsd_gethostbyname" = xyes; then : X_EXTRA_LIBS="$X_EXTRA_LIBS -lbsd" fi @@ -30543,14 +30553,14 @@ fi # must be given before -lnsl if both are needed. We assume that # if connect needs -lnsl, so does gethostbyname. ac_fn_cxx_check_func "$LINENO" "connect" "ac_cv_func_connect" -if test "x$ac_cv_func_connect" = x""yes; then : +if test "x$ac_cv_func_connect" = xyes; then : fi if test $ac_cv_func_connect = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for connect in -lsocket" >&5 $as_echo_n "checking for connect in -lsocket... " >&6; } -if test "${ac_cv_lib_socket_connect+set}" = set; then : +if ${ac_cv_lib_socket_connect+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -30584,7 +30594,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_connect" >&5 $as_echo "$ac_cv_lib_socket_connect" >&6; } -if test "x$ac_cv_lib_socket_connect" = x""yes; then : +if test "x$ac_cv_lib_socket_connect" = xyes; then : X_EXTRA_LIBS="-lsocket $X_EXTRA_LIBS" fi @@ -30592,14 +30602,14 @@ fi # Guillermo Gomez says -lposix is necessary on A/UX. ac_fn_cxx_check_func "$LINENO" "remove" "ac_cv_func_remove" -if test "x$ac_cv_func_remove" = x""yes; then : +if test "x$ac_cv_func_remove" = xyes; then : fi if test $ac_cv_func_remove = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for remove in -lposix" >&5 $as_echo_n "checking for remove in -lposix... " >&6; } -if test "${ac_cv_lib_posix_remove+set}" = set; then : +if ${ac_cv_lib_posix_remove+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -30633,7 +30643,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_posix_remove" >&5 $as_echo "$ac_cv_lib_posix_remove" >&6; } -if test "x$ac_cv_lib_posix_remove" = x""yes; then : +if test "x$ac_cv_lib_posix_remove" = xyes; then : X_EXTRA_LIBS="$X_EXTRA_LIBS -lposix" fi @@ -30641,14 +30651,14 @@ fi # BSDI BSD/OS 2.1 needs -lipc for XOpenDisplay. ac_fn_cxx_check_func "$LINENO" "shmat" "ac_cv_func_shmat" -if test "x$ac_cv_func_shmat" = x""yes; then : +if test "x$ac_cv_func_shmat" = xyes; then : fi if test $ac_cv_func_shmat = no; then { $as_echo "$as_me:${as_lineno-$LINENO}: checking for shmat in -lipc" >&5 $as_echo_n "checking for shmat in -lipc... " >&6; } -if test "${ac_cv_lib_ipc_shmat+set}" = set; then : +if ${ac_cv_lib_ipc_shmat+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -30682,7 +30692,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ipc_shmat" >&5 $as_echo "$ac_cv_lib_ipc_shmat" >&6; } -if test "x$ac_cv_lib_ipc_shmat" = x""yes; then : +if test "x$ac_cv_lib_ipc_shmat" = xyes; then : X_EXTRA_LIBS="$X_EXTRA_LIBS -lipc" fi @@ -30700,7 +30710,7 @@ fi # John Interrante, Karl Berry { $as_echo "$as_me:${as_lineno-$LINENO}: checking for IceConnectionNumber in -lICE" >&5 $as_echo_n "checking for IceConnectionNumber in -lICE... " >&6; } -if test "${ac_cv_lib_ICE_IceConnectionNumber+set}" = set; then : +if ${ac_cv_lib_ICE_IceConnectionNumber+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -30734,7 +30744,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_ICE_IceConnectionNumber" >&5 $as_echo "$ac_cv_lib_ICE_IceConnectionNumber" >&6; } -if test "x$ac_cv_lib_ICE_IceConnectionNumber" = x""yes; then : +if test "x$ac_cv_lib_ICE_IceConnectionNumber" = xyes; then : X_PRE_LIBS="$X_PRE_LIBS -lSM -lICE" fi @@ -31752,7 +31762,7 @@ $as_echo "$FREETYPE2_FOUND" >&6; } LDFLAGS="$FREETYPE2_LIBS" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for FT_Init_FreeType in -lfreetype" >&5 $as_echo_n "checking for FT_Init_FreeType in -lfreetype... " >&6; } -if test "${ac_cv_lib_freetype_FT_Init_FreeType+set}" = set; then : +if ${ac_cv_lib_freetype_FT_Init_FreeType+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -31786,7 +31796,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_freetype_FT_Init_FreeType" >&5 $as_echo "$ac_cv_lib_freetype_FT_Init_FreeType" >&6; } -if test "x$ac_cv_lib_freetype_FT_Init_FreeType" = x""yes; then : +if test "x$ac_cv_lib_freetype_FT_Init_FreeType" = xyes; then : FREETYPE2_FOUND=true else as_fn_error $? "Could not find freetype2! $HELP_MSG " "$LINENO" 5 @@ -32074,7 +32084,7 @@ fi for ac_header in alsa/asoundlib.h do : ac_fn_cxx_check_header_mongrel "$LINENO" "alsa/asoundlib.h" "ac_cv_header_alsa_asoundlib_h" "$ac_includes_default" -if test "x$ac_cv_header_alsa_asoundlib_h" = x""yes; then : +if test "x$ac_cv_header_alsa_asoundlib_h" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_ALSA_ASOUNDLIB_H 1 _ACEOF @@ -32133,7 +32143,7 @@ fi USE_EXTERNAL_LIBJPEG=true { $as_echo "$as_me:${as_lineno-$LINENO}: checking for main in -ljpeg" >&5 $as_echo_n "checking for main in -ljpeg... " >&6; } -if test "${ac_cv_lib_jpeg_main+set}" = set; then : +if ${ac_cv_lib_jpeg_main+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -32161,7 +32171,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_jpeg_main" >&5 $as_echo "$ac_cv_lib_jpeg_main" >&6; } -if test "x$ac_cv_lib_jpeg_main" = x""yes; then : +if test "x$ac_cv_lib_jpeg_main" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBJPEG 1 _ACEOF @@ -32210,7 +32220,7 @@ if test "x${with_giflib}" = "xbundled"; then USE_EXTERNAL_LIBGIF=false elif test "x${with_giflib}" = "xsystem"; then ac_fn_cxx_check_header_mongrel "$LINENO" "gif_lib.h" "ac_cv_header_gif_lib_h" "$ac_includes_default" -if test "x$ac_cv_header_gif_lib_h" = x""yes; then : +if test "x$ac_cv_header_gif_lib_h" = xyes; then : else as_fn_error $? "--with-giflib=system specified, but gif_lib.h not found!" "$LINENO" 5 @@ -32219,7 +32229,7 @@ fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for DGifGetCode in -lgif" >&5 $as_echo_n "checking for DGifGetCode in -lgif... " >&6; } -if test "${ac_cv_lib_gif_DGifGetCode+set}" = set; then : +if ${ac_cv_lib_gif_DGifGetCode+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -32253,7 +32263,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gif_DGifGetCode" >&5 $as_echo "$ac_cv_lib_gif_DGifGetCode" >&6; } -if test "x$ac_cv_lib_gif_DGifGetCode" = x""yes; then : +if test "x$ac_cv_lib_gif_DGifGetCode" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBGIF 1 _ACEOF @@ -32285,7 +32295,7 @@ fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for compress in -lz" >&5 $as_echo_n "checking for compress in -lz... " >&6; } -if test "${ac_cv_lib_z_compress+set}" = set; then : +if ${ac_cv_lib_z_compress+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -32319,7 +32329,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_z_compress" >&5 $as_echo "$ac_cv_lib_z_compress" >&6; } -if test "x$ac_cv_lib_z_compress" = x""yes; then : +if test "x$ac_cv_lib_z_compress" = xyes; then : ZLIB_FOUND=yes else ZLIB_FOUND=no @@ -32412,7 +32422,7 @@ fi { $as_echo "$as_me:${as_lineno-$LINENO}: checking for cos in -lm" >&5 $as_echo_n "checking for cos in -lm... " >&6; } -if test "${ac_cv_lib_m_cos+set}" = set; then : +if ${ac_cv_lib_m_cos+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -32446,7 +32456,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_cos" >&5 $as_echo "$ac_cv_lib_m_cos" >&6; } -if test "x$ac_cv_lib_m_cos" = x""yes; then : +if test "x$ac_cv_lib_m_cos" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBM 1 _ACEOF @@ -32470,7 +32480,7 @@ save_LIBS="$LIBS" LIBS="" { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 $as_echo_n "checking for dlopen in -ldl... " >&6; } -if test "${ac_cv_lib_dl_dlopen+set}" = set; then : +if ${ac_cv_lib_dl_dlopen+:} false; then : $as_echo_n "(cached) " >&6 else ac_check_lib_save_LIBS=$LIBS @@ -32504,7 +32514,7 @@ LIBS=$ac_check_lib_save_LIBS fi { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 $as_echo "$ac_cv_lib_dl_dlopen" >&6; } -if test "x$ac_cv_lib_dl_dlopen" = x""yes; then : +if test "x$ac_cv_lib_dl_dlopen" = xyes; then : cat >>confdefs.h <<_ACEOF #define HAVE_LIBDL 1 _ACEOF @@ -32734,7 +32744,7 @@ and LIBFFI_LIBS to avoid the need to call pkg-config. See the pkg-config man page for more details. To get pkg-config, see . -See \`config.log' for more details" "$LINENO" 5 ; } +See \`config.log' for more details" "$LINENO" 5; } else LIBFFI_CFLAGS=$pkg_cv_LIBFFI_CFLAGS LIBFFI_LIBS=$pkg_cv_LIBFFI_LIBS @@ -32750,7 +32760,7 @@ if test "x$JVM_VARIANT_ZEROSHARK" = xtrue; then set dummy llvm-config; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_prog_LLVM_CONFIG+set}" = set; then : +if ${ac_cv_prog_LLVM_CONFIG+:} false; then : $as_echo_n "(cached) " >&6 else if test -n "$LLVM_CONFIG"; then @@ -33366,7 +33376,7 @@ fi set dummy ccache; ac_word=$2 { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 $as_echo_n "checking for $ac_word... " >&6; } -if test "${ac_cv_path_CCACHE+set}" = set; then : +if ${ac_cv_path_CCACHE+:} false; then : $as_echo_n "(cached) " >&6 else case $CCACHE in @@ -33628,10 +33638,21 @@ $as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; :end' >>confcache if diff "$cache_file" confcache >/dev/null 2>&1; then :; else if test -w "$cache_file"; then - test "x$cache_file" != "x/dev/null" && + if test "x$cache_file" != "x/dev/null"; then { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 $as_echo "$as_me: updating cache $cache_file" >&6;} - cat confcache >$cache_file + if test ! -f "$cache_file" || test -h "$cache_file"; then + cat confcache >"$cache_file" + else + case $cache_file in #( + */* | ?:*) + mv -f confcache "$cache_file"$$ && + mv -f "$cache_file"$$ "$cache_file" ;; #( + *) + mv -f confcache "$cache_file" ;; + esac + fi + fi else { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 $as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} @@ -33663,7 +33684,7 @@ LTLIBOBJS=$ac_ltlibobjs -: ${CONFIG_STATUS=./config.status} +: "${CONFIG_STATUS=./config.status}" ac_write_fail=0 ac_clean_files_save=$ac_clean_files ac_clean_files="$ac_clean_files $CONFIG_STATUS" @@ -33764,6 +33785,7 @@ fi IFS=" "" $as_nl" # Find who we are. Look in the path if we contain no directory separator. +as_myself= case $0 in #(( *[\\/]* ) as_myself=$0 ;; *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR @@ -34071,7 +34093,7 @@ cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 # values after options handling. ac_log=" This file was extended by OpenJDK $as_me jdk8, which was -generated by GNU Autoconf 2.67. Invocation command line was +generated by GNU Autoconf 2.68. Invocation command line was CONFIG_FILES = $CONFIG_FILES CONFIG_HEADERS = $CONFIG_HEADERS @@ -34134,7 +34156,7 @@ cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" ac_cs_version="\\ OpenJDK config.status jdk8 -configured by $0, generated by GNU Autoconf 2.67, +configured by $0, generated by GNU Autoconf 2.68, with options \\"\$ac_cs_config\\" Copyright (C) 2010 Free Software Foundation, Inc. @@ -34263,7 +34285,7 @@ do "$OUTPUT_ROOT/spec.sh") CONFIG_FILES="$CONFIG_FILES $OUTPUT_ROOT/spec.sh:$AUTOCONF_DIR/spec.sh.in" ;; "$OUTPUT_ROOT/Makefile") CONFIG_FILES="$CONFIG_FILES $OUTPUT_ROOT/Makefile:$AUTOCONF_DIR/Makefile.in" ;; - *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5 ;; + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; esac done @@ -34285,9 +34307,10 @@ fi # after its creation but before its name has been assigned to `$tmp'. $debug || { - tmp= + tmp= ac_tmp= trap 'exit_status=$? - { test -z "$tmp" || test ! -d "$tmp" || rm -fr "$tmp"; } && exit $exit_status + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status ' 0 trap 'as_fn_exit 1' 1 2 13 15 } @@ -34295,12 +34318,13 @@ $debug || { tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && - test -n "$tmp" && test -d "$tmp" + test -d "$tmp" } || { tmp=./conf$$-$RANDOM (umask 077 && mkdir "$tmp") } || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp # Set up the scripts for CONFIG_FILES section. # No need to generate them if there are no CONFIG_FILES. @@ -34322,7 +34346,7 @@ else ac_cs_awk_cr=$ac_cr fi -echo 'BEGIN {' >"$tmp/subs1.awk" && +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && _ACEOF @@ -34350,7 +34374,7 @@ done rm -f conf$$subs.sh cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 -cat >>"\$tmp/subs1.awk" <<\\_ACAWK && +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && _ACEOF sed -n ' h @@ -34398,7 +34422,7 @@ t delim rm -f conf$$subs.awk cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 _ACAWK -cat >>"\$tmp/subs1.awk" <<_ACAWK && +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && for (key in S) S_is_set[key] = 1 FS = "" @@ -34430,7 +34454,7 @@ if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" else cat -fi < "$tmp/subs1.awk" > "$tmp/subs.awk" \ +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 _ACEOF @@ -34464,7 +34488,7 @@ fi # test -n "$CONFIG_FILES" # No need to generate them if there are no CONFIG_HEADERS. # This happens for instance with `./config.status Makefile'. if test -n "$CONFIG_HEADERS"; then -cat >"$tmp/defines.awk" <<\_ACAWK || +cat >"$ac_tmp/defines.awk" <<\_ACAWK || BEGIN { _ACEOF @@ -34476,8 +34500,8 @@ _ACEOF # handling of long lines. ac_delim='%!_!# ' for ac_last_try in false false :; do - ac_t=`sed -n "/$ac_delim/p" confdefs.h` - if test -z "$ac_t"; then + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then break elif $ac_last_try; then as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 @@ -34578,7 +34602,7 @@ do esac case $ac_mode$ac_tag in :[FHL]*:*);; - :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5 ;; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; :[FH]-) ac_tag=-:-;; :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; esac @@ -34597,7 +34621,7 @@ do for ac_f do case $ac_f in - -) ac_f="$tmp/stdin";; + -) ac_f="$ac_tmp/stdin";; *) # Look for the file first in the build tree, then in the source tree # (if the path is not absolute). The absolute path cannot be DOS-style, # because $ac_f cannot contain `:'. @@ -34606,7 +34630,7 @@ do [\\/$]*) false;; *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; esac || - as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5 ;; + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; esac case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac as_fn_append ac_file_inputs " '$ac_f'" @@ -34632,8 +34656,8 @@ $as_echo "$as_me: creating $ac_file" >&6;} esac case $ac_tag in - *:-:* | *:-) cat >"$tmp/stdin" \ - || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; esac ;; esac @@ -34758,21 +34782,22 @@ s&@abs_builddir@&$ac_abs_builddir&;t t s&@abs_top_builddir@&$ac_abs_top_builddir&;t t $ac_datarootdir_hack " -eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$tmp/subs.awk" >$tmp/out \ - || as_fn_error $? "could not create $ac_file" "$LINENO" 5 +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | $AWK -f "$ac_tmp/subs.awk" \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && - { ac_out=`sed -n '/\${datarootdir}/p' "$tmp/out"`; test -n "$ac_out"; } && - { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' "$tmp/out"`; test -z "$ac_out"; } && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&5 $as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' which seems to be undefined. Please make sure it is defined" >&2;} - rm -f "$tmp/stdin" + rm -f "$ac_tmp/stdin" case $ac_file in - -) cat "$tmp/out" && rm -f "$tmp/out";; - *) rm -f "$ac_file" && mv "$tmp/out" "$ac_file";; + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; esac \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; @@ -34783,20 +34808,20 @@ which seems to be undefined. Please make sure it is defined" >&2;} if test x"$ac_file" != x-; then { $as_echo "/* $configure_input */" \ - && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" - } >"$tmp/config.h" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 - if diff "$ac_file" "$tmp/config.h" >/dev/null 2>&1; then + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 $as_echo "$as_me: $ac_file is unchanged" >&6;} else rm -f "$ac_file" - mv "$tmp/config.h" "$ac_file" \ + mv "$ac_tmp/config.h" "$ac_file" \ || as_fn_error $? "could not create $ac_file" "$LINENO" 5 fi else $as_echo "/* $configure_input */" \ - && eval '$AWK -f "$tmp/defines.awk"' "$ac_file_inputs" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ || as_fn_error $? "could not create -" "$LINENO" 5 fi ;; diff --git a/common/autoconf/toolchain_windows.m4 b/common/autoconf/toolchain_windows.m4 index 966c0133995..e5d4fff38f9 100644 --- a/common/autoconf/toolchain_windows.m4 +++ b/common/autoconf/toolchain_windows.m4 @@ -208,6 +208,8 @@ AC_DEFUN([TOOLCHAIN_SETUP_VISUAL_STUDIO_ENV], # Remove any trailing \ from INCLUDE and LIB to avoid trouble in spec.gmk. VS_INCLUDE=`$ECHO "$INCLUDE" | $SED 's/\\\\$//'` VS_LIB=`$ECHO "$LIB" | $SED 's/\\\\$//'` + # Remove any paths containing # (typically F#) as that messes up make + PATH=`$ECHO "$PATH" | $SED 's/[[^:#]]*#[^:]*://g'` VS_PATH="$PATH" AC_SUBST(VS_INCLUDE) AC_SUBST(VS_LIB) diff --git a/corba/.hgtags b/corba/.hgtags index 77bfead7060..9acbd27447b 100644 --- a/corba/.hgtags +++ b/corba/.hgtags @@ -218,3 +218,7 @@ c8286839d0df04aba819ec4bef12b86babccf30e jdk8-b90 22f5d7f261d9d61a953d2d9a53f2e9ce0ca361d1 jdk8-b94 2cf36f43df36137980d9828cec27003ec10daeee jdk8-b95 3357c2776431d51a8de326a85e0f41420e40774f jdk8-b96 +469995a8e97424f450c880606d689bf345277b19 jdk8-b97 +3370fb6146e47a6cc05a213fc213e12fc0a38d07 jdk8-b98 +3f67804ab61303782df57e54989ef5e0e4629beb jdk8-b99 +8d492f1dfd1b131a4c7886ee6b59528609f7e4fe jdk8-b100 diff --git a/hotspot/.hgtags b/hotspot/.hgtags index 0363e7ebd3e..c802f848b65 100644 --- a/hotspot/.hgtags +++ b/hotspot/.hgtags @@ -355,3 +355,11 @@ b786c04b7be15194febe88dc1f0c9443e737a84b hs25-b35 2cc5a9d1ba66dfdff578918b393c727bd9450210 hs25-b38 e6a4b8c71fa6f225bd989a34de2d0d0a656a8be8 jdk8-b96 2b9380b0bf0b649f40704735773e8956c2d88ba0 hs25-b39 +d197d377ab2e016d024e8c86cb06a57bd7eae590 jdk8-b97 +c9dd82da51ed34a28f7c6b3245163ee962e94572 hs25-b40 +30b5b75c42ac5174b640fbef8aa87527668e8400 jdk8-b98 +2b9946e10587f74ef75ae8145bea484df4a2738b hs25-b41 +81b6cb70717c66375846b78bb174594ec3aa998e jdk8-b99 +9f71e36a471ae4a668e08827d33035963ed10c08 hs25-b42 +5787fac72e760c6a5fd9efa113b0c75caf554136 jdk8-b100 +46487ba40ff225654d0c51787ed3839bafcbd9f3 hs25-b43 diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/CLHSDB.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/CLHSDB.java index 5071235fa3e..9e8d016dcc2 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/CLHSDB.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/CLHSDB.java @@ -31,13 +31,19 @@ import java.io.*; import java.util.*; public class CLHSDB { + + public CLHSDB(JVMDebugger d) { + jvmDebugger = d; + } + public static void main(String[] args) { new CLHSDB(args).run(); } - private void run() { - // At this point, if pidText != null we are supposed to attach to it. - // Else, if execPath != null, it is the path of a jdk/bin/java + public void run() { + // If jvmDebugger is already set, we have been given a JVMDebugger. + // Otherwise, if pidText != null we are supposed to attach to it. + // Finally, if execPath != null, it is the path of a jdk/bin/java // and coreFilename is the pathname of a core file we are // supposed to attach to. @@ -49,7 +55,9 @@ public class CLHSDB { } }); - if (pidText != null) { + if (jvmDebugger != null) { + attachDebugger(jvmDebugger); + } else if (pidText != null) { attachDebugger(pidText); } else if (execPath != null) { attachDebugger(execPath, coreFilename); @@ -96,6 +104,7 @@ public class CLHSDB { // Internals only below this point // private HotSpotAgent agent; + private JVMDebugger jvmDebugger; private boolean attached; // These had to be made data members because they are referenced in inner classes. private String pidText; @@ -120,7 +129,7 @@ public class CLHSDB { case (1): if (args[0].equals("help") || args[0].equals("-help")) { doUsage(); - System.exit(0); + return; } // If all numbers, it is a PID to attach to // Else, it is a pathname to a .../bin/java for a core file. @@ -142,10 +151,15 @@ public class CLHSDB { default: System.out.println("HSDB Error: Too many options specified"); doUsage(); - System.exit(1); + return; } } + private void attachDebugger(JVMDebugger d) { + agent.attach(d); + attached = true; + } + /** NOTE we are in a different thread here than either the main thread or the Swing/AWT event handler thread, so we must be very careful when creating or removing widgets */ diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/CommandProcessor.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/CommandProcessor.java index 2233844267c..1840caf9313 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/CommandProcessor.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/CommandProcessor.java @@ -101,6 +101,9 @@ import sun.jvm.hotspot.utilities.soql.JSJavaFactoryImpl; import sun.jvm.hotspot.utilities.soql.JSJavaScriptEngine; public class CommandProcessor { + + volatile boolean quit; + public abstract static class DebuggerInterface { public abstract HotSpotAgent getAgent(); public abstract boolean isAttached(); @@ -1135,7 +1138,7 @@ public class CommandProcessor { usage(); } else { debugger.detach(); - System.exit(0); + quit = true; } } }, @@ -1714,7 +1717,7 @@ public class CommandProcessor { } protected void quit() { debugger.detach(); - System.exit(0); + quit = true; } protected BufferedReader getInputReader() { return in; @@ -1781,7 +1784,7 @@ public class CommandProcessor { public void run(boolean prompt) { // Process interactive commands. - while (true) { + while (!quit) { if (prompt) printPrompt(); String ln = null; try { diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/HSDB.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/HSDB.java index 5143408c687..d50cbaa5140 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/HSDB.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/HSDB.java @@ -59,8 +59,11 @@ public class HSDB implements ObjectHistogramPanel.Listener, SAListener { // Internals only below this point // private HotSpotAgent agent; + private JVMDebugger jvmDebugger; private JDesktopPane desktop; private boolean attached; + private boolean argError; + private JFrame frame; /** List */ private java.util.List attachMenuItems; /** List */ @@ -85,6 +88,11 @@ public class HSDB implements ObjectHistogramPanel.Listener, SAListener { System.out.println(" path-to-corefile: Debug this corefile. The default is 'core'"); System.out.println(" If no arguments are specified, you can select what to do from the GUI.\n"); HotSpotAgent.showUsage(); + argError = true; + } + + public HSDB(JVMDebugger d) { + jvmDebugger = d; } private HSDB(String[] args) { @@ -95,7 +103,6 @@ public class HSDB implements ObjectHistogramPanel.Listener, SAListener { case (1): if (args[0].equals("help") || args[0].equals("-help")) { doUsage(); - System.exit(0); } // If all numbers, it is a PID to attach to // Else, it is a pathname to a .../bin/java for a core file. @@ -117,24 +124,29 @@ public class HSDB implements ObjectHistogramPanel.Listener, SAListener { default: System.out.println("HSDB Error: Too many options specified"); doUsage(); - System.exit(1); } } - private void run() { - // At this point, if pidText != null we are supposed to attach to it. - // Else, if execPath != null, it is the path of a jdk/bin/java - // and coreFilename is the pathname of a core file we are - // supposed to attach to. + // close this tool without calling System.exit + protected void closeUI() { + workerThread.shutdown(); + frame.dispose(); + } + + public void run() { + // Don't start the UI if there were bad arguments. + if (argError) { + return; + } agent = new HotSpotAgent(); workerThread = new WorkerThread(); attachMenuItems = new java.util.ArrayList(); detachMenuItems = new java.util.ArrayList(); - JFrame frame = new JFrame("HSDB - HotSpot Debugger"); + frame = new JFrame("HSDB - HotSpot Debugger"); frame.setSize(800, 600); - frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); JMenuBar menuBar = new JMenuBar(); @@ -197,7 +209,7 @@ public class HSDB implements ObjectHistogramPanel.Listener, SAListener { item = createMenuItem("Exit", new ActionListener() { public void actionPerformed(ActionEvent e) { - System.exit(0); + closeUI(); } }); item.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_X, ActionEvent.ALT_MASK)); @@ -406,7 +418,15 @@ public class HSDB implements ObjectHistogramPanel.Listener, SAListener { } }); - if (pidText != null) { + // If jvmDebugger is already set, we have been given a JVMDebugger. + // Otherwise, if pidText != null we are supposed to attach to it. + // Finally, if execPath != null, it is the path of a jdk/bin/java + // and coreFilename is the pathname of a core file we are + // supposed to attach to. + + if (jvmDebugger != null) { + attach(jvmDebugger); + } else if (pidText != null) { attach(pidText); } else if (execPath != null) { attach(execPath, coreFilename); @@ -1113,6 +1133,12 @@ public class HSDB implements ObjectHistogramPanel.Listener, SAListener { }); } + // Attach to existing JVMDebugger, which should be already attached to a core/process. + private void attach(JVMDebugger d) { + attached = true; + showThreadsDialog(); + } + /** NOTE we are in a different thread here than either the main thread or the Swing/AWT event handler thread, so we must be very careful when creating or removing widgets */ diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/HotSpotAgent.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/HotSpotAgent.java index bdf9bd369e6..c963350591d 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/HotSpotAgent.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/HotSpotAgent.java @@ -25,6 +25,8 @@ package sun.jvm.hotspot; import java.rmi.RemoteException; +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import sun.jvm.hotspot.debugger.Debugger; import sun.jvm.hotspot.debugger.DebuggerException; @@ -63,7 +65,6 @@ public class HotSpotAgent { private String os; private String cpu; - private String fileSep; // The system can work in several ways: // - Attaching to local process @@ -155,6 +156,14 @@ public class HotSpotAgent { go(); } + /** This uses a JVMDebugger that is already attached to the core or process */ + public synchronized void attach(JVMDebugger d) + throws DebuggerException { + debugger = d; + isServer = false; + go(); + } + /** This attaches to a "debug server" on a remote machine; this remote server has already attached to a process or opened a core file and is waiting for RMI calls on the Debugger object to @@ -303,28 +312,37 @@ public class HotSpotAgent { // server, but not client attaching to server) // - try { - os = PlatformInfo.getOS(); - cpu = PlatformInfo.getCPU(); - } - catch (UnsupportedPlatformException e) { - throw new DebuggerException(e); - } - fileSep = System.getProperty("file.separator"); + // Handle existing or alternate JVMDebugger: + // these will set os, cpu independently of our PlatformInfo implementation. + String alternateDebugger = System.getProperty("sa.altDebugger"); + if (debugger != null) { + setupDebuggerExisting(); + + } else if (alternateDebugger != null) { + setupDebuggerAlternate(alternateDebugger); - if (os.equals("solaris")) { - setupDebuggerSolaris(); - } else if (os.equals("win32")) { - setupDebuggerWin32(); - } else if (os.equals("linux")) { - setupDebuggerLinux(); - } else if (os.equals("bsd")) { - setupDebuggerBsd(); - } else if (os.equals("darwin")) { - setupDebuggerDarwin(); } else { - // Add support for more operating systems here - throw new DebuggerException("Operating system " + os + " not yet supported"); + // Otherwise, os, cpu are those of our current platform: + try { + os = PlatformInfo.getOS(); + cpu = PlatformInfo.getCPU(); + } catch (UnsupportedPlatformException e) { + throw new DebuggerException(e); + } + if (os.equals("solaris")) { + setupDebuggerSolaris(); + } else if (os.equals("win32")) { + setupDebuggerWin32(); + } else if (os.equals("linux")) { + setupDebuggerLinux(); + } else if (os.equals("bsd")) { + setupDebuggerBsd(); + } else if (os.equals("darwin")) { + setupDebuggerDarwin(); + } else { + // Add support for more operating systems here + throw new DebuggerException("Operating system " + os + " not yet supported"); + } } if (isServer) { @@ -423,6 +441,41 @@ public class HotSpotAgent { // OS-specific debugger setup/connect routines // + // Use the existing JVMDebugger, as passed to our constructor. + // Retrieve os and cpu from that debugger, not the current platform. + private void setupDebuggerExisting() { + + os = debugger.getOS(); + cpu = debugger.getCPU(); + setupJVMLibNames(os); + machDesc = debugger.getMachineDescription(); + } + + // Given a classname, load an alternate implementation of JVMDebugger. + private void setupDebuggerAlternate(String alternateName) { + + try { + Class c = Class.forName(alternateName); + Constructor cons = c.getConstructor(); + debugger = (JVMDebugger) cons.newInstance(); + attachDebugger(); + setupDebuggerExisting(); + + } catch (ClassNotFoundException cnfe) { + throw new DebuggerException("Cannot find alternate SA Debugger: '" + alternateName + "'"); + } catch (NoSuchMethodException nsme) { + throw new DebuggerException("Alternate SA Debugger: '" + alternateName + "' has missing constructor."); + } catch (InstantiationException ie) { + throw new DebuggerException("Alternate SA Debugger: '" + alternateName + "' fails to initialise: ", ie); + } catch (IllegalAccessException iae) { + throw new DebuggerException("Alternate SA Debugger: '" + alternateName + "' fails to initialise: ", iae); + } catch (InvocationTargetException iae) { + throw new DebuggerException("Alternate SA Debugger: '" + alternateName + "' fails to initialise: ", iae); + } + + System.err.println("Loaded alternate HotSpot SA Debugger: " + alternateName); + } + // // Solaris // @@ -466,6 +519,11 @@ public class HotSpotAgent { debugger = new RemoteDebuggerClient(remote); machDesc = ((RemoteDebuggerClient) debugger).getMachineDescription(); os = debugger.getOS(); + setupJVMLibNames(os); + cpu = debugger.getCPU(); + } + + private void setupJVMLibNames(String os) { if (os.equals("solaris")) { setupJVMLibNamesSolaris(); } else if (os.equals("win32")) { @@ -479,8 +537,6 @@ public class HotSpotAgent { } else { throw new RuntimeException("Unknown OS type"); } - - cpu = debugger.getCPU(); } private void setupJVMLibNamesSolaris() { diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/LinuxAddress.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/LinuxAddress.java index 9e85e133b3a..cff29ce8edc 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/LinuxAddress.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/LinuxAddress.java @@ -26,11 +26,11 @@ package sun.jvm.hotspot.debugger.linux; import sun.jvm.hotspot.debugger.*; -class LinuxAddress implements Address { +public class LinuxAddress implements Address { protected LinuxDebugger debugger; protected long addr; - LinuxAddress(LinuxDebugger debugger, long addr) { + public LinuxAddress(LinuxDebugger debugger, long addr) { this.debugger = debugger; this.addr = addr; } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/LinuxOopHandle.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/LinuxOopHandle.java index 310acb88ac7..99291aada29 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/LinuxOopHandle.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/LinuxOopHandle.java @@ -26,8 +26,8 @@ package sun.jvm.hotspot.debugger.linux; import sun.jvm.hotspot.debugger.*; -class LinuxOopHandle extends LinuxAddress implements OopHandle { - LinuxOopHandle(LinuxDebugger debugger, long addr) { +public class LinuxOopHandle extends LinuxAddress implements OopHandle { + public LinuxOopHandle(LinuxDebugger debugger, long addr) { super(debugger, addr); } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ArrayKlass.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ArrayKlass.java index f7cfb046d7d..9530cdd977a 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ArrayKlass.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/ArrayKlass.java @@ -49,7 +49,6 @@ public class ArrayKlass extends Klass { higherDimension = new MetadataField(type.getAddressField("_higher_dimension"), 0); lowerDimension = new MetadataField(type.getAddressField("_lower_dimension"), 0); vtableLen = new CIntField(type.getCIntegerField("_vtable_len"), 0); - allocSize = new CIntField(type.getCIntegerField("_alloc_size"), 0); componentMirror = new OopField(type.getOopField("_component_mirror"), 0); javaLangCloneableName = null; javaLangObjectName = null; @@ -64,7 +63,6 @@ public class ArrayKlass extends Klass { private static MetadataField higherDimension; private static MetadataField lowerDimension; private static CIntField vtableLen; - private static CIntField allocSize; private static OopField componentMirror; public Klass getJavaSuper() { @@ -76,7 +74,6 @@ public class ArrayKlass extends Klass { public Klass getHigherDimension() { return (Klass) higherDimension.getValue(this); } public Klass getLowerDimension() { return (Klass) lowerDimension.getValue(this); } public long getVtableLen() { return vtableLen.getValue(this); } - public long getAllocSize() { return allocSize.getValue(this); } public Oop getComponentMirror() { return componentMirror.getValue(this); } // constant class names - javaLangCloneable, javaIoSerializable, javaLangObject @@ -147,7 +144,6 @@ public class ArrayKlass extends Klass { visitor.doMetadata(higherDimension, true); visitor.doMetadata(lowerDimension, true); visitor.doCInt(vtableLen, true); - visitor.doCInt(allocSize, true); visitor.doOop(componentMirror, true); } } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/Klass.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/Klass.java index 63ac006ebb9..19a3668c7f3 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/Klass.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/oops/Klass.java @@ -57,7 +57,6 @@ public class Klass extends Metadata implements ClassConstants { accessFlags = new CIntField(type.getCIntegerField("_access_flags"), 0); subklass = new MetadataField(type.getAddressField("_subklass"), 0); nextSibling = new MetadataField(type.getAddressField("_next_sibling"), 0); - allocCount = new CIntField(type.getCIntegerField("_alloc_count"), 0); LH_INSTANCE_SLOW_PATH_BIT = db.lookupIntConstant("Klass::_lh_instance_slow_path_bit").intValue(); LH_LOG2_ELEMENT_SIZE_SHIFT = db.lookupIntConstant("Klass::_lh_log2_element_size_shift").intValue(); @@ -87,7 +86,6 @@ public class Klass extends Metadata implements ClassConstants { private static CIntField accessFlags; private static MetadataField subklass; private static MetadataField nextSibling; - private static CIntField allocCount; private Address getValue(AddressField field) { return addr.getAddressAt(field.getOffset()); @@ -108,7 +106,6 @@ public class Klass extends Metadata implements ClassConstants { public AccessFlags getAccessFlagsObj(){ return new AccessFlags(getAccessFlags()); } public Klass getSubklassKlass() { return (Klass) subklass.getValue(this); } public Klass getNextSiblingKlass() { return (Klass) nextSibling.getValue(this); } - public long getAllocCount() { return allocCount.getValue(this); } // computed access flags - takes care of inner classes etc. // This is closer to actual source level than getAccessFlags() etc. @@ -172,7 +169,6 @@ public class Klass extends Metadata implements ClassConstants { visitor.doCInt(accessFlags, true); visitor.doMetadata(subklass, true); visitor.doMetadata(nextSibling, true); - visitor.doCInt(allocCount, true); } public long getObjectSize() { diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java index 0a9d9436878..f84da894ac2 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java @@ -246,7 +246,7 @@ public class VM { } } - private static final boolean disableDerivedPrinterTableCheck; + private static final boolean disableDerivedPointerTableCheck; private static final Properties saProps; static { @@ -256,12 +256,12 @@ public class VM { url = VM.class.getClassLoader().getResource("sa.properties"); saProps.load(new BufferedInputStream(url.openStream())); } catch (Exception e) { - throw new RuntimeException("Unable to load properties " + + System.err.println("Unable to load properties " + (url == null ? "null" : url.toString()) + ": " + e.getMessage()); } - disableDerivedPrinterTableCheck = System.getProperty("sun.jvm.hotspot.runtime.VM.disableDerivedPointerTableCheck") != null; + disableDerivedPointerTableCheck = System.getProperty("sun.jvm.hotspot.runtime.VM.disableDerivedPointerTableCheck") != null; } private VM(TypeDataBase db, JVMDebugger debugger, boolean isBigEndian) { @@ -371,7 +371,8 @@ public class VM { /** This is used by the debugging system */ public static void initialize(TypeDataBase db, JVMDebugger debugger) { if (soleInstance != null) { - throw new RuntimeException("Attempt to initialize VM twice"); + // Using multiple SA Tool classes in the same process creates a call here. + return; } soleInstance = new VM(db, debugger, debugger.getMachineDescription().isBigEndian()); @@ -683,7 +684,7 @@ public class VM { /** Returns true if C2 derived pointer table should be used, false otherwise */ public boolean useDerivedPointerTable() { - return !disableDerivedPrinterTableCheck; + return !disableDerivedPointerTableCheck; } /** Returns the code cache; should not be used if is core build */ diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/ClassLoaderStats.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/ClassLoaderStats.java index 77f0f800445..eeda376b1d6 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/ClassLoaderStats.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/ClassLoaderStats.java @@ -41,6 +41,14 @@ import sun.jvm.hotspot.utilities.*; public class ClassLoaderStats extends Tool { boolean verbose = true; + public ClassLoaderStats() { + super(); + } + + public ClassLoaderStats(JVMDebugger d) { + super(d); + } + public static void main(String[] args) { ClassLoaderStats cls = new ClassLoaderStats(); cls.start(args); diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/FinalizerInfo.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/FinalizerInfo.java index 79e6784a63e..ed707b9ee8a 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/FinalizerInfo.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/FinalizerInfo.java @@ -24,6 +24,7 @@ package sun.jvm.hotspot.tools; +import sun.jvm.hotspot.debugger.JVMDebugger; import sun.jvm.hotspot.tools.*; import sun.jvm.hotspot.oops.*; @@ -42,6 +43,15 @@ import java.util.Comparator; * summary of these objects in the form of a histogram. */ public class FinalizerInfo extends Tool { + + public FinalizerInfo() { + super(); + } + + public FinalizerInfo(JVMDebugger d) { + super(d); + } + public static void main(String[] args) { FinalizerInfo finfo = new FinalizerInfo(); finfo.start(args); diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/FlagDumper.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/FlagDumper.java index effeabb582a..c8db6d6b044 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/FlagDumper.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/FlagDumper.java @@ -25,10 +25,19 @@ package sun.jvm.hotspot.tools; import java.io.PrintStream; +import sun.jvm.hotspot.debugger.JVMDebugger; import sun.jvm.hotspot.runtime.*; public class FlagDumper extends Tool { + public FlagDumper() { + super(); + } + + public FlagDumper(JVMDebugger d) { + super(d); + } + public void run() { VM.Flag[] flags = VM.getVM().getCommandLineFlags(); PrintStream out = System.out; diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/HeapDumper.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/HeapDumper.java index 5a7c06618b9..c5af0ed005d 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/HeapDumper.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/HeapDumper.java @@ -25,6 +25,7 @@ package sun.jvm.hotspot.tools; import sun.jvm.hotspot.utilities.HeapHprofBinWriter; +import sun.jvm.hotspot.debugger.JVMDebugger; import java.io.IOException; /* @@ -42,6 +43,11 @@ public class HeapDumper extends Tool { this.dumpFile = dumpFile; } + public HeapDumper(String dumpFile, JVMDebugger d) { + super(d); + this.dumpFile = dumpFile; + } + protected void printFlagsUsage() { System.out.println(" \tto dump heap to " + DEFAULT_DUMP_FILE); diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/HeapSummary.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/HeapSummary.java index 87621655269..a0123dd4c99 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/HeapSummary.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/HeapSummary.java @@ -29,12 +29,21 @@ import sun.jvm.hotspot.gc_interface.*; import sun.jvm.hotspot.gc_implementation.g1.*; import sun.jvm.hotspot.gc_implementation.parallelScavenge.*; import sun.jvm.hotspot.gc_implementation.shared.*; +import sun.jvm.hotspot.debugger.JVMDebugger; import sun.jvm.hotspot.memory.*; import sun.jvm.hotspot.oops.*; import sun.jvm.hotspot.runtime.*; public class HeapSummary extends Tool { + public HeapSummary() { + super(); + } + + public HeapSummary(JVMDebugger d) { + super(d); + } + public static void main(String[] args) { HeapSummary hs = new HeapSummary(); hs.start(args); diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JInfo.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JInfo.java index a9f6c0e9c90..f2452420744 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JInfo.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JInfo.java @@ -25,12 +25,21 @@ package sun.jvm.hotspot.tools; import sun.jvm.hotspot.runtime.*; +import sun.jvm.hotspot.debugger.JVMDebugger; public class JInfo extends Tool { + public JInfo() { + super(); + } + public JInfo(int m) { mode = m; } + public JInfo(JVMDebugger d) { + super(d); + } + protected boolean needsJavaPrefix() { return false; } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JMap.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JMap.java index d9ea364edaa..f6f3c0741c0 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JMap.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JMap.java @@ -25,6 +25,7 @@ package sun.jvm.hotspot.tools; import java.io.*; +import sun.jvm.hotspot.debugger.JVMDebugger; import sun.jvm.hotspot.utilities.*; public class JMap extends Tool { @@ -36,6 +37,10 @@ public class JMap extends Tool { this(MODE_PMAP); } + public JMap(JVMDebugger d) { + super(d); + } + protected boolean needsJavaPrefix() { return false; } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JSnap.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JSnap.java index 95f46445f8a..9301f1059fd 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JSnap.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JSnap.java @@ -25,9 +25,19 @@ package sun.jvm.hotspot.tools; import java.io.*; +import sun.jvm.hotspot.debugger.JVMDebugger; import sun.jvm.hotspot.runtime.*; public class JSnap extends Tool { + + public JSnap() { + super(); + } + + public JSnap(JVMDebugger d) { + super(d); + } + public void run() { final PrintStream out = System.out; if (PerfMemory.initialized()) { diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JStack.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JStack.java index 9e0688cf393..7cbe8f4d945 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JStack.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/JStack.java @@ -24,6 +24,8 @@ package sun.jvm.hotspot.tools; +import sun.jvm.hotspot.debugger.JVMDebugger; + public class JStack extends Tool { public JStack(boolean mixedMode, boolean concurrentLocks) { this.mixedMode = mixedMode; @@ -34,6 +36,10 @@ public class JStack extends Tool { this(true, true); } + public JStack(JVMDebugger d) { + super(d); + } + protected boolean needsJavaPrefix() { return false; } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/ObjectHistogram.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/ObjectHistogram.java index f03469e13f1..168202eec2c 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/ObjectHistogram.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/ObjectHistogram.java @@ -33,6 +33,14 @@ import java.io.PrintStream; an object histogram from a remote or crashed VM. */ public class ObjectHistogram extends Tool { + public ObjectHistogram() { + super(); + } + + public ObjectHistogram(JVMDebugger d) { + super(d); + } + public void run() { run(System.out, System.err); } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/PMap.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/PMap.java index 70bd55513b9..2a234130991 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/PMap.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/PMap.java @@ -31,6 +31,15 @@ import sun.jvm.hotspot.debugger.cdbg.*; import sun.jvm.hotspot.runtime.*; public class PMap extends Tool { + + public PMap() { + super(); + } + + public PMap(JVMDebugger d) { + super(d); + } + public void run() { run(System.out); } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/PStack.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/PStack.java index 0b3720ff594..7f10612b317 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/PStack.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/PStack.java @@ -45,6 +45,10 @@ public class PStack extends Tool { this(true, true); } + public PStack(JVMDebugger d) { + super(d); + } + public void run() { run(System.out); } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/StackTrace.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/StackTrace.java index 83270bfdeff..eb0cc88d116 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/StackTrace.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/StackTrace.java @@ -45,6 +45,16 @@ public class StackTrace extends Tool { run(System.out); } + public StackTrace(JVMDebugger d) { + super(d); + } + + public StackTrace(JVMDebugger d, boolean v, boolean concurrentLocks) { + super(d); + this.verbose = v; + this.concurrentLocks = concurrentLocks; + } + public void run(java.io.PrintStream tty) { // Ready to go with the database... try { diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/SysPropsDumper.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/SysPropsDumper.java index bb4f703c64b..d601fef4401 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/SysPropsDumper.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/SysPropsDumper.java @@ -27,10 +27,19 @@ package sun.jvm.hotspot.tools; import java.io.PrintStream; import java.util.*; +import sun.jvm.hotspot.debugger.JVMDebugger; import sun.jvm.hotspot.runtime.*; public class SysPropsDumper extends Tool { + public SysPropsDumper() { + super(); + } + + public SysPropsDumper(JVMDebugger d) { + super(d); + } + public void run() { Properties sysProps = VM.getVM().getSystemProperties(); PrintStream out = System.out; diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/Tool.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/Tool.java index 4279c425bd8..3021801c9dd 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/Tool.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/Tool.java @@ -35,6 +35,7 @@ import sun.jvm.hotspot.debugger.*; public abstract class Tool implements Runnable { private HotSpotAgent agent; + private JVMDebugger jvmDebugger; private int debugeeType; // debugeeType is one of constants below @@ -42,6 +43,13 @@ public abstract class Tool implements Runnable { protected static final int DEBUGEE_CORE = 1; protected static final int DEBUGEE_REMOTE = 2; + public Tool() { + } + + public Tool(JVMDebugger d) { + jvmDebugger = d; + } + public String getName() { return getClass().getName(); } @@ -90,7 +98,6 @@ public abstract class Tool implements Runnable { protected void usage() { printUsage(); - System.exit(1); } /* @@ -106,13 +113,13 @@ public abstract class Tool implements Runnable { protected void stop() { if (agent != null) { agent.detach(); - System.exit(0); } } protected void start(String[] args) { if ((args.length < 1) || (args.length > 2)) { usage(); + return; } // Attempt to handle -h or -help or some invalid flag @@ -185,13 +192,31 @@ public abstract class Tool implements Runnable { } if (e.getMessage() != null) { err.print(e.getMessage()); + e.printStackTrace(); } err.println(); - System.exit(1); + return; } err.println("Debugger attached successfully."); + startInternal(); + } + // When using an existing JVMDebugger. + public void start() { + + if (jvmDebugger == null) { + throw new RuntimeException("Tool.start() called with no JVMDebugger set."); + } + agent = new HotSpotAgent(); + agent.attach(jvmDebugger); + startInternal(); + } + + // Remains of the start mechanism, common to both start methods. + private void startInternal() { + + PrintStream err = System.err; VM vm = VM.getVM(); if (vm.isCore()) { err.println("Core build detected."); diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/jcore/ClassDump.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/jcore/ClassDump.java index 34ccc102acb..96817b26226 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/jcore/ClassDump.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/jcore/ClassDump.java @@ -25,6 +25,7 @@ package sun.jvm.hotspot.tools.jcore; import java.io.*; +import java.lang.reflect.Constructor; import java.util.jar.JarOutputStream; import java.util.jar.JarEntry; import java.util.jar.Manifest; @@ -38,6 +39,16 @@ public class ClassDump extends Tool { private ClassFilter classFilter; private String outputDirectory; private JarOutputStream jarStream; + private String pkgList; + + public ClassDump() { + super(); + } + + public ClassDump(JVMDebugger d, String pkgList) { + super(d); + this.pkgList = pkgList; + } public void setClassFilter(ClassFilter cf) { classFilter = cf; @@ -63,6 +74,25 @@ public class ClassDump extends Tool { public void run() { // Ready to go with the database... try { + // The name of the filter always comes from a System property. + // If we have a pkgList, pass it, otherwise let the filter read + // its own System property for the list of classes. + String filterClassName = System.getProperty("sun.jvm.hotspot.tools.jcore.filter", + "sun.jvm.hotspot.tools.jcore.PackageNameFilter"); + try { + Class filterClass = Class.forName(filterClassName); + if (pkgList == null) { + classFilter = (ClassFilter) filterClass.newInstance(); + } else { + Constructor con = filterClass.getConstructor(String.class); + classFilter = (ClassFilter) con.newInstance(pkgList); + } + } catch(Exception exp) { + System.err.println("Warning: Can not create class filter!"); + } + + String outputDirectory = System.getProperty("sun.jvm.hotspot.tools.jcore.outputDir", "."); + setOutputDirectory(outputDirectory); // walk through the system dictionary SystemDictionary dict = VM.getVM().getSystemDictionary(); @@ -139,26 +169,8 @@ public class ClassDump extends Tool { } public static void main(String[] args) { - // load class filters - ClassFilter classFilter = null; - String filterClassName = System.getProperty("sun.jvm.hotspot.tools.jcore.filter"); - if (filterClassName != null) { - try { - Class filterClass = Class.forName(filterClassName); - classFilter = (ClassFilter) filterClass.newInstance(); - } catch(Exception exp) { - System.err.println("Warning: Can not create class filter!"); - } - } - - String outputDirectory = System.getProperty("sun.jvm.hotspot.tools.jcore.outputDir"); - if (outputDirectory == null) - outputDirectory = "."; - ClassDump cd = new ClassDump(); - cd.setClassFilter(classFilter); - cd.setOutputDirectory(outputDirectory); cd.start(args); cd.stop(); } diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/soql/JSDB.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/soql/JSDB.java index e46de0194d7..09874af178e 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/soql/JSDB.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/soql/JSDB.java @@ -24,12 +24,22 @@ package sun.jvm.hotspot.tools.soql; +import sun.jvm.hotspot.debugger.JVMDebugger; import sun.jvm.hotspot.tools.*; import sun.jvm.hotspot.utilities.*; import sun.jvm.hotspot.utilities.soql.*; /** This is command line JavaScript debugger console */ public class JSDB extends Tool { + + public JSDB() { + super(); + } + + public JSDB(JVMDebugger d) { + super(d); + } + public static void main(String[] args) { JSDB jsdb = new JSDB(); jsdb.start(args); diff --git a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/soql/SOQL.java b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/soql/SOQL.java index 3a4c2470b1b..b3054b90bd0 100644 --- a/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/soql/SOQL.java +++ b/hotspot/agent/src/share/classes/sun/jvm/hotspot/tools/soql/SOQL.java @@ -44,6 +44,14 @@ public class SOQL extends Tool { soql.stop(); } + public SOQL() { + super(); + } + + public SOQL(JVMDebugger d) { + super(d); + } + protected SOQLEngine soqlEngine; protected BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); protected PrintStream out = System.out; diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-debug b/hotspot/make/bsd/makefiles/mapfile-vers-debug index d371239ab06..9a8fc822bc4 100644 --- a/hotspot/make/bsd/makefiles/mapfile-vers-debug +++ b/hotspot/make/bsd/makefiles/mapfile-vers-debug @@ -221,7 +221,6 @@ _JVM_SetLength _JVM_SetNativeThreadName _JVM_SetPrimitiveArrayElement - _JVM_SetProtectionDomain _JVM_SetSockOpt _JVM_SetThreadPriority _JVM_Sleep diff --git a/hotspot/make/bsd/makefiles/mapfile-vers-product b/hotspot/make/bsd/makefiles/mapfile-vers-product index ba9cb516620..d446cc81d84 100644 --- a/hotspot/make/bsd/makefiles/mapfile-vers-product +++ b/hotspot/make/bsd/makefiles/mapfile-vers-product @@ -221,7 +221,6 @@ _JVM_SetLength _JVM_SetNativeThreadName _JVM_SetPrimitiveArrayElement - _JVM_SetProtectionDomain _JVM_SetSockOpt _JVM_SetThreadPriority _JVM_Sleep diff --git a/hotspot/make/hotspot_version b/hotspot/make/hotspot_version index 17088cd02f9..b373e5fb0f6 100644 --- a/hotspot/make/hotspot_version +++ b/hotspot/make/hotspot_version @@ -35,7 +35,7 @@ HOTSPOT_VM_COPYRIGHT=Copyright 2013 HS_MAJOR_VER=25 HS_MINOR_VER=0 -HS_BUILD_NUMBER=39 +HS_BUILD_NUMBER=43 JDK_MAJOR_VER=1 JDK_MINOR_VER=8 diff --git a/hotspot/make/linux/makefiles/mapfile-vers-debug b/hotspot/make/linux/makefiles/mapfile-vers-debug index b18fb74fd9a..68be2ffefb3 100644 --- a/hotspot/make/linux/makefiles/mapfile-vers-debug +++ b/hotspot/make/linux/makefiles/mapfile-vers-debug @@ -223,7 +223,6 @@ SUNWprivate_1.1 { JVM_SetLength; JVM_SetNativeThreadName; JVM_SetPrimitiveArrayElement; - JVM_SetProtectionDomain; JVM_SetSockOpt; JVM_SetThreadPriority; JVM_Sleep; diff --git a/hotspot/make/linux/makefiles/mapfile-vers-product b/hotspot/make/linux/makefiles/mapfile-vers-product index 168d84c1e90..4641af0af20 100644 --- a/hotspot/make/linux/makefiles/mapfile-vers-product +++ b/hotspot/make/linux/makefiles/mapfile-vers-product @@ -223,7 +223,6 @@ SUNWprivate_1.1 { JVM_SetLength; JVM_SetNativeThreadName; JVM_SetPrimitiveArrayElement; - JVM_SetProtectionDomain; JVM_SetSockOpt; JVM_SetThreadPriority; JVM_Sleep; diff --git a/hotspot/make/linux/makefiles/vm.make b/hotspot/make/linux/makefiles/vm.make index 3c3bd2e2d16..7df141f8895 100644 --- a/hotspot/make/linux/makefiles/vm.make +++ b/hotspot/make/linux/makefiles/vm.make @@ -46,6 +46,7 @@ ifeq ($(findstring true, $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true) include $(MAKEFILES_DIR)/zeroshark.make else include $(MAKEFILES_DIR)/$(BUILDARCH).make + -include $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make endif # set VPATH so make knows where to look for source files @@ -211,6 +212,12 @@ ifeq ($(Platform_arch_model), x86_64) Src_Files_EXCLUDE += \*x86_32\* endif +# Alternate vm.make +# This has to be included here to allow changes to the source +# directories and excluded files before they are expanded +# by the definition of Src_Files. +-include $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/vm.make + # Locate all source files in the given directory, excluding files in Src_Files_EXCLUDE. define findsrc $(notdir $(shell find $(1)/. ! -name . -prune \ @@ -380,4 +387,4 @@ build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(LIBJVM_DB) $(BUILDLIBSAPROC) dtraceChe install: install_jvm install_jsig install_saproc -.PHONY: default build install install_jvm +.PHONY: default build install install_jvm $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/$(BUILDARCH).make $(HS_ALT_MAKE)/$(Platform_os_family)/makefiles/vm.make diff --git a/hotspot/make/solaris/makefiles/mapfile-vers b/hotspot/make/solaris/makefiles/mapfile-vers index 1a0b572a5c6..01b31b6fffb 100644 --- a/hotspot/make/solaris/makefiles/mapfile-vers +++ b/hotspot/make/solaris/makefiles/mapfile-vers @@ -223,7 +223,6 @@ SUNWprivate_1.1 { JVM_SetLength; JVM_SetNativeThreadName; JVM_SetPrimitiveArrayElement; - JVM_SetProtectionDomain; JVM_SetSockOpt; JVM_SetThreadPriority; JVM_Sleep; diff --git a/hotspot/make/windows/makefiles/compile.make b/hotspot/make/windows/makefiles/compile.make index ea16fca3dde..6f8dcce3406 100644 --- a/hotspot/make/windows/makefiles/compile.make +++ b/hotspot/make/windows/makefiles/compile.make @@ -1,5 +1,5 @@ # -# Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 1997, 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 @@ -110,6 +110,7 @@ CXX_FLAGS=$(CXX_FLAGS) /D TARGET_COMPILER_visCPP # 1400 is for VS2005 # 1500 is for VS2008 # 1600 is for VS2010 +# 1700 is for VS2012 # Do not confuse this MSC_VER with the predefined macro _MSC_VER that the # compiler provides, when MSC_VER==1399, _MSC_VER will be 1400. # Normally they are the same, but a pre-release of the VS2005 compilers @@ -142,6 +143,9 @@ COMPILER_NAME=VS2008 !if "$(MSC_VER)" == "1600" COMPILER_NAME=VS2010 !endif +!if "$(MSC_VER)" == "1700" +COMPILER_NAME=VS2012 +!endif !endif # By default, we do not want to use the debug version of the msvcrt.dll file @@ -151,9 +155,13 @@ MS_RUNTIME_OPTION = /MD MS_RUNTIME_OPTION = /MTd /D "_DEBUG" !endif +# VS2012 and later won't work with: +# /D _STATIC_CPPLIB /D _DISABLE_DEPRECATE_STATIC_CPPLIB +!if "$(MSC_VER)" < "1700" # Always add the _STATIC_CPPLIB flag STATIC_CPPLIB_OPTION = /D _STATIC_CPPLIB /D _DISABLE_DEPRECATE_STATIC_CPPLIB MS_RUNTIME_OPTION = $(MS_RUNTIME_OPTION) $(STATIC_CPPLIB_OPTION) +!endif CXX_FLAGS=$(CXX_FLAGS) $(MS_RUNTIME_OPTION) # How /GX option is spelled @@ -221,6 +229,22 @@ LD_FLAGS = /SAFESEH $(LD_FLAGS) !endif !endif +!if "$(COMPILER_NAME)" == "VS2012" +PRODUCT_OPT_OPTION = /O2 /Oy- +FASTDEBUG_OPT_OPTION = /O2 /Oy- +DEBUG_OPT_OPTION = /Od +GX_OPTION = /EHsc +LD_FLAGS = /manifest $(LD_FLAGS) +# Manifest Tool - used in VS2005 and later to adjust manifests stored +# as resources inside build artifacts. +!if "x$(MT)" == "x" +MT=mt.exe +!endif +!if "$(BUILDARCH)" == "i486" +LD_FLAGS = /SAFESEH $(LD_FLAGS) +!endif +!endif + # If NO_OPTIMIZATIONS is defined in the environment, turn everything off !ifdef NO_OPTIMIZATIONS PRODUCT_OPT_OPTION = $(DEBUG_OPT_OPTION) diff --git a/hotspot/make/windows/makefiles/sanity.make b/hotspot/make/windows/makefiles/sanity.make index 86c6b59aefe..b502cfaa65f 100644 --- a/hotspot/make/windows/makefiles/sanity.make +++ b/hotspot/make/windows/makefiles/sanity.make @@ -1,5 +1,5 @@ # -# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved. +# Copyright (c) 2006, 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 @@ -27,9 +27,9 @@ all: checkCL checkLink checkCL: - @ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" \ + @ if "$(MSC_VER)" NEQ "1310" if "$(MSC_VER)" NEQ "1399" if "$(MSC_VER)" NEQ "1400" if "$(MSC_VER)" NEQ "1500" if "$(MSC_VER)" NEQ "1600" if "$(MSC_VER)" NEQ "1700" \ echo *** WARNING *** unrecognized cl.exe version $(MSC_VER) ($(RAW_MSC_VER)). Use FORCE_MSC_VER to override automatic detection. checkLink: - @ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" \ + @ if "$(LD_VER)" NEQ "710" if "$(LD_VER)" NEQ "800" if "$(LD_VER)" NEQ "900" if "$(LD_VER)" NEQ "1000" if "$(LD_VER)" NEQ "1100" \ echo *** WARNING *** unrecognized link.exe version $(LD_VER) ($(RAW_LD_VER)). Use FORCE_LD_VER to override automatic detection. diff --git a/hotspot/make/windows/makefiles/vm.make b/hotspot/make/windows/makefiles/vm.make index 54ba1eef5b8..b76443774de 100644 --- a/hotspot/make/windows/makefiles/vm.make +++ b/hotspot/make/windows/makefiles/vm.make @@ -132,6 +132,10 @@ CXX_DONT_USE_PCH=/D DONT_USE_PRECOMPILED_HEADER !if "$(USE_PRECOMPILED_HEADER)" != "0" CXX_USE_PCH=/Fp"vm.pch" /Yu"precompiled.hpp" +!if "$(COMPILER_NAME)" == "VS2012" +# VS2012 requires this object file to be listed: +LD_FLAGS=$(LD_FLAGS) _build_pch_file.obj +!endif !else CXX_USE_PCH=$(CXX_DONT_USE_PCH) !endif diff --git a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp index 1cbc5c41316..64745015923 100644 --- a/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -2946,6 +2946,9 @@ void LIR_Assembler::monitor_address(int monitor_no, LIR_Opr dst_opr) { } } +void LIR_Assembler::emit_updatecrc32(LIR_OpUpdateCRC32* op) { + fatal("CRC32 intrinsic is not implemented on this platform"); +} void LIR_Assembler::emit_lock(LIR_OpLock* op) { Register obj = op->obj_opr()->as_register(); diff --git a/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp index 82cc696e8b7..dc3bc8691ac 100644 --- a/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -784,6 +784,10 @@ void LIRGenerator::do_ArrayCopy(Intrinsic* x) { set_no_result(x); } +void LIRGenerator::do_update_CRC32(Intrinsic* x) { + fatal("CRC32 intrinsic is not implemented on this platform"); +} + // _i2l, _i2f, _i2d, _l2i, _l2f, _l2d, _f2i, _f2l, _f2d, _d2i, _d2l, _d2f // _i2b, _i2c, _i2s void LIRGenerator::do_Convert(Convert* x) { diff --git a/hotspot/src/cpu/sparc/vm/c1_globals_sparc.hpp b/hotspot/src/cpu/sparc/vm/c1_globals_sparc.hpp index a43a9cee538..c6cf521272d 100644 --- a/hotspot/src/cpu/sparc/vm/c1_globals_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/c1_globals_sparc.hpp @@ -49,8 +49,9 @@ define_pd_global(intx, FreqInlineSize, 325 ); define_pd_global(bool, ResizeTLAB, true ); define_pd_global(intx, ReservedCodeCacheSize, 32*M ); define_pd_global(intx, CodeCacheExpansionSize, 32*K ); -define_pd_global(uintx,CodeCacheMinBlockLength, 1); -define_pd_global(uintx,MetaspaceSize, 12*M ); +define_pd_global(uintx, CodeCacheMinBlockLength, 1); +define_pd_global(uintx, CodeCacheMinimumUseSpace, 400*K); +define_pd_global(uintx, MetaspaceSize, 12*M ); define_pd_global(bool, NeverActAsServerClassMachine, true ); define_pd_global(intx, NewSizeThreadIncrease, 16*K ); define_pd_global(uint64_t,MaxRAM, 1ULL*G); diff --git a/hotspot/src/cpu/sparc/vm/c2_globals_sparc.hpp b/hotspot/src/cpu/sparc/vm/c2_globals_sparc.hpp index c642e915fe1..e32094deb06 100644 --- a/hotspot/src/cpu/sparc/vm/c2_globals_sparc.hpp +++ b/hotspot/src/cpu/sparc/vm/c2_globals_sparc.hpp @@ -86,7 +86,8 @@ define_pd_global(intx, CodeCacheExpansionSize, 32*K); // Ergonomics related flags define_pd_global(uint64_t,MaxRAM, 4ULL*G); #endif -define_pd_global(uintx,CodeCacheMinBlockLength, 4); +define_pd_global(uintx, CodeCacheMinBlockLength, 4); +define_pd_global(uintx, CodeCacheMinimumUseSpace, 400*K); // Heap related flags define_pd_global(uintx,MetaspaceSize, ScaleForWordSize(16*M)); diff --git a/hotspot/src/cpu/sparc/vm/frame_sparc.cpp b/hotspot/src/cpu/sparc/vm/frame_sparc.cpp index 55f344f55a1..ac9746679b3 100644 --- a/hotspot/src/cpu/sparc/vm/frame_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/frame_sparc.cpp @@ -257,11 +257,6 @@ bool frame::safe_for_sender(JavaThread *thread) { return false; } - // Could be a zombie method - if (sender_blob->is_zombie() || sender_blob->is_unloaded()) { - return false; - } - // It should be safe to construct the sender though it might not be valid frame sender(_SENDER_SP, younger_sp, adjusted_stack); diff --git a/hotspot/src/cpu/sparc/vm/frame_sparc.inline.hpp b/hotspot/src/cpu/sparc/vm/frame_sparc.inline.hpp index 71655f6d760..774e8f3f0f5 100644 --- a/hotspot/src/cpu/sparc/vm/frame_sparc.inline.hpp +++ b/hotspot/src/cpu/sparc/vm/frame_sparc.inline.hpp @@ -240,10 +240,10 @@ inline ConstantPoolCache** frame::interpreter_frame_cache_addr() const { #endif // CC_INTERP -inline JavaCallWrapper* frame::entry_frame_call_wrapper() const { +inline JavaCallWrapper** frame::entry_frame_call_wrapper_addr() const { // note: adjust this code if the link argument in StubGenerator::call_stub() changes! const Argument link = Argument(0, false); - return (JavaCallWrapper*)sp()[link.as_in().as_register()->sp_offset_in_saved_window()]; + return (JavaCallWrapper**)&sp()[link.as_in().as_register()->sp_offset_in_saved_window()]; } diff --git a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp index 494c1bc405a..214940cdbfb 100644 --- a/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp +++ b/hotspot/src/cpu/sparc/vm/stubGenerator_sparc.cpp @@ -410,6 +410,51 @@ class StubGenerator: public StubCodeGenerator { return start; } + // Safefetch stubs. + void generate_safefetch(const char* name, int size, address* entry, + address* fault_pc, address* continuation_pc) { + // safefetch signatures: + // int SafeFetch32(int* adr, int errValue); + // intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue); + // + // arguments: + // o0 = adr + // o1 = errValue + // + // result: + // o0 = *adr or errValue + + StubCodeMark mark(this, "StubRoutines", name); + + // Entry point, pc or function descriptor. + __ align(CodeEntryAlignment); + *entry = __ pc(); + + __ mov(O0, G1); // g1 = o0 + __ mov(O1, O0); // o0 = o1 + // Load *adr into c_rarg1, may fault. + *fault_pc = __ pc(); + switch (size) { + case 4: + // int32_t + __ ldsw(G1, 0, O0); // o0 = [g1] + break; + case 8: + // int64_t + __ ldx(G1, 0, O0); // o0 = [g1] + break; + default: + ShouldNotReachHere(); + } + + // return errValue or *adr + *continuation_pc = __ pc(); + // By convention with the trap handler we ensure there is a non-CTI + // instruction in the trap shadow. + __ nop(); + __ retl(); + __ delayed()->nop(); + } //------------------------------------------------------------------------------------------------------------------------ // Continuation point for throwing of implicit exceptions that are not handled in @@ -3315,6 +3360,14 @@ class StubGenerator: public StubCodeGenerator { // Don't initialize the platform math functions since sparc // doesn't have intrinsics for these operations. + + // Safefetch stubs. + generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry, + &StubRoutines::_safefetch32_fault_pc, + &StubRoutines::_safefetch32_continuation_pc); + generate_safefetch("SafeFetchN", sizeof(intptr_t), &StubRoutines::_safefetchN_entry, + &StubRoutines::_safefetchN_fault_pc, + &StubRoutines::_safefetchN_continuation_pc); } diff --git a/hotspot/src/cpu/x86/vm/assembler_x86.cpp b/hotspot/src/cpu/x86/vm/assembler_x86.cpp index 02a438f2f40..761b5c3259f 100644 --- a/hotspot/src/cpu/x86/vm/assembler_x86.cpp +++ b/hotspot/src/cpu/x86/vm/assembler_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -1673,6 +1673,11 @@ void Assembler::movdqa(XMMRegister dst, XMMRegister src) { emit_simd_arith_nonds(0x6F, dst, src, VEX_SIMD_66); } +void Assembler::movdqa(XMMRegister dst, Address src) { + NOT_LP64(assert(VM_Version::supports_sse2(), "")); + emit_simd_arith_nonds(0x6F, dst, src, VEX_SIMD_66); +} + void Assembler::movdqu(XMMRegister dst, Address src) { NOT_LP64(assert(VM_Version::supports_sse2(), "")); emit_simd_arith_nonds(0x6F, dst, src, VEX_SIMD_F3); @@ -2286,6 +2291,38 @@ void Assembler::pcmpestri(XMMRegister dst, XMMRegister src, int imm8) { emit_int8(imm8); } +void Assembler::pextrd(Register dst, XMMRegister src, int imm8) { + assert(VM_Version::supports_sse4_1(), ""); + int encode = simd_prefix_and_encode(as_XMMRegister(dst->encoding()), xnoreg, src, VEX_SIMD_66, VEX_OPCODE_0F_3A, false); + emit_int8(0x16); + emit_int8((unsigned char)(0xC0 | encode)); + emit_int8(imm8); +} + +void Assembler::pextrq(Register dst, XMMRegister src, int imm8) { + assert(VM_Version::supports_sse4_1(), ""); + int encode = simd_prefix_and_encode(as_XMMRegister(dst->encoding()), xnoreg, src, VEX_SIMD_66, VEX_OPCODE_0F_3A, true); + emit_int8(0x16); + emit_int8((unsigned char)(0xC0 | encode)); + emit_int8(imm8); +} + +void Assembler::pinsrd(XMMRegister dst, Register src, int imm8) { + assert(VM_Version::supports_sse4_1(), ""); + int encode = simd_prefix_and_encode(dst, dst, as_XMMRegister(src->encoding()), VEX_SIMD_66, VEX_OPCODE_0F_3A, false); + emit_int8(0x22); + emit_int8((unsigned char)(0xC0 | encode)); + emit_int8(imm8); +} + +void Assembler::pinsrq(XMMRegister dst, Register src, int imm8) { + assert(VM_Version::supports_sse4_1(), ""); + int encode = simd_prefix_and_encode(dst, dst, as_XMMRegister(src->encoding()), VEX_SIMD_66, VEX_OPCODE_0F_3A, true); + emit_int8(0x22); + emit_int8((unsigned char)(0xC0 | encode)); + emit_int8(imm8); +} + void Assembler::pmovzxbw(XMMRegister dst, Address src) { assert(VM_Version::supports_sse4_1(), ""); InstructionMark im(this); @@ -3691,6 +3728,16 @@ void Assembler::vpbroadcastd(XMMRegister dst, XMMRegister src) { emit_int8((unsigned char)(0xC0 | encode)); } +// Carry-Less Multiplication Quadword +void Assembler::vpclmulqdq(XMMRegister dst, XMMRegister nds, XMMRegister src, int mask) { + assert(VM_Version::supports_avx() && VM_Version::supports_clmul(), ""); + bool vector256 = false; + int encode = vex_prefix_and_encode(dst, nds, src, VEX_SIMD_66, vector256, VEX_OPCODE_0F_3A); + emit_int8(0x44); + emit_int8((unsigned char)(0xC0 | encode)); + emit_int8((unsigned char)mask); +} + void Assembler::vzeroupper() { assert(VM_Version::supports_avx(), ""); (void)vex_prefix_and_encode(xmm0, xmm0, xmm0, VEX_SIMD_NONE); diff --git a/hotspot/src/cpu/x86/vm/assembler_x86.hpp b/hotspot/src/cpu/x86/vm/assembler_x86.hpp index 97a5bfc0368..31481b5808f 100644 --- a/hotspot/src/cpu/x86/vm/assembler_x86.hpp +++ b/hotspot/src/cpu/x86/vm/assembler_x86.hpp @@ -1266,6 +1266,7 @@ private: // Move Aligned Double Quadword void movdqa(XMMRegister dst, XMMRegister src); + void movdqa(XMMRegister dst, Address src); // Move Unaligned Double Quadword void movdqu(Address dst, XMMRegister src); @@ -1404,6 +1405,14 @@ private: void pcmpestri(XMMRegister xmm1, XMMRegister xmm2, int imm8); void pcmpestri(XMMRegister xmm1, Address src, int imm8); + // SSE 4.1 extract + void pextrd(Register dst, XMMRegister src, int imm8); + void pextrq(Register dst, XMMRegister src, int imm8); + + // SSE 4.1 insert + void pinsrd(XMMRegister dst, Register src, int imm8); + void pinsrq(XMMRegister dst, Register src, int imm8); + // SSE4.1 packed move void pmovzxbw(XMMRegister dst, XMMRegister src); void pmovzxbw(XMMRegister dst, Address src); @@ -1764,6 +1773,9 @@ private: // duplicate 4-bytes integer data from src into 8 locations in dest void vpbroadcastd(XMMRegister dst, XMMRegister src); + // Carry-Less Multiplication Quadword + void vpclmulqdq(XMMRegister dst, XMMRegister nds, XMMRegister src, int mask); + // AVX instruction which is used to clear upper 128 bits of YMM registers and // to avoid transaction penalty between AVX and SSE states. There is no // penalty if legacy SSE instructions are encoded using VEX prefix because diff --git a/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp b/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp index a99d7939373..b5bceeb60c6 100644 --- a/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -3512,6 +3512,22 @@ void LIR_Assembler::emit_arraycopy(LIR_OpArrayCopy* op) { __ bind(*stub->continuation()); } +void LIR_Assembler::emit_updatecrc32(LIR_OpUpdateCRC32* op) { + assert(op->crc()->is_single_cpu(), "crc must be register"); + assert(op->val()->is_single_cpu(), "byte value must be register"); + assert(op->result_opr()->is_single_cpu(), "result must be register"); + Register crc = op->crc()->as_register(); + Register val = op->val()->as_register(); + Register res = op->result_opr()->as_register(); + + assert_different_registers(val, crc, res); + + __ lea(res, ExternalAddress(StubRoutines::crc_table_addr())); + __ notl(crc); // ~crc + __ update_byte_crc32(crc, val, res); + __ notl(crc); // ~crc + __ mov(res, crc); +} void LIR_Assembler::emit_lock(LIR_OpLock* op) { Register obj = op->obj_opr()->as_register(); // may not be an oop diff --git a/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp b/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp index 6810ae54216..e6638581bcf 100644 --- a/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp +++ b/hotspot/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -932,6 +932,81 @@ void LIRGenerator::do_ArrayCopy(Intrinsic* x) { __ arraycopy(src.result(), src_pos.result(), dst.result(), dst_pos.result(), length.result(), tmp, expected_type, flags, info); // does add_safepoint } +void LIRGenerator::do_update_CRC32(Intrinsic* x) { + assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support"); + // Make all state_for calls early since they can emit code + LIR_Opr result = rlock_result(x); + int flags = 0; + switch (x->id()) { + case vmIntrinsics::_updateCRC32: { + LIRItem crc(x->argument_at(0), this); + LIRItem val(x->argument_at(1), this); + crc.load_item(); + val.load_item(); + __ update_crc32(crc.result(), val.result(), result); + break; + } + case vmIntrinsics::_updateBytesCRC32: + case vmIntrinsics::_updateByteBufferCRC32: { + bool is_updateBytes = (x->id() == vmIntrinsics::_updateBytesCRC32); + + LIRItem crc(x->argument_at(0), this); + LIRItem buf(x->argument_at(1), this); + LIRItem off(x->argument_at(2), this); + LIRItem len(x->argument_at(3), this); + buf.load_item(); + off.load_nonconstant(); + + LIR_Opr index = off.result(); + int offset = is_updateBytes ? arrayOopDesc::base_offset_in_bytes(T_BYTE) : 0; + if(off.result()->is_constant()) { + index = LIR_OprFact::illegalOpr; + offset += off.result()->as_jint(); + } + LIR_Opr base_op = buf.result(); + +#ifndef _LP64 + if (!is_updateBytes) { // long b raw address + base_op = new_register(T_INT); + __ convert(Bytecodes::_l2i, buf.result(), base_op); + } +#else + if (index->is_valid()) { + LIR_Opr tmp = new_register(T_LONG); + __ convert(Bytecodes::_i2l, index, tmp); + index = tmp; + } +#endif + + LIR_Address* a = new LIR_Address(base_op, + index, + LIR_Address::times_1, + offset, + T_BYTE); + BasicTypeList signature(3); + signature.append(T_INT); + signature.append(T_ADDRESS); + signature.append(T_INT); + CallingConvention* cc = frame_map()->c_calling_convention(&signature); + const LIR_Opr result_reg = result_register_for(x->type()); + + LIR_Opr addr = new_pointer_register(); + __ leal(LIR_OprFact::address(a), addr); + + crc.load_item_force(cc->at(0)); + __ move(addr, cc->at(1)); + len.load_item_force(cc->at(2)); + + __ call_runtime_leaf(StubRoutines::updateBytesCRC32(), getThreadTemp(), result_reg, cc->args()); + __ move(result_reg, result); + + break; + } + default: { + ShouldNotReachHere(); + } + } +} // _i2l, _i2f, _i2d, _l2i, _l2f, _l2d, _f2i, _f2l, _f2d, _d2i, _d2l, _d2f // _i2b, _i2c, _i2s diff --git a/hotspot/src/cpu/x86/vm/c1_globals_x86.hpp b/hotspot/src/cpu/x86/vm/c1_globals_x86.hpp index 98e02b16cd0..13f3df82c29 100644 --- a/hotspot/src/cpu/x86/vm/c1_globals_x86.hpp +++ b/hotspot/src/cpu/x86/vm/c1_globals_x86.hpp @@ -50,8 +50,9 @@ define_pd_global(intx, InitialCodeCacheSize, 160*K); define_pd_global(intx, ReservedCodeCacheSize, 32*M ); define_pd_global(bool, ProfileInterpreter, false); define_pd_global(intx, CodeCacheExpansionSize, 32*K ); -define_pd_global(uintx,CodeCacheMinBlockLength, 1); -define_pd_global(uintx,MetaspaceSize, 12*M ); +define_pd_global(uintx, CodeCacheMinBlockLength, 1); +define_pd_global(uintx, CodeCacheMinimumUseSpace, 400*K); +define_pd_global(uintx, MetaspaceSize, 12*M ); define_pd_global(bool, NeverActAsServerClassMachine, true ); define_pd_global(uint64_t,MaxRAM, 1ULL*G); define_pd_global(bool, CICompileOSR, true ); diff --git a/hotspot/src/cpu/x86/vm/c2_globals_x86.hpp b/hotspot/src/cpu/x86/vm/c2_globals_x86.hpp index f63b8c46d58..ce92123e818 100644 --- a/hotspot/src/cpu/x86/vm/c2_globals_x86.hpp +++ b/hotspot/src/cpu/x86/vm/c2_globals_x86.hpp @@ -85,7 +85,8 @@ define_pd_global(bool, OptoScheduling, false); define_pd_global(bool, OptoBundling, false); define_pd_global(intx, ReservedCodeCacheSize, 48*M); -define_pd_global(uintx,CodeCacheMinBlockLength, 4); +define_pd_global(uintx, CodeCacheMinBlockLength, 4); +define_pd_global(uintx, CodeCacheMinimumUseSpace, 400*K); // Heap related flags define_pd_global(uintx,MetaspaceSize, ScaleForWordSize(16*M)); diff --git a/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp b/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp index b15b00be586..3c5c225c399 100644 --- a/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp +++ b/hotspot/src/cpu/x86/vm/frame_x86.inline.hpp @@ -272,11 +272,10 @@ inline jint frame::interpreter_frame_expression_stack_direction() { return -1; } // Entry frames -inline JavaCallWrapper* frame::entry_frame_call_wrapper() const { - return (JavaCallWrapper*)at(entry_frame_call_wrapper_offset); +inline JavaCallWrapper** frame::entry_frame_call_wrapper_addr() const { + return (JavaCallWrapper**)addr_at(entry_frame_call_wrapper_offset); } - // Compiled frames inline int frame::local_offset_for_compiler(int local_index, int nof_args, int max_nof_locals, int max_nof_monitors) { diff --git a/hotspot/src/cpu/x86/vm/globals_x86.hpp b/hotspot/src/cpu/x86/vm/globals_x86.hpp index 07ab0cfcdce..c47f7d1c193 100644 --- a/hotspot/src/cpu/x86/vm/globals_x86.hpp +++ b/hotspot/src/cpu/x86/vm/globals_x86.hpp @@ -96,6 +96,9 @@ define_pd_global(uintx, CMSYoungGenPerWorker, 64*M); // default max size of CMS product(intx, UseAVX, 99, \ "Highest supported AVX instructions set on x86/x64") \ \ + product(bool, UseCLMUL, false, \ + "Control whether CLMUL instructions can be used on x86/x64") \ + \ diagnostic(bool, UseIncDec, true, \ "Use INC, DEC instructions on x86") \ \ diff --git a/hotspot/src/cpu/x86/vm/interpreterGenerator_x86.hpp b/hotspot/src/cpu/x86/vm/interpreterGenerator_x86.hpp index 13786e4149a..08f47708cdc 100644 --- a/hotspot/src/cpu/x86/vm/interpreterGenerator_x86.hpp +++ b/hotspot/src/cpu/x86/vm/interpreterGenerator_x86.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -39,6 +39,8 @@ address generate_empty_entry(void); address generate_accessor_entry(void); address generate_Reference_get_entry(); + address generate_CRC32_update_entry(); + address generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind); void lock_method(void); void generate_stack_overflow_check(void); diff --git a/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp b/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp index 98c93f99a0f..8aad6965156 100644 --- a/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp +++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -2794,6 +2794,15 @@ void MacroAssembler::movdqu(XMMRegister dst, AddressLiteral src) { } } +void MacroAssembler::movdqa(XMMRegister dst, AddressLiteral src) { + if (reachable(src)) { + Assembler::movdqa(dst, as_Address(src)); + } else { + lea(rscratch1, src); + Assembler::movdqa(dst, Address(rscratch1, 0)); + } +} + void MacroAssembler::movsd(XMMRegister dst, AddressLiteral src) { if (reachable(src)) { Assembler::movsd(dst, as_Address(src)); @@ -6388,6 +6397,193 @@ void MacroAssembler::encode_iso_array(Register src, Register dst, Register len, bind(L_done); } +/** + * Emits code to update CRC-32 with a byte value according to constants in table + * + * @param [in,out]crc Register containing the crc. + * @param [in]val Register containing the byte to fold into the CRC. + * @param [in]table Register containing the table of crc constants. + * + * uint32_t crc; + * val = crc_table[(val ^ crc) & 0xFF]; + * crc = val ^ (crc >> 8); + * + */ +void MacroAssembler::update_byte_crc32(Register crc, Register val, Register table) { + xorl(val, crc); + andl(val, 0xFF); + shrl(crc, 8); // unsigned shift + xorl(crc, Address(table, val, Address::times_4, 0)); +} + +/** + * Fold 128-bit data chunk + */ +void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset) { + vpclmulhdq(xtmp, xK, xcrc); // [123:64] + vpclmulldq(xcrc, xK, xcrc); // [63:0] + vpxor(xcrc, xcrc, Address(buf, offset), false /* vector256 */); + pxor(xcrc, xtmp); +} + +void MacroAssembler::fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf) { + vpclmulhdq(xtmp, xK, xcrc); + vpclmulldq(xcrc, xK, xcrc); + pxor(xcrc, xbuf); + pxor(xcrc, xtmp); +} + +/** + * 8-bit folds to compute 32-bit CRC + * + * uint64_t xcrc; + * timesXtoThe32[xcrc & 0xFF] ^ (xcrc >> 8); + */ +void MacroAssembler::fold_8bit_crc32(XMMRegister xcrc, Register table, XMMRegister xtmp, Register tmp) { + movdl(tmp, xcrc); + andl(tmp, 0xFF); + movdl(xtmp, Address(table, tmp, Address::times_4, 0)); + psrldq(xcrc, 1); // unsigned shift one byte + pxor(xcrc, xtmp); +} + +/** + * uint32_t crc; + * timesXtoThe32[crc & 0xFF] ^ (crc >> 8); + */ +void MacroAssembler::fold_8bit_crc32(Register crc, Register table, Register tmp) { + movl(tmp, crc); + andl(tmp, 0xFF); + shrl(crc, 8); + xorl(crc, Address(table, tmp, Address::times_4, 0)); +} + +/** + * @param crc register containing existing CRC (32-bit) + * @param buf register pointing to input byte buffer (byte*) + * @param len register containing number of bytes + * @param table register that will contain address of CRC table + * @param tmp scratch register + */ +void MacroAssembler::kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp) { + assert_different_registers(crc, buf, len, table, tmp, rax); + + Label L_tail, L_tail_restore, L_tail_loop, L_exit, L_align_loop, L_aligned; + Label L_fold_tail, L_fold_128b, L_fold_512b, L_fold_512b_loop, L_fold_tail_loop; + + lea(table, ExternalAddress(StubRoutines::crc_table_addr())); + notl(crc); // ~crc + cmpl(len, 16); + jcc(Assembler::less, L_tail); + + // Align buffer to 16 bytes + movl(tmp, buf); + andl(tmp, 0xF); + jccb(Assembler::zero, L_aligned); + subl(tmp, 16); + addl(len, tmp); + + align(4); + BIND(L_align_loop); + movsbl(rax, Address(buf, 0)); // load byte with sign extension + update_byte_crc32(crc, rax, table); + increment(buf); + incrementl(tmp); + jccb(Assembler::less, L_align_loop); + + BIND(L_aligned); + movl(tmp, len); // save + shrl(len, 4); + jcc(Assembler::zero, L_tail_restore); + + // Fold crc into first bytes of vector + movdqa(xmm1, Address(buf, 0)); + movdl(rax, xmm1); + xorl(crc, rax); + pinsrd(xmm1, crc, 0); + addptr(buf, 16); + subl(len, 4); // len > 0 + jcc(Assembler::less, L_fold_tail); + + movdqa(xmm2, Address(buf, 0)); + movdqa(xmm3, Address(buf, 16)); + movdqa(xmm4, Address(buf, 32)); + addptr(buf, 48); + subl(len, 3); + jcc(Assembler::lessEqual, L_fold_512b); + + // Fold total 512 bits of polynomial on each iteration, + // 128 bits per each of 4 parallel streams. + movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 32)); + + align(32); + BIND(L_fold_512b_loop); + fold_128bit_crc32(xmm1, xmm0, xmm5, buf, 0); + fold_128bit_crc32(xmm2, xmm0, xmm5, buf, 16); + fold_128bit_crc32(xmm3, xmm0, xmm5, buf, 32); + fold_128bit_crc32(xmm4, xmm0, xmm5, buf, 48); + addptr(buf, 64); + subl(len, 4); + jcc(Assembler::greater, L_fold_512b_loop); + + // Fold 512 bits to 128 bits. + BIND(L_fold_512b); + movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16)); + fold_128bit_crc32(xmm1, xmm0, xmm5, xmm2); + fold_128bit_crc32(xmm1, xmm0, xmm5, xmm3); + fold_128bit_crc32(xmm1, xmm0, xmm5, xmm4); + + // Fold the rest of 128 bits data chunks + BIND(L_fold_tail); + addl(len, 3); + jccb(Assembler::lessEqual, L_fold_128b); + movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr() + 16)); + + BIND(L_fold_tail_loop); + fold_128bit_crc32(xmm1, xmm0, xmm5, buf, 0); + addptr(buf, 16); + decrementl(len); + jccb(Assembler::greater, L_fold_tail_loop); + + // Fold 128 bits in xmm1 down into 32 bits in crc register. + BIND(L_fold_128b); + movdqu(xmm0, ExternalAddress(StubRoutines::x86::crc_by128_masks_addr())); + vpclmulqdq(xmm2, xmm0, xmm1, 0x1); + vpand(xmm3, xmm0, xmm2, false /* vector256 */); + vpclmulqdq(xmm0, xmm0, xmm3, 0x1); + psrldq(xmm1, 8); + psrldq(xmm2, 4); + pxor(xmm0, xmm1); + pxor(xmm0, xmm2); + + // 8 8-bit folds to compute 32-bit CRC. + for (int j = 0; j < 4; j++) { + fold_8bit_crc32(xmm0, table, xmm1, rax); + } + movdl(crc, xmm0); // mov 32 bits to general register + for (int j = 0; j < 4; j++) { + fold_8bit_crc32(crc, table, rax); + } + + BIND(L_tail_restore); + movl(len, tmp); // restore + BIND(L_tail); + andl(len, 0xf); + jccb(Assembler::zero, L_exit); + + // Fold the rest of bytes + align(4); + BIND(L_tail_loop); + movsbl(rax, Address(buf, 0)); // load byte with sign extension + update_byte_crc32(crc, rax, table); + increment(buf); + decrementl(len); + jccb(Assembler::greater, L_tail_loop); + + BIND(L_exit); + notl(crc); // ~c +} + #undef BIND #undef BLOCK_COMMENT diff --git a/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp b/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp index e9f409dc500..3acef073c0e 100644 --- a/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp +++ b/hotspot/src/cpu/x86/vm/macroAssembler_x86.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -899,6 +899,11 @@ public: void movdqu(XMMRegister dst, XMMRegister src) { Assembler::movdqu(dst, src); } void movdqu(XMMRegister dst, AddressLiteral src); + // Move Aligned Double Quadword + void movdqa(XMMRegister dst, Address src) { Assembler::movdqa(dst, src); } + void movdqa(XMMRegister dst, XMMRegister src) { Assembler::movdqa(dst, src); } + void movdqa(XMMRegister dst, AddressLiteral src); + void movsd(XMMRegister dst, XMMRegister src) { Assembler::movsd(dst, src); } void movsd(Address dst, XMMRegister src) { Assembler::movsd(dst, src); } void movsd(XMMRegister dst, Address src) { Assembler::movsd(dst, src); } @@ -1027,6 +1032,16 @@ public: Assembler::vinsertf128h(dst, nds, src); } + // Carry-Less Multiplication Quadword + void vpclmulldq(XMMRegister dst, XMMRegister nds, XMMRegister src) { + // 0x00 - multiply lower 64 bits [0:63] + Assembler::vpclmulqdq(dst, nds, src, 0x00); + } + void vpclmulhdq(XMMRegister dst, XMMRegister nds, XMMRegister src) { + // 0x11 - multiply upper 64 bits [64:127] + Assembler::vpclmulqdq(dst, nds, src, 0x11); + } + // Data void cmov32( Condition cc, Register dst, Address src); @@ -1143,6 +1158,16 @@ public: XMMRegister tmp1, XMMRegister tmp2, XMMRegister tmp3, XMMRegister tmp4, Register tmp5, Register result); + // CRC32 code for java.util.zip.CRC32::updateBytes() instrinsic. + void update_byte_crc32(Register crc, Register val, Register table); + void kernel_crc32(Register crc, Register buf, Register len, Register table, Register tmp); + // Fold 128-bit data chunk + void fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, Register buf, int offset); + void fold_128bit_crc32(XMMRegister xcrc, XMMRegister xK, XMMRegister xtmp, XMMRegister xbuf); + // Fold 8-bit data + void fold_8bit_crc32(Register crc, Register table, Register tmp); + void fold_8bit_crc32(XMMRegister crc, Register table, XMMRegister xtmp, Register tmp); + #undef VIRTUAL }; diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp index f24c5fdb38d..a8abfea6bcd 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_32.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -2713,6 +2713,92 @@ class StubGenerator: public StubCodeGenerator { return start; } + /** + * Arguments: + * + * Inputs: + * rsp(4) - int crc + * rsp(8) - byte* buf + * rsp(12) - int length + * + * Ouput: + * rax - int crc result + */ + address generate_updateBytesCRC32() { + assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions"); + + __ align(CodeEntryAlignment); + StubCodeMark mark(this, "StubRoutines", "updateBytesCRC32"); + + address start = __ pc(); + + const Register crc = rdx; // crc + const Register buf = rsi; // source java byte array address + const Register len = rcx; // length + const Register table = rdi; // crc_table address (reuse register) + const Register tmp = rbx; + assert_different_registers(crc, buf, len, table, tmp, rax); + + BLOCK_COMMENT("Entry:"); + __ enter(); // required for proper stackwalking of RuntimeStub frame + __ push(rsi); + __ push(rdi); + __ push(rbx); + + Address crc_arg(rbp, 8 + 0); + Address buf_arg(rbp, 8 + 4); + Address len_arg(rbp, 8 + 8); + + // Load up: + __ movl(crc, crc_arg); + __ movptr(buf, buf_arg); + __ movl(len, len_arg); + + __ kernel_crc32(crc, buf, len, table, tmp); + + __ movl(rax, crc); + __ pop(rbx); + __ pop(rdi); + __ pop(rsi); + __ leave(); // required for proper stackwalking of RuntimeStub frame + __ ret(0); + + return start; + } + + // Safefetch stubs. + void generate_safefetch(const char* name, int size, address* entry, + address* fault_pc, address* continuation_pc) { + // safefetch signatures: + // int SafeFetch32(int* adr, int errValue); + // intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue); + + StubCodeMark mark(this, "StubRoutines", name); + + // Entry point, pc or function descriptor. + *entry = __ pc(); + + __ movl(rax, Address(rsp, 0x8)); + __ movl(rcx, Address(rsp, 0x4)); + // Load *adr into eax, may fault. + *fault_pc = __ pc(); + switch (size) { + case 4: + // int32_t + __ movl(rax, Address(rcx, 0)); + break; + case 8: + // int64_t + Unimplemented(); + break; + default: + ShouldNotReachHere(); + } + + // Return errValue or *adr. + *continuation_pc = __ pc(); + __ ret(0); + } public: // Information about frame layout at time of blocking runtime call. @@ -2887,6 +2973,12 @@ class StubGenerator: public StubCodeGenerator { // Build this early so it's available for the interpreter StubRoutines::_throw_StackOverflowError_entry = generate_throw_exception("StackOverflowError throw_exception", CAST_FROM_FN_PTR(address, SharedRuntime::throw_StackOverflowError)); + + if (UseCRC32Intrinsics) { + // set table address before stub generation which use it + StubRoutines::_crc_table_adr = (address)StubRoutines::x86::_crc_table; + StubRoutines::_updateBytesCRC32 = generate_updateBytesCRC32(); + } } @@ -2919,6 +3011,14 @@ class StubGenerator: public StubCodeGenerator { StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt(); StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt(); } + + // Safefetch stubs. + generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry, + &StubRoutines::_safefetch32_fault_pc, + &StubRoutines::_safefetch32_continuation_pc); + StubRoutines::_safefetchN_entry = StubRoutines::_safefetch32_entry; + StubRoutines::_safefetchN_fault_pc = StubRoutines::_safefetch32_fault_pc; + StubRoutines::_safefetchN_continuation_pc = StubRoutines::_safefetch32_continuation_pc; } diff --git a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp index 7b8408d7131..e38139d28ec 100644 --- a/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/stubGenerator_x86_64.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -279,7 +279,7 @@ class StubGenerator: public StubCodeGenerator { __ stmxcsr(mxcsr_save); __ movl(rax, mxcsr_save); __ andl(rax, MXCSR_MASK); // Only check control and mask bits - ExternalAddress mxcsr_std(StubRoutines::x86::mxcsr_std()); + ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std()); __ cmp32(rax, mxcsr_std); __ jcc(Assembler::equal, skip_ldmx); __ ldmxcsr(mxcsr_std); @@ -729,17 +729,18 @@ class StubGenerator: public StubCodeGenerator { if (CheckJNICalls) { Label ok_ret; + ExternalAddress mxcsr_std(StubRoutines::addr_mxcsr_std()); __ push(rax); __ subptr(rsp, wordSize); // allocate a temp location __ stmxcsr(mxcsr_save); __ movl(rax, mxcsr_save); __ andl(rax, MXCSR_MASK); // Only check control and mask bits - __ cmpl(rax, *(int *)(StubRoutines::x86::mxcsr_std())); + __ cmp32(rax, mxcsr_std); __ jcc(Assembler::equal, ok_ret); __ warn("MXCSR changed by native JNI code, use -XX:+RestoreMXCSROnJNICall"); - __ ldmxcsr(ExternalAddress(StubRoutines::x86::mxcsr_std())); + __ ldmxcsr(mxcsr_std); __ bind(ok_ret); __ addptr(rsp, wordSize); @@ -3357,7 +3358,45 @@ class StubGenerator: public StubCodeGenerator { return start; } + // Safefetch stubs. + void generate_safefetch(const char* name, int size, address* entry, + address* fault_pc, address* continuation_pc) { + // safefetch signatures: + // int SafeFetch32(int* adr, int errValue); + // intptr_t SafeFetchN (intptr_t* adr, intptr_t errValue); + // + // arguments: + // c_rarg0 = adr + // c_rarg1 = errValue + // + // result: + // PPC_RET = *adr or errValue + StubCodeMark mark(this, "StubRoutines", name); + + // Entry point, pc or function descriptor. + *entry = __ pc(); + + // Load *adr into c_rarg1, may fault. + *fault_pc = __ pc(); + switch (size) { + case 4: + // int32_t + __ movl(c_rarg1, Address(c_rarg0, 0)); + break; + case 8: + // int64_t + __ movq(c_rarg1, Address(c_rarg0, 0)); + break; + default: + ShouldNotReachHere(); + } + + // return errValue or *adr + *continuation_pc = __ pc(); + __ movq(rax, c_rarg1); + __ ret(0); + } // This is a version of CBC/AES Decrypt which does 4 blocks in a loop at a time // to hide instruction latency @@ -3584,7 +3623,45 @@ class StubGenerator: public StubCodeGenerator { return start; } + /** + * Arguments: + * + * Inputs: + * c_rarg0 - int crc + * c_rarg1 - byte* buf + * c_rarg2 - int length + * + * Ouput: + * rax - int crc result + */ + address generate_updateBytesCRC32() { + assert(UseCRC32Intrinsics, "need AVX and CLMUL instructions"); + __ align(CodeEntryAlignment); + StubCodeMark mark(this, "StubRoutines", "updateBytesCRC32"); + + address start = __ pc(); + // Win64: rcx, rdx, r8, r9 (c_rarg0, c_rarg1, ...) + // Unix: rdi, rsi, rdx, rcx, r8, r9 (c_rarg0, c_rarg1, ...) + // rscratch1: r10 + const Register crc = c_rarg0; // crc + const Register buf = c_rarg1; // source java byte array address + const Register len = c_rarg2; // length + const Register table = c_rarg3; // crc_table address (reuse register) + const Register tmp = r11; + assert_different_registers(crc, buf, len, table, tmp, rax); + + BLOCK_COMMENT("Entry:"); + __ enter(); // required for proper stackwalking of RuntimeStub frame + + __ kernel_crc32(crc, buf, len, table, tmp); + + __ movl(rax, crc); + __ leave(); // required for proper stackwalking of RuntimeStub frame + __ ret(0); + + return start; + } #undef __ #define __ masm-> @@ -3691,12 +3768,35 @@ class StubGenerator: public StubCodeGenerator { return stub->entry_point(); } + void create_control_words() { + // Round to nearest, 53-bit mode, exceptions masked + StubRoutines::_fpu_cntrl_wrd_std = 0x027F; + // Round to zero, 53-bit mode, exception mased + StubRoutines::_fpu_cntrl_wrd_trunc = 0x0D7F; + // Round to nearest, 24-bit mode, exceptions masked + StubRoutines::_fpu_cntrl_wrd_24 = 0x007F; + // Round to nearest, 64-bit mode, exceptions masked + StubRoutines::_fpu_cntrl_wrd_64 = 0x037F; + // Round to nearest, 64-bit mode, exceptions masked + StubRoutines::_mxcsr_std = 0x1F80; + // Note: the following two constants are 80-bit values + // layout is critical for correct loading by FPU. + // Bias for strict fp multiply/divide + StubRoutines::_fpu_subnormal_bias1[0]= 0x00000000; // 2^(-15360) == 0x03ff 8000 0000 0000 0000 + StubRoutines::_fpu_subnormal_bias1[1]= 0x80000000; + StubRoutines::_fpu_subnormal_bias1[2]= 0x03ff; + // Un-Bias for strict fp multiply/divide + StubRoutines::_fpu_subnormal_bias2[0]= 0x00000000; // 2^(+15360) == 0x7bff 8000 0000 0000 0000 + StubRoutines::_fpu_subnormal_bias2[1]= 0x80000000; + StubRoutines::_fpu_subnormal_bias2[2]= 0x7bff; + } + // Initialization void generate_initial() { // Generates all stubs and initializes the entry points - // This platform-specific stub is needed by generate_call_stub() - StubRoutines::x86::_mxcsr_std = generate_fp_mask("mxcsr_std", 0x0000000000001F80); + // This platform-specific settings are needed by generate_call_stub() + create_control_words(); // entry points that exist in all platforms Note: This is code // that could be shared among different platforms - however the @@ -3736,6 +3836,11 @@ class StubGenerator: public StubCodeGenerator { CAST_FROM_FN_PTR(address, SharedRuntime:: throw_StackOverflowError)); + if (UseCRC32Intrinsics) { + // set table address before stub generation which use it + StubRoutines::_crc_table_adr = (address)StubRoutines::x86::_crc_table; + StubRoutines::_updateBytesCRC32 = generate_updateBytesCRC32(); + } } void generate_all() { @@ -3790,6 +3895,14 @@ class StubGenerator: public StubCodeGenerator { StubRoutines::_cipherBlockChaining_encryptAESCrypt = generate_cipherBlockChaining_encryptAESCrypt(); StubRoutines::_cipherBlockChaining_decryptAESCrypt = generate_cipherBlockChaining_decryptAESCrypt_Parallel(); } + + // Safefetch stubs. + generate_safefetch("SafeFetch32", sizeof(int), &StubRoutines::_safefetch32_entry, + &StubRoutines::_safefetch32_fault_pc, + &StubRoutines::_safefetch32_continuation_pc); + generate_safefetch("SafeFetchN", sizeof(intptr_t), &StubRoutines::_safefetchN_entry, + &StubRoutines::_safefetchN_fault_pc, + &StubRoutines::_safefetchN_continuation_pc); } public: diff --git a/hotspot/src/cpu/x86/vm/stubRoutines_x86.cpp b/hotspot/src/cpu/x86/vm/stubRoutines_x86.cpp new file mode 100644 index 00000000000..200f2aff80d --- /dev/null +++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86.cpp @@ -0,0 +1,130 @@ +/* + * 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 + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#include "precompiled.hpp" +#include "runtime/deoptimization.hpp" +#include "runtime/frame.inline.hpp" +#include "runtime/stubRoutines.hpp" +#include "runtime/thread.inline.hpp" + +// Implementation of the platform-specific part of StubRoutines - for +// a description of how to extend it, see the stubRoutines.hpp file. + +address StubRoutines::x86::_verify_mxcsr_entry = NULL; +address StubRoutines::x86::_key_shuffle_mask_addr = NULL; + +uint64_t StubRoutines::x86::_crc_by128_masks[] = +{ + /* The fields in this structure are arranged so that they can be + * picked up two at a time with 128-bit loads. + * + * Because of flipped bit order for this CRC polynomials + * the constant for X**N is left-shifted by 1. This is because + * a 64 x 64 polynomial multiply produces a 127-bit result + * but the highest term is always aligned to bit 0 in the container. + * Pre-shifting by one fixes this, at the cost of potentially making + * the 32-bit constant no longer fit in a 32-bit container (thus the + * use of uint64_t, though this is also the size used by the carry- + * less multiply instruction. + * + * In addition, the flipped bit order and highest-term-at-least-bit + * multiply changes the constants used. The 96-bit result will be + * aligned to the high-term end of the target 128-bit container, + * not the low-term end; that is, instead of a 512-bit or 576-bit fold, + * instead it is a 480 (=512-32) or 544 (=512+64-32) bit fold. + * + * This cause additional problems in the 128-to-64-bit reduction; see the + * code for details. By storing a mask in the otherwise unused half of + * a 128-bit constant, bits can be cleared before multiplication without + * storing and reloading. Note that staying on a 128-bit datapath means + * that some data is uselessly stored and some unused data is intersected + * with an irrelevant constant. + */ + + ((uint64_t) 0xffffffffUL), /* low of K_M_64 */ + ((uint64_t) 0xb1e6b092U << 1), /* high of K_M_64 */ + ((uint64_t) 0xba8ccbe8U << 1), /* low of K_160_96 */ + ((uint64_t) 0x6655004fU << 1), /* high of K_160_96 */ + ((uint64_t) 0xaa2215eaU << 1), /* low of K_544_480 */ + ((uint64_t) 0xe3720acbU << 1) /* high of K_544_480 */ +}; + +/** + * crc_table[] from jdk/src/share/native/java/util/zip/zlib-1.2.5/crc32.h + */ +juint StubRoutines::x86::_crc_table[] = +{ + 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL, + 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL, + 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL, + 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL, + 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL, + 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL, + 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL, + 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL, + 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL, + 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL, + 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL, + 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL, + 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL, + 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL, + 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL, + 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL, + 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL, + 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL, + 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL, + 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL, + 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL, + 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL, + 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL, + 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL, + 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL, + 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL, + 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL, + 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL, + 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL, + 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL, + 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL, + 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL, + 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL, + 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL, + 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL, + 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL, + 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL, + 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL, + 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL, + 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL, + 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL, + 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL, + 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL, + 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL, + 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL, + 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL, + 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL, + 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL, + 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL, + 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL, + 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL, + 0x2d02ef8dUL +}; diff --git a/hotspot/src/cpu/x86/vm/stubRoutines_x86.hpp b/hotspot/src/cpu/x86/vm/stubRoutines_x86.hpp new file mode 100644 index 00000000000..d8e52ab3b11 --- /dev/null +++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86.hpp @@ -0,0 +1,45 @@ +/* + * 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 + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#ifndef CPU_X86_VM_STUBROUTINES_X86_HPP +#define CPU_X86_VM_STUBROUTINES_X86_HPP + +// This file holds the platform specific parts of the StubRoutines +// definition. See stubRoutines.hpp for a description on how to +// extend it. + + private: + static address _verify_mxcsr_entry; + // shuffle mask for fixing up 128-bit words consisting of big-endian 32-bit integers + static address _key_shuffle_mask_addr; + // masks and table for CRC32 + static uint64_t _crc_by128_masks[]; + static juint _crc_table[]; + + public: + static address verify_mxcsr_entry() { return _verify_mxcsr_entry; } + static address key_shuffle_mask_addr() { return _key_shuffle_mask_addr; } + static address crc_by128_masks_addr() { return (address)_crc_by128_masks; } + +#endif // CPU_X86_VM_STUBROUTINES_X86_32_HPP diff --git a/hotspot/src/cpu/x86/vm/stubRoutines_x86_32.cpp b/hotspot/src/cpu/x86/vm/stubRoutines_x86_32.cpp index 65e773ed53c..53464dcccdf 100644 --- a/hotspot/src/cpu/x86/vm/stubRoutines_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86_32.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -31,6 +31,4 @@ // Implementation of the platform-specific part of StubRoutines - for // a description of how to extend it, see the stubRoutines.hpp file. -address StubRoutines::x86::_verify_mxcsr_entry = NULL; address StubRoutines::x86::_verify_fpu_cntrl_wrd_entry = NULL; -address StubRoutines::x86::_key_shuffle_mask_addr = NULL; diff --git a/hotspot/src/cpu/x86/vm/stubRoutines_x86_32.hpp b/hotspot/src/cpu/x86/vm/stubRoutines_x86_32.hpp index d53124fc6c8..bca5d493ce4 100644 --- a/hotspot/src/cpu/x86/vm/stubRoutines_x86_32.hpp +++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86_32.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -39,15 +39,12 @@ class x86 { friend class VMStructs; private: - static address _verify_mxcsr_entry; static address _verify_fpu_cntrl_wrd_entry; - // shuffle mask for fixing up 128-bit words consisting of big-endian 32-bit integers - static address _key_shuffle_mask_addr; public: - static address verify_mxcsr_entry() { return _verify_mxcsr_entry; } static address verify_fpu_cntrl_wrd_entry() { return _verify_fpu_cntrl_wrd_entry; } - static address key_shuffle_mask_addr() { return _key_shuffle_mask_addr; } + +# include "stubRoutines_x86.hpp" }; diff --git a/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.cpp b/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.cpp index 9f0a94200a5..bf539083e90 100644 --- a/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -34,8 +34,6 @@ address StubRoutines::x86::_get_previous_fp_entry = NULL; address StubRoutines::x86::_get_previous_sp_entry = NULL; -address StubRoutines::x86::_verify_mxcsr_entry = NULL; - address StubRoutines::x86::_f2i_fixup = NULL; address StubRoutines::x86::_f2l_fixup = NULL; address StubRoutines::x86::_d2i_fixup = NULL; @@ -44,5 +42,3 @@ address StubRoutines::x86::_float_sign_mask = NULL; address StubRoutines::x86::_float_sign_flip = NULL; address StubRoutines::x86::_double_sign_mask = NULL; address StubRoutines::x86::_double_sign_flip = NULL; -address StubRoutines::x86::_mxcsr_std = NULL; -address StubRoutines::x86::_key_shuffle_mask_addr = NULL; diff --git a/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.hpp b/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.hpp index c3efeecb759..205bce4eb76 100644 --- a/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.hpp +++ b/hotspot/src/cpu/x86/vm/stubRoutines_x86_64.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -42,7 +42,6 @@ class x86 { private: static address _get_previous_fp_entry; static address _get_previous_sp_entry; - static address _verify_mxcsr_entry; static address _f2i_fixup; static address _f2l_fixup; @@ -53,9 +52,6 @@ class x86 { static address _float_sign_flip; static address _double_sign_mask; static address _double_sign_flip; - static address _mxcsr_std; - // shuffle mask for fixing up 128-bit words consisting of big-endian 32-bit integers - static address _key_shuffle_mask_addr; public: @@ -69,11 +65,6 @@ class x86 { return _get_previous_sp_entry; } - static address verify_mxcsr_entry() - { - return _verify_mxcsr_entry; - } - static address f2i_fixup() { return _f2i_fixup; @@ -114,12 +105,7 @@ class x86 { return _double_sign_flip; } - static address mxcsr_std() - { - return _mxcsr_std; - } - - static address key_shuffle_mask_addr() { return _key_shuffle_mask_addr; } +# include "stubRoutines_x86.hpp" }; diff --git a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp index 3908a8c09da..2efa59f8b33 100644 --- a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp +++ b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_32.cpp @@ -868,6 +868,120 @@ address InterpreterGenerator::generate_Reference_get_entry(void) { return generate_accessor_entry(); } +/** + * Method entry for static native methods: + * int java.util.zip.CRC32.update(int crc, int b) + */ +address InterpreterGenerator::generate_CRC32_update_entry() { + if (UseCRC32Intrinsics) { + address entry = __ pc(); + + // rbx,: Method* + // rsi: senderSP must preserved for slow path, set SP to it on fast path + // rdx: scratch + // rdi: scratch + + Label slow_path; + // If we need a safepoint check, generate full interpreter entry. + ExternalAddress state(SafepointSynchronize::address_of_state()); + __ cmp32(ExternalAddress(SafepointSynchronize::address_of_state()), + SafepointSynchronize::_not_synchronized); + __ jcc(Assembler::notEqual, slow_path); + + // We don't generate local frame and don't align stack because + // we call stub code and there is no safepoint on this path. + + // Load parameters + const Register crc = rax; // crc + const Register val = rdx; // source java byte value + const Register tbl = rdi; // scratch + + // Arguments are reversed on java expression stack + __ movl(val, Address(rsp, wordSize)); // byte value + __ movl(crc, Address(rsp, 2*wordSize)); // Initial CRC + + __ lea(tbl, ExternalAddress(StubRoutines::crc_table_addr())); + __ notl(crc); // ~crc + __ update_byte_crc32(crc, val, tbl); + __ notl(crc); // ~crc + // result in rax + + // _areturn + __ pop(rdi); // get return address + __ mov(rsp, rsi); // set sp to sender sp + __ jmp(rdi); + + // generate a vanilla native entry as the slow path + __ bind(slow_path); + + (void) generate_native_entry(false); + + return entry; + } + return generate_native_entry(false); +} + +/** + * Method entry for static native methods: + * int java.util.zip.CRC32.updateBytes(int crc, byte[] b, int off, int len) + * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len) + */ +address InterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) { + if (UseCRC32Intrinsics) { + address entry = __ pc(); + + // rbx,: Method* + // rsi: senderSP must preserved for slow path, set SP to it on fast path + // rdx: scratch + // rdi: scratch + + Label slow_path; + // If we need a safepoint check, generate full interpreter entry. + ExternalAddress state(SafepointSynchronize::address_of_state()); + __ cmp32(ExternalAddress(SafepointSynchronize::address_of_state()), + SafepointSynchronize::_not_synchronized); + __ jcc(Assembler::notEqual, slow_path); + + // We don't generate local frame and don't align stack because + // we call stub code and there is no safepoint on this path. + + // Load parameters + const Register crc = rax; // crc + const Register buf = rdx; // source java byte array address + const Register len = rdi; // length + + // Arguments are reversed on java expression stack + __ movl(len, Address(rsp, wordSize)); // Length + // Calculate address of start element + if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) { + __ movptr(buf, Address(rsp, 3*wordSize)); // long buf + __ addptr(buf, Address(rsp, 2*wordSize)); // + offset + __ movl(crc, Address(rsp, 5*wordSize)); // Initial CRC + } else { + __ movptr(buf, Address(rsp, 3*wordSize)); // byte[] array + __ addptr(buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size + __ addptr(buf, Address(rsp, 2*wordSize)); // + offset + __ movl(crc, Address(rsp, 4*wordSize)); // Initial CRC + } + + __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32()), crc, buf, len); + // result in rax + + // _areturn + __ pop(rdi); // get return address + __ mov(rsp, rsi); // set sp to sender sp + __ jmp(rdi); + + // generate a vanilla native entry as the slow path + __ bind(slow_path); + + (void) generate_native_entry(false); + + return entry; + } + return generate_native_entry(false); +} + // // Interpreter stub for calling a native method. (asm interpreter) // This sets up a somewhat different looking stack for calling the native method @@ -1501,15 +1615,16 @@ address AbstractInterpreterGenerator::generate_method_entry(AbstractInterpreter: // determine code generation flags bool synchronized = false; address entry_point = NULL; + InterpreterGenerator* ig_this = (InterpreterGenerator*)this; switch (kind) { - case Interpreter::zerolocals : break; - case Interpreter::zerolocals_synchronized: synchronized = true; break; - case Interpreter::native : entry_point = ((InterpreterGenerator*)this)->generate_native_entry(false); break; - case Interpreter::native_synchronized : entry_point = ((InterpreterGenerator*)this)->generate_native_entry(true); break; - case Interpreter::empty : entry_point = ((InterpreterGenerator*)this)->generate_empty_entry(); break; - case Interpreter::accessor : entry_point = ((InterpreterGenerator*)this)->generate_accessor_entry(); break; - case Interpreter::abstract : entry_point = ((InterpreterGenerator*)this)->generate_abstract_entry(); break; + case Interpreter::zerolocals : break; + case Interpreter::zerolocals_synchronized: synchronized = true; break; + case Interpreter::native : entry_point = ig_this->generate_native_entry(false); break; + case Interpreter::native_synchronized : entry_point = ig_this->generate_native_entry(true); break; + case Interpreter::empty : entry_point = ig_this->generate_empty_entry(); break; + case Interpreter::accessor : entry_point = ig_this->generate_accessor_entry(); break; + case Interpreter::abstract : entry_point = ig_this->generate_abstract_entry(); break; case Interpreter::java_lang_math_sin : // fall thru case Interpreter::java_lang_math_cos : // fall thru @@ -1519,9 +1634,15 @@ address AbstractInterpreterGenerator::generate_method_entry(AbstractInterpreter: case Interpreter::java_lang_math_log10 : // fall thru case Interpreter::java_lang_math_sqrt : // fall thru case Interpreter::java_lang_math_pow : // fall thru - case Interpreter::java_lang_math_exp : entry_point = ((InterpreterGenerator*)this)->generate_math_entry(kind); break; + case Interpreter::java_lang_math_exp : entry_point = ig_this->generate_math_entry(kind); break; case Interpreter::java_lang_ref_reference_get - : entry_point = ((InterpreterGenerator*)this)->generate_Reference_get_entry(); break; + : entry_point = ig_this->generate_Reference_get_entry(); break; + case Interpreter::java_util_zip_CRC32_update + : entry_point = ig_this->generate_CRC32_update_entry(); break; + case Interpreter::java_util_zip_CRC32_updateBytes + : // fall thru + case Interpreter::java_util_zip_CRC32_updateByteBuffer + : entry_point = ig_this->generate_CRC32_updateBytes_entry(kind); break; default: fatal(err_msg("unexpected method kind: %d", kind)); break; @@ -1529,7 +1650,7 @@ address AbstractInterpreterGenerator::generate_method_entry(AbstractInterpreter: if (entry_point) return entry_point; - return ((InterpreterGenerator*)this)->generate_normal_entry(synchronized); + return ig_this->generate_normal_entry(synchronized); } diff --git a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp index 50bb8a968f6..f0a2258a70e 100644 --- a/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp +++ b/hotspot/src/cpu/x86/vm/templateInterpreter_x86_64.cpp @@ -840,6 +840,117 @@ address InterpreterGenerator::generate_Reference_get_entry(void) { return generate_accessor_entry(); } +/** + * Method entry for static native methods: + * int java.util.zip.CRC32.update(int crc, int b) + */ +address InterpreterGenerator::generate_CRC32_update_entry() { + if (UseCRC32Intrinsics) { + address entry = __ pc(); + + // rbx,: Method* + // rsi: senderSP must preserved for slow path, set SP to it on fast path + // rdx: scratch + // rdi: scratch + + Label slow_path; + // If we need a safepoint check, generate full interpreter entry. + ExternalAddress state(SafepointSynchronize::address_of_state()); + __ cmp32(ExternalAddress(SafepointSynchronize::address_of_state()), + SafepointSynchronize::_not_synchronized); + __ jcc(Assembler::notEqual, slow_path); + + // We don't generate local frame and don't align stack because + // we call stub code and there is no safepoint on this path. + + // Load parameters + const Register crc = rax; // crc + const Register val = rdx; // source java byte value + const Register tbl = rdi; // scratch + + // Arguments are reversed on java expression stack + __ movl(val, Address(rsp, wordSize)); // byte value + __ movl(crc, Address(rsp, 2*wordSize)); // Initial CRC + + __ lea(tbl, ExternalAddress(StubRoutines::crc_table_addr())); + __ notl(crc); // ~crc + __ update_byte_crc32(crc, val, tbl); + __ notl(crc); // ~crc + // result in rax + + // _areturn + __ pop(rdi); // get return address + __ mov(rsp, rsi); // set sp to sender sp + __ jmp(rdi); + + // generate a vanilla native entry as the slow path + __ bind(slow_path); + + (void) generate_native_entry(false); + + return entry; + } + return generate_native_entry(false); +} + +/** + * Method entry for static native methods: + * int java.util.zip.CRC32.updateBytes(int crc, byte[] b, int off, int len) + * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len) + */ +address InterpreterGenerator::generate_CRC32_updateBytes_entry(AbstractInterpreter::MethodKind kind) { + if (UseCRC32Intrinsics) { + address entry = __ pc(); + + // rbx,: Method* + // r13: senderSP must preserved for slow path, set SP to it on fast path + + Label slow_path; + // If we need a safepoint check, generate full interpreter entry. + ExternalAddress state(SafepointSynchronize::address_of_state()); + __ cmp32(ExternalAddress(SafepointSynchronize::address_of_state()), + SafepointSynchronize::_not_synchronized); + __ jcc(Assembler::notEqual, slow_path); + + // We don't generate local frame and don't align stack because + // we call stub code and there is no safepoint on this path. + + // Load parameters + const Register crc = c_rarg0; // crc + const Register buf = c_rarg1; // source java byte array address + const Register len = c_rarg2; // length + + // Arguments are reversed on java expression stack + __ movl(len, Address(rsp, wordSize)); // Length + // Calculate address of start element + if (kind == Interpreter::java_util_zip_CRC32_updateByteBuffer) { + __ movptr(buf, Address(rsp, 3*wordSize)); // long buf + __ addptr(buf, Address(rsp, 2*wordSize)); // + offset + __ movl(crc, Address(rsp, 5*wordSize)); // Initial CRC + } else { + __ movptr(buf, Address(rsp, 3*wordSize)); // byte[] array + __ addptr(buf, arrayOopDesc::base_offset_in_bytes(T_BYTE)); // + header size + __ addptr(buf, Address(rsp, 2*wordSize)); // + offset + __ movl(crc, Address(rsp, 4*wordSize)); // Initial CRC + } + + __ super_call_VM_leaf(CAST_FROM_FN_PTR(address, StubRoutines::updateBytesCRC32()), crc, buf, len); + // result in rax + + // _areturn + __ pop(rdi); // get return address + __ mov(rsp, r13); // set sp to sender sp + __ jmp(rdi); + + // generate a vanilla native entry as the slow path + __ bind(slow_path); + + (void) generate_native_entry(false); + + return entry; + } + return generate_native_entry(false); +} // Interpreter stub for calling a native method. (asm interpreter) // This sets up a somewhat different looking stack for calling the @@ -1510,15 +1621,16 @@ address AbstractInterpreterGenerator::generate_method_entry( // determine code generation flags bool synchronized = false; address entry_point = NULL; + InterpreterGenerator* ig_this = (InterpreterGenerator*)this; switch (kind) { - case Interpreter::zerolocals : break; - case Interpreter::zerolocals_synchronized: synchronized = true; break; - case Interpreter::native : entry_point = ((InterpreterGenerator*)this)->generate_native_entry(false); break; - case Interpreter::native_synchronized : entry_point = ((InterpreterGenerator*)this)->generate_native_entry(true); break; - case Interpreter::empty : entry_point = ((InterpreterGenerator*)this)->generate_empty_entry(); break; - case Interpreter::accessor : entry_point = ((InterpreterGenerator*)this)->generate_accessor_entry(); break; - case Interpreter::abstract : entry_point = ((InterpreterGenerator*)this)->generate_abstract_entry(); break; + case Interpreter::zerolocals : break; + case Interpreter::zerolocals_synchronized: synchronized = true; break; + case Interpreter::native : entry_point = ig_this->generate_native_entry(false); break; + case Interpreter::native_synchronized : entry_point = ig_this->generate_native_entry(true); break; + case Interpreter::empty : entry_point = ig_this->generate_empty_entry(); break; + case Interpreter::accessor : entry_point = ig_this->generate_accessor_entry(); break; + case Interpreter::abstract : entry_point = ig_this->generate_abstract_entry(); break; case Interpreter::java_lang_math_sin : // fall thru case Interpreter::java_lang_math_cos : // fall thru @@ -1528,9 +1640,15 @@ address AbstractInterpreterGenerator::generate_method_entry( case Interpreter::java_lang_math_log10 : // fall thru case Interpreter::java_lang_math_sqrt : // fall thru case Interpreter::java_lang_math_pow : // fall thru - case Interpreter::java_lang_math_exp : entry_point = ((InterpreterGenerator*)this)->generate_math_entry(kind); break; + case Interpreter::java_lang_math_exp : entry_point = ig_this->generate_math_entry(kind); break; case Interpreter::java_lang_ref_reference_get - : entry_point = ((InterpreterGenerator*)this)->generate_Reference_get_entry(); break; + : entry_point = ig_this->generate_Reference_get_entry(); break; + case Interpreter::java_util_zip_CRC32_update + : entry_point = ig_this->generate_CRC32_update_entry(); break; + case Interpreter::java_util_zip_CRC32_updateBytes + : // fall thru + case Interpreter::java_util_zip_CRC32_updateByteBuffer + : entry_point = ig_this->generate_CRC32_updateBytes_entry(kind); break; default: fatal(err_msg("unexpected method kind: %d", kind)); break; @@ -1540,8 +1658,7 @@ address AbstractInterpreterGenerator::generate_method_entry( return entry_point; } - return ((InterpreterGenerator*) this)-> - generate_normal_entry(synchronized); + return ig_this->generate_normal_entry(synchronized); } // These should never be compiled since the interpreter will prefer diff --git a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp index 90066c1041a..de38b4a3a53 100644 --- a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp +++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -446,6 +446,7 @@ void VM_Version::get_processor_features() { (supports_avx() ? ", avx" : ""), (supports_avx2() ? ", avx2" : ""), (supports_aes() ? ", aes" : ""), + (supports_clmul() ? ", clmul" : ""), (supports_erms() ? ", erms" : ""), (supports_mmx_ext() ? ", mmxext" : ""), (supports_3dnow_prefetch() ? ", 3dnowpref" : ""), @@ -489,6 +490,27 @@ void VM_Version::get_processor_features() { FLAG_SET_DEFAULT(UseAES, false); } + // Use CLMUL instructions if available. + if (supports_clmul()) { + if (FLAG_IS_DEFAULT(UseCLMUL)) { + UseCLMUL = true; + } + } else if (UseCLMUL) { + if (!FLAG_IS_DEFAULT(UseCLMUL)) + warning("CLMUL instructions not available on this CPU (AVX may also be required)"); + FLAG_SET_DEFAULT(UseCLMUL, false); + } + + if (UseCLMUL && (UseAVX > 0) && (UseSSE > 2)) { + if (FLAG_IS_DEFAULT(UseCRC32Intrinsics)) { + UseCRC32Intrinsics = true; + } + } else if (UseCRC32Intrinsics) { + if (!FLAG_IS_DEFAULT(UseCRC32Intrinsics)) + warning("CRC32 Intrinsics requires AVX and CLMUL instructions (not available on this CPU)"); + FLAG_SET_DEFAULT(UseCRC32Intrinsics, false); + } + // The AES intrinsic stubs require AES instruction support (of course) // but also require sse3 mode for instructions it use. if (UseAES && (UseSSE > 2)) { diff --git a/hotspot/src/cpu/x86/vm/vm_version_x86.hpp b/hotspot/src/cpu/x86/vm/vm_version_x86.hpp index ec8caba23f0..86e9b662d52 100644 --- a/hotspot/src/cpu/x86/vm/vm_version_x86.hpp +++ b/hotspot/src/cpu/x86/vm/vm_version_x86.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -61,7 +61,8 @@ public: uint32_t value; struct { uint32_t sse3 : 1, - : 2, + clmul : 1, + : 1, monitor : 1, : 1, vmx : 1, @@ -249,7 +250,8 @@ protected: CPU_AVX = (1 << 17), CPU_AVX2 = (1 << 18), CPU_AES = (1 << 19), - CPU_ERMS = (1 << 20) // enhanced 'rep movsb/stosb' instructions + CPU_ERMS = (1 << 20), // enhanced 'rep movsb/stosb' instructions + CPU_CLMUL = (1 << 21) // carryless multiply for CRC } cpuFeatureFlags; enum { @@ -429,6 +431,8 @@ protected: result |= CPU_AES; if (_cpuid_info.sef_cpuid7_ebx.bits.erms != 0) result |= CPU_ERMS; + if (_cpuid_info.std_cpuid1_ecx.bits.clmul != 0) + result |= CPU_CLMUL; // AMD features. if (is_amd()) { @@ -555,6 +559,7 @@ public: static bool supports_tsc() { return (_cpuFeatures & CPU_TSC) != 0; } static bool supports_aes() { return (_cpuFeatures & CPU_AES) != 0; } static bool supports_erms() { return (_cpuFeatures & CPU_ERMS) != 0; } + static bool supports_clmul() { return (_cpuFeatures & CPU_CLMUL) != 0; } // Intel features static bool is_intel_family_core() { return is_intel() && diff --git a/hotspot/src/cpu/zero/vm/shark_globals_zero.hpp b/hotspot/src/cpu/zero/vm/shark_globals_zero.hpp index 1d17143761a..c04b225b830 100644 --- a/hotspot/src/cpu/zero/vm/shark_globals_zero.hpp +++ b/hotspot/src/cpu/zero/vm/shark_globals_zero.hpp @@ -58,7 +58,9 @@ define_pd_global(intx, ReservedCodeCacheSize, 32*M ); define_pd_global(bool, ProfileInterpreter, false); define_pd_global(intx, CodeCacheExpansionSize, 32*K ); define_pd_global(uintx, CodeCacheMinBlockLength, 1 ); -define_pd_global(uintx, MetaspaceSize, 12*M ); +define_pd_global(uintx, CodeCacheMinimumUseSpace, 200*K); + +define_pd_global(uintx, MetaspaceSize, 12*M ); define_pd_global(bool, NeverActAsServerClassMachine, true ); define_pd_global(uint64_t, MaxRAM, 1ULL*G); define_pd_global(bool, CICompileOSR, true ); diff --git a/hotspot/src/os/bsd/vm/attachListener_bsd.cpp b/hotspot/src/os/bsd/vm/attachListener_bsd.cpp index ee4feb8d046..6f128f2543b 100644 --- a/hotspot/src/os/bsd/vm/attachListener_bsd.cpp +++ b/hotspot/src/os/bsd/vm/attachListener_bsd.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -437,6 +437,30 @@ AttachOperation* AttachListener::dequeue() { return op; } + +// Performs initialization at vm startup +// For BSD we remove any stale .java_pid file which could cause +// an attaching process to think we are ready to receive on the +// domain socket before we are properly initialized + +void AttachListener::vm_start() { + char fn[UNIX_PATH_MAX]; + struct stat64 st; + int ret; + + int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d", + os::get_temp_directory(), os::current_process_id()); + assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow"); + + RESTARTABLE(::stat64(fn, &st), ret); + if (ret == 0) { + ret = ::unlink(fn); + if (ret == -1) { + debug_only(warning("failed to remove stale attach pid file at %s", fn)); + } + } +} + int AttachListener::pd_init() { JavaThread* thread = JavaThread::current(); ThreadBlockInVM tbivm(thread); diff --git a/hotspot/src/os/bsd/vm/os_bsd.cpp b/hotspot/src/os/bsd/vm/os_bsd.cpp index 2db740583e8..55043ad243a 100644 --- a/hotspot/src/os/bsd/vm/os_bsd.cpp +++ b/hotspot/src/os/bsd/vm/os_bsd.cpp @@ -1234,12 +1234,13 @@ bool os::address_is_in_vm(address addr) { Dl_info dlinfo; if (libjvm_base_addr == NULL) { - dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo); - libjvm_base_addr = (address)dlinfo.dli_fbase; + if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { + libjvm_base_addr = (address)dlinfo.dli_fbase; + } assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); } - if (dladdr((void *)addr, &dlinfo)) { + if (dladdr((void *)addr, &dlinfo) != 0) { if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; } @@ -1251,35 +1252,40 @@ bool os::address_is_in_vm(address addr) { bool os::dll_address_to_function_name(address addr, char *buf, int buflen, int *offset) { + // buf is not optional, but offset is optional + assert(buf != NULL, "sanity check"); + Dl_info dlinfo; char localbuf[MACH_MAXSYMLEN]; - // dladdr will find names of dynamic functions only, but does - // it set dli_fbase with mach_header address when it "fails" ? - if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) { - if (buf != NULL) { - if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { + if (dladdr((void*)addr, &dlinfo) != 0) { + // see if we have a matching symbol + if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { + if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); } + if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; + return true; } - if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; - return true; - } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) { - if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), - buf, buflen, offset, dlinfo.dli_fname)) { - return true; + // no matching symbol so try for just file info + if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { + if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), + buf, buflen, offset, dlinfo.dli_fname)) { + return true; + } } - } - // Handle non-dymanic manually: - if (dlinfo.dli_fbase != NULL && - Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, dlinfo.dli_fbase)) { - if(!Decoder::demangle(localbuf, buf, buflen)) { - jio_snprintf(buf, buflen, "%s", localbuf); + // Handle non-dynamic manually: + if (dlinfo.dli_fbase != NULL && + Decoder::decode(addr, localbuf, MACH_MAXSYMLEN, offset, + dlinfo.dli_fbase)) { + if (!Decoder::demangle(localbuf, buf, buflen)) { + jio_snprintf(buf, buflen, "%s", localbuf); + } + return true; } - return true; } - if (buf != NULL) buf[0] = '\0'; + buf[0] = '\0'; if (offset != NULL) *offset = -1; return false; } @@ -1287,17 +1293,24 @@ bool os::dll_address_to_function_name(address addr, char *buf, // ported from solaris version bool os::dll_address_to_library_name(address addr, char* buf, int buflen, int* offset) { + // buf is not optional, but offset is optional + assert(buf != NULL, "sanity check"); + Dl_info dlinfo; - if (dladdr((void*)addr, &dlinfo)){ - if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); - if (offset) *offset = addr - (address)dlinfo.dli_fbase; - return true; - } else { - if (buf) buf[0] = '\0'; - if (offset) *offset = -1; - return false; + if (dladdr((void*)addr, &dlinfo) != 0) { + if (dlinfo.dli_fname != NULL) { + jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); + } + if (dlinfo.dli_fbase != NULL && offset != NULL) { + *offset = addr - (address)dlinfo.dli_fbase; + } + return true; } + + buf[0] = '\0'; + if (offset) *offset = -1; + return false; } // Loads .dll/.so and @@ -1520,49 +1533,50 @@ static bool _print_ascii_file(const char* filename, outputStream* st) { } void os::print_dll_info(outputStream *st) { - st->print_cr("Dynamic libraries:"); + st->print_cr("Dynamic libraries:"); #ifdef RTLD_DI_LINKMAP - Dl_info dli; - void *handle; - Link_map *map; - Link_map *p; + Dl_info dli; + void *handle; + Link_map *map; + Link_map *p; - if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) { - st->print_cr("Error: Cannot print dynamic libraries."); - return; - } - handle = dlopen(dli.dli_fname, RTLD_LAZY); - if (handle == NULL) { - st->print_cr("Error: Cannot print dynamic libraries."); - return; - } - dlinfo(handle, RTLD_DI_LINKMAP, &map); - if (map == NULL) { - st->print_cr("Error: Cannot print dynamic libraries."); - return; - } + if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 || + dli.dli_fname == NULL) { + st->print_cr("Error: Cannot print dynamic libraries."); + return; + } + handle = dlopen(dli.dli_fname, RTLD_LAZY); + if (handle == NULL) { + st->print_cr("Error: Cannot print dynamic libraries."); + return; + } + dlinfo(handle, RTLD_DI_LINKMAP, &map); + if (map == NULL) { + st->print_cr("Error: Cannot print dynamic libraries."); + return; + } - while (map->l_prev != NULL) - map = map->l_prev; + while (map->l_prev != NULL) + map = map->l_prev; - while (map != NULL) { - st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name); - map = map->l_next; - } + while (map != NULL) { + st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name); + map = map->l_next; + } - dlclose(handle); + dlclose(handle); #elif defined(__APPLE__) - uint32_t count; - uint32_t i; + uint32_t count; + uint32_t i; - count = _dyld_image_count(); - for (i = 1; i < count; i++) { - const char *name = _dyld_get_image_name(i); - intptr_t slide = _dyld_get_image_vmaddr_slide(i); - st->print_cr(PTR_FORMAT " \t%s", slide, name); - } + count = _dyld_image_count(); + for (i = 1; i < count; i++) { + const char *name = _dyld_get_image_name(i); + intptr_t slide = _dyld_get_image_vmaddr_slide(i); + st->print_cr(PTR_FORMAT " \t%s", slide, name); + } #else - st->print_cr("Error: Cannot print dynamic libraries."); + st->print_cr("Error: Cannot print dynamic libraries."); #endif } @@ -1707,8 +1721,11 @@ void os::jvm_path(char *buf, jint buflen) { bool ret = dll_address_to_library_name( CAST_FROM_FN_PTR(address, os::jvm_path), dli_fname, sizeof(dli_fname), NULL); - assert(ret != 0, "cannot locate libjvm"); - char *rp = realpath(dli_fname, buf); + assert(ret, "cannot locate libjvm"); + char *rp = NULL; + if (ret && dli_fname[0] != '\0') { + rp = realpath(dli_fname, buf); + } if (rp == NULL) return; @@ -3747,20 +3764,20 @@ int os::Bsd::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mutex, bool os::find(address addr, outputStream* st) { Dl_info dlinfo; memset(&dlinfo, 0, sizeof(dlinfo)); - if (dladdr(addr, &dlinfo)) { + if (dladdr(addr, &dlinfo) != 0) { st->print(PTR_FORMAT ": ", addr); - if (dlinfo.dli_sname != NULL) { + if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { st->print("%s+%#x", dlinfo.dli_sname, addr - (intptr_t)dlinfo.dli_saddr); - } else if (dlinfo.dli_fname) { + } else if (dlinfo.dli_fbase != NULL) { st->print("", addr - (intptr_t)dlinfo.dli_fbase); } else { st->print(""); } - if (dlinfo.dli_fname) { + if (dlinfo.dli_fname != NULL) { st->print(" in %s", dlinfo.dli_fname); } - if (dlinfo.dli_fbase) { + if (dlinfo.dli_fbase != NULL) { st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); } st->cr(); @@ -3773,7 +3790,7 @@ bool os::find(address addr, outputStream* st) { if (!lowest) lowest = (address) dlinfo.dli_fbase; if (begin < lowest) begin = lowest; Dl_info dlinfo2; - if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr + if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) end = (address) dlinfo2.dli_saddr; Disassembler::decode(begin, end, st); diff --git a/hotspot/src/os/linux/vm/attachListener_linux.cpp b/hotspot/src/os/linux/vm/attachListener_linux.cpp index 035d298a36c..700a09ff0c5 100644 --- a/hotspot/src/os/linux/vm/attachListener_linux.cpp +++ b/hotspot/src/os/linux/vm/attachListener_linux.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -432,6 +432,30 @@ AttachOperation* AttachListener::dequeue() { return op; } + +// Performs initialization at vm startup +// For Linux we remove any stale .java_pid file which could cause +// an attaching process to think we are ready to receive on the +// domain socket before we are properly initialized + +void AttachListener::vm_start() { + char fn[UNIX_PATH_MAX]; + struct stat64 st; + int ret; + + int n = snprintf(fn, UNIX_PATH_MAX, "%s/.java_pid%d", + os::get_temp_directory(), os::current_process_id()); + assert(n < (int)UNIX_PATH_MAX, "java_pid file name buffer overflow"); + + RESTARTABLE(::stat64(fn, &st), ret); + if (ret == 0) { + ret = ::unlink(fn); + if (ret == -1) { + debug_only(warning("failed to remove stale attach pid file at %s", fn)); + } + } +} + int AttachListener::pd_init() { JavaThread* thread = JavaThread::current(); ThreadBlockInVM tbivm(thread); diff --git a/hotspot/src/os/linux/vm/jsig.c b/hotspot/src/os/linux/vm/jsig.c index 13ddb668341..ae2f25b33c4 100644 --- a/hotspot/src/os/linux/vm/jsig.c +++ b/hotspot/src/os/linux/vm/jsig.c @@ -1,5 +1,5 @@ /* - * Copyright (c) 2001, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2001, 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 @@ -107,7 +107,7 @@ static sa_handler_t set_signal(int sig, sa_handler_t disp, bool is_sigset) { signal_lock(); - sigused = (MASK(sig) & jvmsigs) != 0; + sigused = (sig < MAXSIGNUM) && ((MASK(sig) & jvmsigs) != 0); if (jvm_signal_installed && sigused) { /* jvm has installed its signal handler for this signal. */ /* Save the handler. Don't really install it. */ @@ -116,7 +116,7 @@ static sa_handler_t set_signal(int sig, sa_handler_t disp, bool is_sigset) { signal_unlock(); return oldhandler; - } else if (jvm_signal_installing) { + } else if (sig < MAXSIGNUM && jvm_signal_installing) { /* jvm is installing its signal handlers. Install the new * handlers and save the old ones. jvm uses sigaction(). * Leave the piece here just in case. */ @@ -165,7 +165,7 @@ int sigaction(int sig, const struct sigaction *act, struct sigaction *oact) { signal_lock(); - sigused = (MASK(sig) & jvmsigs) != 0; + sigused = (sig < MAXSIGNUM) && ((MASK(sig) & jvmsigs) != 0); if (jvm_signal_installed && sigused) { /* jvm has installed its signal handler for this signal. */ /* Save the handler. Don't really install it. */ @@ -178,7 +178,7 @@ int sigaction(int sig, const struct sigaction *act, struct sigaction *oact) { signal_unlock(); return 0; - } else if (jvm_signal_installing) { + } else if (sig < MAXSIGNUM && jvm_signal_installing) { /* jvm is installing its signal handlers. Install the new * handlers and save the old ones. */ res = call_os_sigaction(sig, act, &oldAct); diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp index 53bfe4e7369..df58be635d1 100644 --- a/hotspot/src/os/linux/vm/os_linux.cpp +++ b/hotspot/src/os/linux/vm/os_linux.cpp @@ -1682,12 +1682,13 @@ bool os::address_is_in_vm(address addr) { Dl_info dlinfo; if (libjvm_base_addr == NULL) { - dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo); - libjvm_base_addr = (address)dlinfo.dli_fbase; + if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { + libjvm_base_addr = (address)dlinfo.dli_fbase; + } assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); } - if (dladdr((void *)addr, &dlinfo)) { + if (dladdr((void *)addr, &dlinfo) != 0) { if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; } @@ -1696,24 +1697,30 @@ bool os::address_is_in_vm(address addr) { bool os::dll_address_to_function_name(address addr, char *buf, int buflen, int *offset) { + // buf is not optional, but offset is optional + assert(buf != NULL, "sanity check"); + Dl_info dlinfo; - if (dladdr((void*)addr, &dlinfo) && dlinfo.dli_sname != NULL) { - if (buf != NULL) { - if(!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { + if (dladdr((void*)addr, &dlinfo) != 0) { + // see if we have a matching symbol + if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { + if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); } + if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; + return true; } - if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; - return true; - } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) { - if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), - buf, buflen, offset, dlinfo.dli_fname)) { - return true; + // no matching symbol so try for just file info + if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { + if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), + buf, buflen, offset, dlinfo.dli_fname)) { + return true; + } } } - if (buf != NULL) buf[0] = '\0'; + buf[0] = '\0'; if (offset != NULL) *offset = -1; return false; } @@ -1764,6 +1771,9 @@ static int address_to_library_name_callback(struct dl_phdr_info *info, bool os::dll_address_to_library_name(address addr, char* buf, int buflen, int* offset) { + // buf is not optional, but offset is optional + assert(buf != NULL, "sanity check"); + Dl_info dlinfo; struct _address_to_library_name data; @@ -1782,15 +1792,20 @@ bool os::dll_address_to_library_name(address addr, char* buf, // buf already contains library name if (offset) *offset = addr - data.base; return true; - } else if (dladdr((void*)addr, &dlinfo)){ - if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); - if (offset) *offset = addr - (address)dlinfo.dli_fbase; - return true; - } else { - if (buf) buf[0] = '\0'; - if (offset) *offset = -1; - return false; } + if (dladdr((void*)addr, &dlinfo) != 0) { + if (dlinfo.dli_fname != NULL) { + jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); + } + if (dlinfo.dli_fbase != NULL && offset != NULL) { + *offset = addr - (address)dlinfo.dli_fbase; + } + return true; + } + + buf[0] = '\0'; + if (offset) *offset = -1; + return false; } // Loads .dll/.so and @@ -2317,8 +2332,11 @@ void os::jvm_path(char *buf, jint buflen) { bool ret = dll_address_to_library_name( CAST_FROM_FN_PTR(address, os::jvm_path), dli_fname, sizeof(dli_fname), NULL); - assert(ret != 0, "cannot locate libjvm"); - char *rp = realpath(dli_fname, buf); + assert(ret, "cannot locate libjvm"); + char *rp = NULL; + if (ret && dli_fname[0] != '\0') { + rp = realpath(dli_fname, buf); + } if (rp == NULL) return; @@ -4730,20 +4748,20 @@ int os::Linux::safe_cond_timedwait(pthread_cond_t *_cond, pthread_mutex_t *_mute bool os::find(address addr, outputStream* st) { Dl_info dlinfo; memset(&dlinfo, 0, sizeof(dlinfo)); - if (dladdr(addr, &dlinfo)) { + if (dladdr(addr, &dlinfo) != 0) { st->print(PTR_FORMAT ": ", addr); - if (dlinfo.dli_sname != NULL) { + if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { st->print("%s+%#x", dlinfo.dli_sname, addr - (intptr_t)dlinfo.dli_saddr); - } else if (dlinfo.dli_fname) { + } else if (dlinfo.dli_fbase != NULL) { st->print("", addr - (intptr_t)dlinfo.dli_fbase); } else { st->print(""); } - if (dlinfo.dli_fname) { + if (dlinfo.dli_fname != NULL) { st->print(" in %s", dlinfo.dli_fname); } - if (dlinfo.dli_fbase) { + if (dlinfo.dli_fbase != NULL) { st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); } st->cr(); @@ -4756,7 +4774,7 @@ bool os::find(address addr, outputStream* st) { if (!lowest) lowest = (address) dlinfo.dli_fbase; if (begin < lowest) begin = lowest; Dl_info dlinfo2; - if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr + if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) end = (address) dlinfo2.dli_saddr; Disassembler::decode(begin, end, st); diff --git a/hotspot/src/os/posix/vm/os_posix.cpp b/hotspot/src/os/posix/vm/os_posix.cpp index e2d7c2d7f7f..bf6a1fafacd 100644 --- a/hotspot/src/os/posix/vm/os_posix.cpp +++ b/hotspot/src/os/posix/vm/os_posix.cpp @@ -259,3 +259,52 @@ const char* os::get_current_directory(char *buf, size_t buflen) { FILE* os::open(int fd, const char* mode) { return ::fdopen(fd, mode); } + +os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() { + assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread"); +} + +/* + * See the caveats for this class in os_posix.hpp + * Protects the callback call so that SIGSEGV / SIGBUS jumps back into this + * method and returns false. If none of the signals are raised, returns true. + * The callback is supposed to provide the method that should be protected. + */ +bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) { + assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread"); + assert(!WatcherThread::watcher_thread()->has_crash_protection(), + "crash_protection already set?"); + + if (sigsetjmp(_jmpbuf, 1) == 0) { + // make sure we can see in the signal handler that we have crash protection + // installed + WatcherThread::watcher_thread()->set_crash_protection(this); + cb.call(); + // and clear the crash protection + WatcherThread::watcher_thread()->set_crash_protection(NULL); + return true; + } + // this happens when we siglongjmp() back + WatcherThread::watcher_thread()->set_crash_protection(NULL); + return false; +} + +void os::WatcherThreadCrashProtection::restore() { + assert(WatcherThread::watcher_thread()->has_crash_protection(), + "must have crash protection"); + + siglongjmp(_jmpbuf, 1); +} + +void os::WatcherThreadCrashProtection::check_crash_protection(int sig, + Thread* thread) { + + if (thread != NULL && + thread->is_Watcher_thread() && + WatcherThread::watcher_thread()->has_crash_protection()) { + + if (sig == SIGSEGV || sig == SIGBUS) { + WatcherThread::watcher_thread()->crash_protection()->restore(); + } + } +} diff --git a/hotspot/src/os/posix/vm/os_posix.hpp b/hotspot/src/os/posix/vm/os_posix.hpp index c7d1d6bd741..16a065acf30 100644 --- a/hotspot/src/os/posix/vm/os_posix.hpp +++ b/hotspot/src/os/posix/vm/os_posix.hpp @@ -37,5 +37,24 @@ protected: }; +/* + * Crash protection for the watcher thread. Wrap the callback + * with a sigsetjmp and in case of a SIGSEGV/SIGBUS we siglongjmp + * back. + * To be able to use this - don't take locks, don't rely on destructors, + * don't make OS library calls, don't allocate memory, don't print, + * don't call code that could leave the heap / memory in an inconsistent state, + * or anything else where we are not in control if we suddenly jump out. + */ +class WatcherThreadCrashProtection : public StackObj { +public: + WatcherThreadCrashProtection(); + bool call(os::CrashProtectionCallback& cb); + + static void check_crash_protection(int signal, Thread* thread); +private: + void restore(); + sigjmp_buf _jmpbuf; +}; #endif diff --git a/hotspot/src/os/solaris/dtrace/jhelper.d b/hotspot/src/os/solaris/dtrace/jhelper.d index 976a832107f..752f5ae535e 100644 --- a/hotspot/src/os/solaris/dtrace/jhelper.d +++ b/hotspot/src/os/solaris/dtrace/jhelper.d @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -332,12 +332,15 @@ dtrace:helper:ustack: this->nameSymbol = copyin_ptr(this->constantPool + this->nameIndex * sizeof (pointer) + SIZE_ConstantPool); + /* The symbol is a CPSlot and has lower bit set to indicate metadata */ + this->nameSymbol &= (~1); /* remove metadata lsb */ this->nameSymbolLength = copyin_uint16(this->nameSymbol + OFFSET_Symbol_length); this->signatureSymbol = copyin_ptr(this->constantPool + this->signatureIndex * sizeof (pointer) + SIZE_ConstantPool); + this->signatureSymbol &= (~1); /* remove metadata lsb */ this->signatureSymbolLength = copyin_uint16(this->signatureSymbol + OFFSET_Symbol_length); diff --git a/hotspot/src/os/solaris/vm/attachListener_solaris.cpp b/hotspot/src/os/solaris/vm/attachListener_solaris.cpp index 9cc66876268..37400795e13 100644 --- a/hotspot/src/os/solaris/vm/attachListener_solaris.cpp +++ b/hotspot/src/os/solaris/vm/attachListener_solaris.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -576,6 +576,30 @@ AttachOperation* AttachListener::dequeue() { return op; } + +// Performs initialization at vm startup +// For Solaris we remove any stale .java_pid file which could cause +// an attaching process to think we are ready to receive a door_call +// before we are properly initialized + +void AttachListener::vm_start() { + char fn[PATH_MAX+1]; + struct stat64 st; + int ret; + + int n = snprintf(fn, sizeof(fn), "%s/.java_pid%d", + os::get_temp_directory(), os::current_process_id()); + assert(n < sizeof(fn), "java_pid file name buffer overflow"); + + RESTARTABLE(::stat64(fn, &st), ret); + if (ret == 0) { + ret = ::unlink(fn); + if (ret == -1) { + debug_only(warning("failed to remove stale attach pid file at %s", fn)); + } + } +} + int AttachListener::pd_init() { JavaThread* thread = JavaThread::current(); ThreadBlockInVM tbivm(thread); diff --git a/hotspot/src/os/solaris/vm/globals_solaris.hpp b/hotspot/src/os/solaris/vm/globals_solaris.hpp index a567a357e16..2abbe15a7fd 100644 --- a/hotspot/src/os/solaris/vm/globals_solaris.hpp +++ b/hotspot/src/os/solaris/vm/globals_solaris.hpp @@ -30,15 +30,6 @@ // #define RUNTIME_OS_FLAGS(develop, develop_pd, product, product_pd, diagnostic, notproduct) \ \ - product(bool, UseISM, false, \ - "Use Intimate Shared Memory (Solaris Only)") \ - \ - product(bool, UsePermISM, false, \ - "Obsolete flag for compatibility (same as UseISM)") \ - \ - product(bool, UseMPSS, true, \ - "Use Multiple Page Size Support (Solaris 9 Only)") \ - \ product(bool, UseExtendedFileIO, true, \ "Enable workaround for limitations of stdio FILE structure") diff --git a/hotspot/src/os/solaris/vm/os_solaris.cpp b/hotspot/src/os/solaris/vm/os_solaris.cpp index ad8c52914be..0a94cb536ab 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.cpp +++ b/hotspot/src/os/solaris/vm/os_solaris.cpp @@ -115,45 +115,6 @@ // for timer info max values which include all bits #define ALL_64_BITS CONST64(0xFFFFFFFFFFFFFFFF) -#ifdef _GNU_SOURCE -// See bug #6514594 -extern "C" int madvise(caddr_t, size_t, int); -extern "C" int memcntl(caddr_t addr, size_t len, int cmd, caddr_t arg, - int attr, int mask); -#endif //_GNU_SOURCE - -/* - MPSS Changes Start. - The JVM binary needs to be built and run on pre-Solaris 9 - systems, but the constants needed by MPSS are only in Solaris 9 - header files. They are textually replicated here to allow - building on earlier systems. Once building on Solaris 8 is - no longer a requirement, these #defines can be replaced by ordinary - system .h inclusion. - - In earlier versions of the JDK and Solaris, we used ISM for large pages. - But ISM requires shared memory to achieve this and thus has many caveats. - MPSS is a fully transparent and is a cleaner way to get large pages. - Although we still require keeping ISM for backward compatiblitiy as well as - giving the opportunity to use large pages on older systems it is - recommended that MPSS be used for Solaris 9 and above. - -*/ - -#ifndef MC_HAT_ADVISE - -struct memcntl_mha { - uint_t mha_cmd; /* command(s) */ - uint_t mha_flags; - size_t mha_pagesize; -}; -#define MC_HAT_ADVISE 7 /* advise hat map size */ -#define MHA_MAPSIZE_VA 0x1 /* set preferred page size */ -#define MAP_ALIGN 0x200 /* addr specifies alignment */ - -#endif -// MPSS Changes End. - // Here are some liblgrp types from sys/lgrp_user.h to be able to // compile on older systems without this header file. @@ -172,32 +133,6 @@ struct memcntl_mha { # define LGRP_RSRC_MEM 1 /* memory resources */ #endif -// Some more macros from sys/mman.h that are not present in Solaris 8. - -#ifndef MAX_MEMINFO_CNT -/* - * info_req request type definitions for meminfo - * request types starting with MEMINFO_V are used for Virtual addresses - * and should not be mixed with MEMINFO_PLGRP which is targeted for Physical - * addresses - */ -# define MEMINFO_SHIFT 16 -# define MEMINFO_MASK (0xFF << MEMINFO_SHIFT) -# define MEMINFO_VPHYSICAL (0x01 << MEMINFO_SHIFT) /* get physical addr */ -# define MEMINFO_VLGRP (0x02 << MEMINFO_SHIFT) /* get lgroup */ -# define MEMINFO_VPAGESIZE (0x03 << MEMINFO_SHIFT) /* size of phys page */ -# define MEMINFO_VREPLCNT (0x04 << MEMINFO_SHIFT) /* no. of replica */ -# define MEMINFO_VREPL (0x05 << MEMINFO_SHIFT) /* physical replica */ -# define MEMINFO_VREPL_LGRP (0x06 << MEMINFO_SHIFT) /* lgrp of replica */ -# define MEMINFO_PLGRP (0x07 << MEMINFO_SHIFT) /* lgroup for paddr */ - -/* maximum number of addresses meminfo() can process at a time */ -# define MAX_MEMINFO_CNT 256 - -/* maximum number of request types */ -# define MAX_MEMINFO_REQ 31 -#endif - // see thr_setprio(3T) for the basis of these numbers #define MinimumPriority 0 #define NormalPriority 64 @@ -1924,12 +1859,13 @@ bool os::address_is_in_vm(address addr) { Dl_info dlinfo; if (libjvm_base_addr == NULL) { - dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo); - libjvm_base_addr = (address)dlinfo.dli_fbase; + if (dladdr(CAST_FROM_FN_PTR(void *, os::address_is_in_vm), &dlinfo) != 0) { + libjvm_base_addr = (address)dlinfo.dli_fbase; + } assert(libjvm_base_addr !=NULL, "Cannot obtain base address for libjvm"); } - if (dladdr((void *)addr, &dlinfo)) { + if (dladdr((void *)addr, &dlinfo) != 0) { if (libjvm_base_addr == (address)dlinfo.dli_fbase) return true; } @@ -1941,114 +1877,133 @@ static dladdr1_func_type dladdr1_func = NULL; bool os::dll_address_to_function_name(address addr, char *buf, int buflen, int * offset) { + // buf is not optional, but offset is optional + assert(buf != NULL, "sanity check"); + Dl_info dlinfo; // dladdr1_func was initialized in os::init() - if (dladdr1_func){ - // yes, we have dladdr1 + if (dladdr1_func != NULL) { + // yes, we have dladdr1 - // Support for dladdr1 is checked at runtime; it may be - // available even if the vm is built on a machine that does - // not have dladdr1 support. Make sure there is a value for - // RTLD_DL_SYMENT. - #ifndef RTLD_DL_SYMENT - #define RTLD_DL_SYMENT 1 - #endif + // Support for dladdr1 is checked at runtime; it may be + // available even if the vm is built on a machine that does + // not have dladdr1 support. Make sure there is a value for + // RTLD_DL_SYMENT. + #ifndef RTLD_DL_SYMENT + #define RTLD_DL_SYMENT 1 + #endif #ifdef _LP64 - Elf64_Sym * info; + Elf64_Sym * info; #else - Elf32_Sym * info; + Elf32_Sym * info; #endif - if (dladdr1_func((void *)addr, &dlinfo, (void **)&info, - RTLD_DL_SYMENT)) { - if ((char *)dlinfo.dli_saddr + info->st_size > (char *)addr) { - if (buf != NULL) { - if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) - jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); - } - if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; - return true; - } - } - if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) { - if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), - buf, buflen, offset, dlinfo.dli_fname)) { + if (dladdr1_func((void *)addr, &dlinfo, (void **)&info, + RTLD_DL_SYMENT) != 0) { + // see if we have a matching symbol that covers our address + if (dlinfo.dli_saddr != NULL && + (char *)dlinfo.dli_saddr + info->st_size > (char *)addr) { + if (dlinfo.dli_sname != NULL) { + if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { + jio_snprintf(buf, buflen, "%s", dlinfo.dli_sname); + } + if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; return true; } } - if (buf != NULL) buf[0] = '\0'; - if (offset != NULL) *offset = -1; - return false; - } else { - // no, only dladdr is available - if (dladdr((void *)addr, &dlinfo)) { - if (buf != NULL) { - if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) - jio_snprintf(buf, buflen, dlinfo.dli_sname); - } - if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; - return true; - } else if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != 0) { + // no matching symbol so try for just file info + if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), - buf, buflen, offset, dlinfo.dli_fname)) { + buf, buflen, offset, dlinfo.dli_fname)) { return true; } } - if (buf != NULL) buf[0] = '\0'; - if (offset != NULL) *offset = -1; - return false; + } + buf[0] = '\0'; + if (offset != NULL) *offset = -1; + return false; } + + // no, only dladdr is available + if (dladdr((void *)addr, &dlinfo) != 0) { + // see if we have a matching symbol + if (dlinfo.dli_saddr != NULL && dlinfo.dli_sname != NULL) { + if (!Decoder::demangle(dlinfo.dli_sname, buf, buflen)) { + jio_snprintf(buf, buflen, dlinfo.dli_sname); + } + if (offset != NULL) *offset = addr - (address)dlinfo.dli_saddr; + return true; + } + // no matching symbol so try for just file info + if (dlinfo.dli_fname != NULL && dlinfo.dli_fbase != NULL) { + if (Decoder::decode((address)(addr - (address)dlinfo.dli_fbase), + buf, buflen, offset, dlinfo.dli_fname)) { + return true; + } + } + } + buf[0] = '\0'; + if (offset != NULL) *offset = -1; + return false; } bool os::dll_address_to_library_name(address addr, char* buf, int buflen, int* offset) { + // buf is not optional, but offset is optional + assert(buf != NULL, "sanity check"); + Dl_info dlinfo; - if (dladdr((void*)addr, &dlinfo)){ - if (buf) jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); - if (offset) *offset = addr - (address)dlinfo.dli_fbase; - return true; - } else { - if (buf) buf[0] = '\0'; - if (offset) *offset = -1; - return false; + if (dladdr((void*)addr, &dlinfo) != 0) { + if (dlinfo.dli_fname != NULL) { + jio_snprintf(buf, buflen, "%s", dlinfo.dli_fname); + } + if (dlinfo.dli_fbase != NULL && offset != NULL) { + *offset = addr - (address)dlinfo.dli_fbase; + } + return true; } + + buf[0] = '\0'; + if (offset) *offset = -1; + return false; } // Prints the names and full paths of all opened dynamic libraries // for current process void os::print_dll_info(outputStream * st) { - Dl_info dli; - void *handle; - Link_map *map; - Link_map *p; + Dl_info dli; + void *handle; + Link_map *map; + Link_map *p; - st->print_cr("Dynamic libraries:"); st->flush(); + st->print_cr("Dynamic libraries:"); st->flush(); - if (!dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli)) { - st->print_cr("Error: Cannot print dynamic libraries."); - return; - } - handle = dlopen(dli.dli_fname, RTLD_LAZY); - if (handle == NULL) { - st->print_cr("Error: Cannot print dynamic libraries."); - return; - } - dlinfo(handle, RTLD_DI_LINKMAP, &map); - if (map == NULL) { - st->print_cr("Error: Cannot print dynamic libraries."); - return; - } + if (dladdr(CAST_FROM_FN_PTR(void *, os::print_dll_info), &dli) == 0 || + dli.dli_fname == NULL) { + st->print_cr("Error: Cannot print dynamic libraries."); + return; + } + handle = dlopen(dli.dli_fname, RTLD_LAZY); + if (handle == NULL) { + st->print_cr("Error: Cannot print dynamic libraries."); + return; + } + dlinfo(handle, RTLD_DI_LINKMAP, &map); + if (map == NULL) { + st->print_cr("Error: Cannot print dynamic libraries."); + return; + } - while (map->l_prev != NULL) - map = map->l_prev; + while (map->l_prev != NULL) + map = map->l_prev; - while (map != NULL) { - st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name); - map = map->l_next; - } + while (map != NULL) { + st->print_cr(PTR_FORMAT " \t%s", map->l_addr, map->l_name); + map = map->l_next; + } - dlclose(handle); + dlclose(handle); } // Loads .dll/.so and @@ -2475,7 +2430,12 @@ void os::jvm_path(char *buf, jint buflen) { Dl_info dlinfo; int ret = dladdr(CAST_FROM_FN_PTR(void *, os::jvm_path), &dlinfo); assert(ret != 0, "cannot locate libjvm"); - realpath((char *)dlinfo.dli_fname, buf); + if (ret != 0 && dlinfo.dli_fname != NULL) { + realpath((char *)dlinfo.dli_fname, buf); + } else { + buf[0] = '\0'; + return; + } if (Arguments::created_by_gamma_launcher()) { // Support for the gamma launcher. Typical value for buf is @@ -2859,7 +2819,7 @@ int os::Solaris::commit_memory_impl(char* addr, size_t bytes, size_t alignment_hint, bool exec) { int err = Solaris::commit_memory_impl(addr, bytes, exec); if (err == 0) { - if (UseMPSS && alignment_hint > (size_t)vm_page_size()) { + if (UseLargePages && (alignment_hint > (size_t)vm_page_size())) { // If the large page size has been set and the VM // is using large pages, use the large page size // if it is smaller than the alignment hint. This is @@ -2878,7 +2838,7 @@ int os::Solaris::commit_memory_impl(char* addr, size_t bytes, page_size = alignment_hint; } // Since this is a hint, ignore any failures. - (void)Solaris::set_mpss_range(addr, bytes, page_size); + (void)Solaris::setup_large_pages(addr, bytes, page_size); } } return err; @@ -2921,8 +2881,8 @@ bool os::remove_stack_guard_pages(char* addr, size_t size) { void os::pd_realign_memory(char *addr, size_t bytes, size_t alignment_hint) { assert((intptr_t)addr % alignment_hint == 0, "Address should be aligned."); assert((intptr_t)(addr + bytes) % alignment_hint == 0, "End should be aligned."); - if (UseLargePages && UseMPSS) { - Solaris::set_mpss_range(addr, bytes, alignment_hint); + if (UseLargePages) { + Solaris::setup_large_pages(addr, bytes, alignment_hint); } } @@ -3321,47 +3281,8 @@ bool os::unguard_memory(char* addr, size_t bytes) { } // Large page support - -// UseLargePages is the master flag to enable/disable large page memory. -// UseMPSS and UseISM are supported for compatibility reasons. Their combined -// effects can be described in the following table: -// -// UseLargePages UseMPSS UseISM -// false * * => UseLargePages is the master switch, turning -// it off will turn off both UseMPSS and -// UseISM. VM will not use large page memory -// regardless the settings of UseMPSS/UseISM. -// true false false => Unless future Solaris provides other -// mechanism to use large page memory, this -// combination is equivalent to -UseLargePages, -// VM will not use large page memory -// true true false => JVM will use MPSS for large page memory. -// This is the default behavior. -// true false true => JVM will use ISM for large page memory. -// true true true => JVM will use ISM if it is available. -// Otherwise, JVM will fall back to MPSS. -// Becaues ISM is now available on all -// supported Solaris versions, this combination -// is equivalent to +UseISM -UseMPSS. - static size_t _large_page_size = 0; -bool os::Solaris::ism_sanity_check(bool warn, size_t * page_size) { - // x86 uses either 2M or 4M page, depending on whether PAE (Physical Address - // Extensions) mode is enabled. AMD64/EM64T uses 2M page in 64bit mode. Sparc - // can support multiple page sizes. - - // Don't bother to probe page size because getpagesizes() comes with MPSS. - // ISM is only recommended on old Solaris where there is no MPSS support. - // Simply choose a conservative value as default. - *page_size = LargePageSizeInBytes ? LargePageSizeInBytes : - SPARC_ONLY(4 * M) IA32_ONLY(4 * M) AMD64_ONLY(2 * M) - ARM_ONLY(2 * M); - - // ISM is available on all supported Solaris versions - return true; -} - // Insertion sort for small arrays (descending order). static void insertion_sort_descending(size_t* array, int len) { for (int i = 0; i < len; i++) { @@ -3374,7 +3295,7 @@ static void insertion_sort_descending(size_t* array, int len) { } } -bool os::Solaris::mpss_sanity_check(bool warn, size_t * page_size) { +bool os::Solaris::mpss_sanity_check(bool warn, size_t* page_size) { const unsigned int usable_count = VM_Version::page_size_count(); if (usable_count == 1) { return false; @@ -3440,41 +3361,24 @@ bool os::Solaris::mpss_sanity_check(bool warn, size_t * page_size) { } void os::large_page_init() { - if (!UseLargePages) { - UseISM = false; - UseMPSS = false; - return; + if (UseLargePages) { + // print a warning if any large page related flag is specified on command line + bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) || + !FLAG_IS_DEFAULT(LargePageSizeInBytes); + + UseLargePages = Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size); } - - // print a warning if any large page related flag is specified on command line - bool warn_on_failure = !FLAG_IS_DEFAULT(UseLargePages) || - !FLAG_IS_DEFAULT(UseISM) || - !FLAG_IS_DEFAULT(UseMPSS) || - !FLAG_IS_DEFAULT(LargePageSizeInBytes); - UseISM = UseISM && - Solaris::ism_sanity_check(warn_on_failure, &_large_page_size); - if (UseISM) { - // ISM disables MPSS to be compatible with old JDK behavior - UseMPSS = false; - _page_sizes[0] = _large_page_size; - _page_sizes[1] = vm_page_size(); - } - - UseMPSS = UseMPSS && - Solaris::mpss_sanity_check(warn_on_failure, &_large_page_size); - - UseLargePages = UseISM || UseMPSS; } -bool os::Solaris::set_mpss_range(caddr_t start, size_t bytes, size_t align) { +bool os::Solaris::setup_large_pages(caddr_t start, size_t bytes, size_t align) { // Signal to OS that we want large pages for addresses // from addr, addr + bytes struct memcntl_mha mpss_struct; mpss_struct.mha_cmd = MHA_MAPSIZE_VA; mpss_struct.mha_pagesize = align; mpss_struct.mha_flags = 0; - if (memcntl(start, bytes, MC_HAT_ADVISE, - (caddr_t) &mpss_struct, 0, 0) < 0) { + // Upon successful completion, memcntl() returns 0 + if (memcntl(start, bytes, MC_HAT_ADVISE, (caddr_t) &mpss_struct, 0, 0)) { debug_only(warning("Attempt to use MPSS failed.")); return false; } @@ -3482,72 +3386,13 @@ bool os::Solaris::set_mpss_range(caddr_t start, size_t bytes, size_t align) { } char* os::reserve_memory_special(size_t size, char* addr, bool exec) { - // "exec" is passed in but not used. Creating the shared image for - // the code cache doesn't have an SHM_X executable permission to check. - assert(UseLargePages && UseISM, "only for ISM large pages"); - - char* retAddr = NULL; - int shmid; - key_t ismKey; - - bool warn_on_failure = UseISM && - (!FLAG_IS_DEFAULT(UseLargePages) || - !FLAG_IS_DEFAULT(UseISM) || - !FLAG_IS_DEFAULT(LargePageSizeInBytes) - ); - char msg[128]; - - ismKey = IPC_PRIVATE; - - // Create a large shared memory region to attach to based on size. - // Currently, size is the total size of the heap - shmid = shmget(ismKey, size, SHM_R | SHM_W | IPC_CREAT); - if (shmid == -1){ - if (warn_on_failure) { - jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno); - warning(msg); - } - return NULL; - } - - // Attach to the region - retAddr = (char *) shmat(shmid, 0, SHM_SHARE_MMU | SHM_R | SHM_W); - int err = errno; - - // Remove shmid. If shmat() is successful, the actual shared memory segment - // will be deleted when it's detached by shmdt() or when the process - // terminates. If shmat() is not successful this will remove the shared - // segment immediately. - shmctl(shmid, IPC_RMID, NULL); - - if (retAddr == (char *) -1) { - if (warn_on_failure) { - jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err); - warning(msg); - } - return NULL; - } - if ((retAddr != NULL) && UseNUMAInterleaving) { - numa_make_global(retAddr, size); - } - - // The memory is committed - MemTracker::record_virtual_memory_reserve_and_commit((address)retAddr, size, mtNone, CURRENT_PC); - - return retAddr; + fatal("os::reserve_memory_special should not be called on Solaris."); + return NULL; } bool os::release_memory_special(char* base, size_t bytes) { - MemTracker::Tracker tkr = MemTracker::get_virtual_memory_release_tracker(); - // detaching the SHM segment will also delete it, see reserve_memory_special() - int rslt = shmdt(base); - if (rslt == 0) { - tkr.record((address)base, bytes); - return true; - } else { - tkr.discard(); - return false; - } + fatal("os::release_memory_special should not be called on Solaris."); + return false; } size_t os::large_page_size() { @@ -3557,11 +3402,11 @@ size_t os::large_page_size() { // MPSS allows application to commit large page memory on demand; with ISM // the entire memory region must be allocated as shared memory. bool os::can_commit_large_page_memory() { - return UseISM ? false : true; + return true; } bool os::can_execute_large_page_memory() { - return UseISM ? false : true; + return true; } static int os_sleep(jlong millis, bool interruptible) { @@ -3835,28 +3680,6 @@ static bool priocntl_enable = false; static const int criticalPrio = 60; // FX/60 is critical thread class/priority on T4 static int java_MaxPriority_to_os_priority = 0; // Saved mapping -// Call the version of priocntl suitable for all supported versions -// of Solaris. We need to call through this wrapper so that we can -// build on Solaris 9 and run on Solaris 8, 9 and 10. -// -// This code should be removed if we ever stop supporting Solaris 8 -// and earlier releases. - -static long priocntl_stub(int pcver, idtype_t idtype, id_t id, int cmd, caddr_t arg); -typedef long (*priocntl_type)(int pcver, idtype_t idtype, id_t id, int cmd, caddr_t arg); -static priocntl_type priocntl_ptr = priocntl_stub; - -// Stub to set the value of the real pointer, and then call the real -// function. - -static long priocntl_stub(int pcver, idtype_t idtype, id_t id, int cmd, caddr_t arg) { - // Try Solaris 8- name only. - priocntl_type tmp = (priocntl_type)dlsym(RTLD_DEFAULT, "__priocntl"); - guarantee(tmp != NULL, "priocntl function not found."); - priocntl_ptr = tmp; - return (*priocntl_ptr)(PC_VERSION, idtype, id, cmd, arg); -} - // lwp_priocntl_init // @@ -3864,9 +3687,7 @@ static long priocntl_stub(int pcver, idtype_t idtype, id_t id, int cmd, caddr_t // // Return errno or 0 if OK. // -static -int lwp_priocntl_init () -{ +static int lwp_priocntl_init () { int rslt; pcinfo_t ClassInfo; pcparms_t ParmInfo; @@ -3906,7 +3727,7 @@ int lwp_priocntl_init () strcpy(ClassInfo.pc_clname, "TS"); ClassInfo.pc_cid = -1; - rslt = (*priocntl_ptr)(PC_VERSION, P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); + rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); if (rslt < 0) return errno; assert(ClassInfo.pc_cid != -1, "cid for TS class is -1"); tsLimits.schedPolicy = ClassInfo.pc_cid; @@ -3915,7 +3736,7 @@ int lwp_priocntl_init () strcpy(ClassInfo.pc_clname, "IA"); ClassInfo.pc_cid = -1; - rslt = (*priocntl_ptr)(PC_VERSION, P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); + rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); if (rslt < 0) return errno; assert(ClassInfo.pc_cid != -1, "cid for IA class is -1"); iaLimits.schedPolicy = ClassInfo.pc_cid; @@ -3924,7 +3745,7 @@ int lwp_priocntl_init () strcpy(ClassInfo.pc_clname, "RT"); ClassInfo.pc_cid = -1; - rslt = (*priocntl_ptr)(PC_VERSION, P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); + rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); if (rslt < 0) return errno; assert(ClassInfo.pc_cid != -1, "cid for RT class is -1"); rtLimits.schedPolicy = ClassInfo.pc_cid; @@ -3933,7 +3754,7 @@ int lwp_priocntl_init () strcpy(ClassInfo.pc_clname, "FX"); ClassInfo.pc_cid = -1; - rslt = (*priocntl_ptr)(PC_VERSION, P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); + rslt = priocntl(P_ALL, 0, PC_GETCID, (caddr_t)&ClassInfo); if (rslt < 0) return errno; assert(ClassInfo.pc_cid != -1, "cid for FX class is -1"); fxLimits.schedPolicy = ClassInfo.pc_cid; @@ -3944,7 +3765,7 @@ int lwp_priocntl_init () // This will normally be IA, TS or, rarely, FX or RT. memset(&ParmInfo, 0, sizeof(ParmInfo)); ParmInfo.pc_cid = PC_CLNULL; - rslt = (*priocntl_ptr) (PC_VERSION, P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo); + rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo); if (rslt < 0) return errno; myClass = ParmInfo.pc_cid; @@ -3952,7 +3773,7 @@ int lwp_priocntl_init () // about the class. ClassInfo.pc_cid = myClass; ClassInfo.pc_clname[0] = 0; - rslt = (*priocntl_ptr) (PC_VERSION, (idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo); + rslt = priocntl((idtype)0, 0, PC_GETCLINFO, (caddr_t)&ClassInfo); if (rslt < 0) return errno; if (ThreadPriorityVerbose) { @@ -3961,7 +3782,7 @@ int lwp_priocntl_init () memset(&ParmInfo, 0, sizeof(pcparms_t)); ParmInfo.pc_cid = PC_CLNULL; - rslt = (*priocntl_ptr)(PC_VERSION, P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo); + rslt = priocntl(P_PID, P_MYID, PC_GETPARMS, (caddr_t)&ParmInfo); if (rslt < 0) return errno; if (ParmInfo.pc_cid == rtLimits.schedPolicy) { @@ -4065,7 +3886,7 @@ int set_lwp_class_and_priority(int ThreadID, int lwpid, memset(&ParmInfo, 0, sizeof(pcparms_t)); ParmInfo.pc_cid = PC_CLNULL; - rslt = (*priocntl_ptr)(PC_VERSION, P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo); + rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ParmInfo); if (rslt < 0) return errno; int cur_class = ParmInfo.pc_cid; @@ -4133,7 +3954,7 @@ int set_lwp_class_and_priority(int ThreadID, int lwpid, return EINVAL; // no clue, punt } - rslt = (*priocntl_ptr)(PC_VERSION, P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo); + rslt = priocntl(P_LWPID, lwpid, PC_SETPARMS, (caddr_t)&ParmInfo); if (ThreadPriorityVerbose && rslt) { tty->print_cr ("PC_SETPARMS ->%d %d\n", rslt, errno); } @@ -4152,7 +3973,7 @@ int set_lwp_class_and_priority(int ThreadID, int lwpid, memset(&ReadBack, 0, sizeof(pcparms_t)); ReadBack.pc_cid = PC_CLNULL; - rslt = (*priocntl_ptr)(PC_VERSION, P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack); + rslt = priocntl(P_LWPID, lwpid, PC_GETPARMS, (caddr_t)&ReadBack); assert(rslt >= 0, "priocntl failed"); Actual = Expected = 0xBAD; assert(ParmInfo.pc_cid == ReadBack.pc_cid, "cid's don't match"); @@ -5244,11 +5065,6 @@ uint_t os::Solaris::getisax(uint32_t* array, uint_t n) { return _getisax(array, n); } -// Symbol doesn't exist in Solaris 8 pset.h -#ifndef PS_MYID -#define PS_MYID -3 -#endif - // int pset_getloadavg(psetid_t pset, double loadavg[], int nelem); typedef long (*pset_getloadavg_type)(psetid_t pset, double loadavg[], int nelem); static pset_getloadavg_type pset_getloadavg_ptr = NULL; @@ -5418,20 +5234,6 @@ jint os::init_2(void) { UseNUMA = false; } } - // ISM is not compatible with the NUMA allocator - it always allocates - // pages round-robin across the lgroups. - if (UseNUMA && UseLargePages && UseISM) { - if (!FLAG_IS_DEFAULT(UseNUMA)) { - if (FLAG_IS_DEFAULT(UseLargePages) && FLAG_IS_DEFAULT(UseISM)) { - UseLargePages = false; - } else { - warning("UseNUMA is not compatible with ISM large pages, disabling NUMA allocator"); - UseNUMA = false; - } - } else { - UseNUMA = false; - } - } if (!UseNUMA && ForceNUMA) { UseNUMA = true; } @@ -6077,24 +5879,20 @@ int os::loadavg(double loadavg[], int nelem) { bool os::find(address addr, outputStream* st) { Dl_info dlinfo; memset(&dlinfo, 0, sizeof(dlinfo)); - if (dladdr(addr, &dlinfo)) { -#ifdef _LP64 - st->print("0x%016lx: ", addr); -#else - st->print("0x%08x: ", addr); -#endif - if (dlinfo.dli_sname != NULL) + if (dladdr(addr, &dlinfo) != 0) { + st->print(PTR_FORMAT ": ", addr); + if (dlinfo.dli_sname != NULL && dlinfo.dli_saddr != NULL) { st->print("%s+%#lx", dlinfo.dli_sname, addr-(intptr_t)dlinfo.dli_saddr); - else if (dlinfo.dli_fname) + } else if (dlinfo.dli_fbase != NULL) st->print("", addr-(intptr_t)dlinfo.dli_fbase); else st->print(""); - if (dlinfo.dli_fname) st->print(" in %s", dlinfo.dli_fname); -#ifdef _LP64 - if (dlinfo.dli_fbase) st->print(" at 0x%016lx", dlinfo.dli_fbase); -#else - if (dlinfo.dli_fbase) st->print(" at 0x%08x", dlinfo.dli_fbase); -#endif + if (dlinfo.dli_fname != NULL) { + st->print(" in %s", dlinfo.dli_fname); + } + if (dlinfo.dli_fbase != NULL) { + st->print(" at " PTR_FORMAT, dlinfo.dli_fbase); + } st->cr(); if (Verbose) { @@ -6105,7 +5903,7 @@ bool os::find(address addr, outputStream* st) { if (!lowest) lowest = (address) dlinfo.dli_fbase; if (begin < lowest) begin = lowest; Dl_info dlinfo2; - if (dladdr(end, &dlinfo2) && dlinfo2.dli_saddr != dlinfo.dli_saddr + if (dladdr(end, &dlinfo2) != 0 && dlinfo2.dli_saddr != dlinfo.dli_saddr && end > dlinfo2.dli_saddr && dlinfo2.dli_saddr > begin) end = (address) dlinfo2.dli_saddr; Disassembler::decode(begin, end, st); diff --git a/hotspot/src/os/solaris/vm/os_solaris.hpp b/hotspot/src/os/solaris/vm/os_solaris.hpp index f7f0a3d7283..330d4fbc591 100644 --- a/hotspot/src/os/solaris/vm/os_solaris.hpp +++ b/hotspot/src/os/solaris/vm/os_solaris.hpp @@ -106,8 +106,8 @@ class Solaris { static meminfo_func_t _meminfo; - // Large Page Support--mpss. - static bool set_mpss_range(caddr_t start, size_t bytes, size_t align); + // Large Page Support + static bool setup_large_pages(caddr_t start, size_t bytes, size_t align); static void init_thread_fpu_state(void); @@ -174,7 +174,6 @@ class Solaris { static char* mmap_chunk(char *addr, size_t size, int flags, int prot); static char* anon_mmap(char* requested_addr, size_t bytes, size_t alignment_hint, bool fixed); static bool mpss_sanity_check(bool warn, size_t * page_size); - static bool ism_sanity_check (bool warn, size_t * page_size); // Workaround for 4352906. thr_stksegment sometimes returns // a bad value for the primordial thread's stack base when diff --git a/hotspot/src/os/windows/vm/attachListener_windows.cpp b/hotspot/src/os/windows/vm/attachListener_windows.cpp index 1d5857f1c2f..34a454f6363 100644 --- a/hotspot/src/os/windows/vm/attachListener_windows.cpp +++ b/hotspot/src/os/windows/vm/attachListener_windows.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -358,6 +358,10 @@ AttachOperation* AttachListener::dequeue() { return op; } +void AttachListener::vm_start() { + // nothing to do +} + int AttachListener::pd_init() { return Win32AttachListener::init(); } diff --git a/hotspot/src/os/windows/vm/os_windows.cpp b/hotspot/src/os/windows/vm/os_windows.cpp index cc43934d423..3b44d9a220f 100644 --- a/hotspot/src/os/windows/vm/os_windows.cpp +++ b/hotspot/src/os/windows/vm/os_windows.cpp @@ -1420,34 +1420,40 @@ static int _locate_module_by_addr(int pid, char * mod_fname, address base_addr, bool os::dll_address_to_library_name(address addr, char* buf, int buflen, int* offset) { + // buf is not optional, but offset is optional + assert(buf != NULL, "sanity check"); + // NOTE: the reason we don't use SymGetModuleInfo() is it doesn't always // return the full path to the DLL file, sometimes it returns path // to the corresponding PDB file (debug info); sometimes it only // returns partial path, which makes life painful. - struct _modinfo mi; - mi.addr = addr; - mi.full_path = buf; - mi.buflen = buflen; - int pid = os::current_process_id(); - if (enumerate_modules(pid, _locate_module_by_addr, (void *)&mi)) { - // buf already contains path name - if (offset) *offset = addr - mi.base_addr; - return true; - } else { - if (buf) buf[0] = '\0'; - if (offset) *offset = -1; - return false; - } + struct _modinfo mi; + mi.addr = addr; + mi.full_path = buf; + mi.buflen = buflen; + int pid = os::current_process_id(); + if (enumerate_modules(pid, _locate_module_by_addr, (void *)&mi)) { + // buf already contains path name + if (offset) *offset = addr - mi.base_addr; + return true; + } + + buf[0] = '\0'; + if (offset) *offset = -1; + return false; } bool os::dll_address_to_function_name(address addr, char *buf, int buflen, int *offset) { + // buf is not optional, but offset is optional + assert(buf != NULL, "sanity check"); + if (Decoder::decode(addr, buf, buflen, offset)) { return true; } if (offset != NULL) *offset = -1; - if (buf != NULL) buf[0] = '\0'; + buf[0] = '\0'; return false; } @@ -2317,6 +2323,11 @@ LONG WINAPI topLevelExceptionFilter(struct _EXCEPTION_POINTERS* exceptionInfo) { #endif Thread* t = ThreadLocalStorage::get_thread_slow(); // slow & steady + // Handle SafeFetch32 and SafeFetchN exceptions. + if (StubRoutines::is_safefetch_fault(pc)) { + return Handle_Exception(exceptionInfo, StubRoutines::continuation_for_safefetch_fault(pc)); + } + #ifndef _WIN64 // Execution protection violation - win32 running on AMD64 only // Handled first to avoid misdiagnosis as a "normal" access violation; @@ -2689,6 +2700,19 @@ address os::win32::fast_jni_accessor_wrapper(BasicType type) { } #endif +#ifndef PRODUCT +void os::win32::call_test_func_with_wrapper(void (*funcPtr)(void)) { + // Install a win32 structured exception handler around the test + // function call so the VM can generate an error dump if needed. + __try { + (*funcPtr)(); + } __except(topLevelExceptionFilter( + (_EXCEPTION_POINTERS*)_exception_info())) { + // Nothing to do. + } +} +#endif + // Virtual Memory int os::vm_page_size() { return os::win32::vm_page_size(); } @@ -4665,6 +4689,34 @@ void os::pause() { } } +os::WatcherThreadCrashProtection::WatcherThreadCrashProtection() { + assert(Thread::current()->is_Watcher_thread(), "Must be WatcherThread"); +} + +/* + * See the caveats for this class in os_windows.hpp + * Protects the callback call so that raised OS EXCEPTIONS causes a jump back + * into this method and returns false. If no OS EXCEPTION was raised, returns + * true. + * The callback is supposed to provide the method that should be protected. + */ +bool os::WatcherThreadCrashProtection::call(os::CrashProtectionCallback& cb) { + assert(Thread::current()->is_Watcher_thread(), "Only for WatcherThread"); + assert(!WatcherThread::watcher_thread()->has_crash_protection(), + "crash_protection already set?"); + + bool success = true; + __try { + WatcherThread::watcher_thread()->set_crash_protection(this); + cb.call(); + } __except(EXCEPTION_EXECUTE_HANDLER) { + // only for protection, nothing to do + success = false; + } + WatcherThread::watcher_thread()->set_crash_protection(NULL); + return success; +} + // An Event wraps a win32 "CreateEvent" kernel handle. // // We have a number of choices regarding "CreateEvent" win32 handle leakage: diff --git a/hotspot/src/os/windows/vm/os_windows.hpp b/hotspot/src/os/windows/vm/os_windows.hpp index f3196af9afc..67ed8a4af7c 100644 --- a/hotspot/src/os/windows/vm/os_windows.hpp +++ b/hotspot/src/os/windows/vm/os_windows.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -94,10 +94,28 @@ class win32 { static address fast_jni_accessor_wrapper(BasicType); #endif +#ifndef PRODUCT + static void call_test_func_with_wrapper(void (*funcPtr)(void)); +#endif + // filter function to ignore faults on serializations page static LONG WINAPI serialize_fault_filter(struct _EXCEPTION_POINTERS* e); }; +/* + * Crash protection for the watcher thread. Wrap the callback + * with a __try { call() } + * To be able to use this - don't take locks, don't rely on destructors, + * don't make OS library calls, don't allocate memory, don't print, + * don't call code that could leave the heap / memory in an inconsistent state, + * or anything else where we are not in control if we suddenly jump out. + */ +class WatcherThreadCrashProtection : public StackObj { +public: + WatcherThreadCrashProtection(); + bool call(os::CrashProtectionCallback& cb); +}; + class PlatformEvent : public CHeapObj { private: double CachePad [4] ; // increase odds that _Event is sole occupant of cache line diff --git a/hotspot/src/os/windows/vm/os_windows.inline.hpp b/hotspot/src/os/windows/vm/os_windows.inline.hpp index 5b1c46dfc59..5303743aee4 100644 --- a/hotspot/src/os/windows/vm/os_windows.inline.hpp +++ b/hotspot/src/os/windows/vm/os_windows.inline.hpp @@ -106,4 +106,10 @@ inline size_t os::write(int fd, const void *buf, unsigned int nBytes) { inline int os::close(int fd) { return ::close(fd); } + +#ifndef PRODUCT + #define CALL_TEST_FUNC_WITH_WRAPPER_IF_NEEDED(f) \ + os::win32::call_test_func_with_wrapper(f) +#endif + #endif // OS_WINDOWS_VM_OS_WINDOWS_INLINE_HPP diff --git a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s index 402c8da11a6..3275996f0c7 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s +++ b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_32.s @@ -63,24 +63,6 @@ SYMBOL(fixcw): popl %eax ret - .globl SYMBOL(SafeFetch32), SYMBOL(Fetch32PFI), SYMBOL(Fetch32Resume) - .globl SYMBOL(SafeFetchN) - ## TODO: avoid exposing Fetch32PFI and Fetch32Resume. - ## Instead, the signal handler would call a new SafeFetchTriage(FaultingEIP) - ## routine to vet the address. If the address is the faulting LD then - ## SafeFetchTriage() would return the resume-at EIP, otherwise null. - ELF_TYPE(SafeFetch32,@function) - .p2align 4,,15 -SYMBOL(SafeFetch32): -SYMBOL(SafeFetchN): - movl 0x8(%esp), %eax - movl 0x4(%esp), %ecx -SYMBOL(Fetch32PFI): - movl (%ecx), %eax -SYMBOL(Fetch32Resume): - ret - - .globl SYMBOL(SpinPause) ELF_TYPE(SpinPause,@function) .p2align 4,,15 diff --git a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s index 65d2db45f70..2f70fce77a3 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s +++ b/hotspot/src/os_cpu/bsd_x86/vm/bsd_x86_64.s @@ -46,28 +46,6 @@ .text - .globl SYMBOL(SafeFetch32), SYMBOL(Fetch32PFI), SYMBOL(Fetch32Resume) - .p2align 4,,15 - ELF_TYPE(SafeFetch32,@function) - // Prototype: int SafeFetch32 (int * Adr, int ErrValue) -SYMBOL(SafeFetch32): - movl %esi, %eax -SYMBOL(Fetch32PFI): - movl (%rdi), %eax -SYMBOL(Fetch32Resume): - ret - - .globl SYMBOL(SafeFetchN), SYMBOL(FetchNPFI), SYMBOL(FetchNResume) - .p2align 4,,15 - ELF_TYPE(SafeFetchN,@function) - // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) -SYMBOL(SafeFetchN): - movq %rsi, %rax -SYMBOL(FetchNPFI): - movq (%rdi), %rax -SYMBOL(FetchNResume): - ret - .globl SYMBOL(SpinPause) .p2align 4,,15 ELF_TYPE(SpinPause,@function) diff --git a/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp b/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp index 0ac6d3093f8..8cb9d4a1451 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp +++ b/hotspot/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp @@ -72,7 +72,7 @@ inline jushort OrderAccess::load_acquire(volatile jushort* p) { return *p; } inline juint OrderAccess::load_acquire(volatile juint* p) { return *p; } inline julong OrderAccess::load_acquire(volatile julong* p) { return Atomic::load((volatile jlong*)p); } inline jfloat OrderAccess::load_acquire(volatile jfloat* p) { return *p; } -inline jdouble OrderAccess::load_acquire(volatile jdouble* p) { return *p; } +inline jdouble OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); } inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t* p) { return *p; } inline void* OrderAccess::load_ptr_acquire(volatile void* p) { return *(void* volatile *)p; } @@ -87,7 +87,7 @@ inline void OrderAccess::release_store(volatile jushort* p, jushort v) { *p inline void OrderAccess::release_store(volatile juint* p, juint v) { *p = v; } inline void OrderAccess::release_store(volatile julong* p, julong v) { Atomic::store((jlong)v, (volatile jlong*)p); } inline void OrderAccess::release_store(volatile jfloat* p, jfloat v) { *p = v; } -inline void OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; } +inline void OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); } inline void OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; } inline void OrderAccess::release_store_ptr(volatile void* p, void* v) { *(void* volatile *)p = v; } @@ -190,7 +190,7 @@ inline void OrderAccess::release_store_fence(volatile juint* p, juint v) inline void OrderAccess::release_store_fence(volatile julong* p, julong v) { release_store_fence((volatile jlong*)p, (jlong)v); } inline void OrderAccess::release_store_fence(volatile jfloat* p, jfloat v) { *p = v; fence(); } -inline void OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); } +inline void OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jdouble_cast(v)); } inline void OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) { #ifdef AMD64 diff --git a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp index aa36599ea2a..24f364e985f 100644 --- a/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp +++ b/hotspot/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp @@ -385,13 +385,6 @@ enum { trap_page_fault = 0xE }; -extern "C" void Fetch32PFI () ; -extern "C" void Fetch32Resume () ; -#ifdef AMD64 -extern "C" void FetchNPFI () ; -extern "C" void FetchNResume () ; -#endif // AMD64 - extern "C" JNIEXPORT int JVM_handle_bsd_signal(int sig, siginfo_t* info, @@ -401,6 +394,10 @@ JVM_handle_bsd_signal(int sig, Thread* t = ThreadLocalStorage::get_thread_slow(); + // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away + // (no destructors can be run) + os::WatcherThreadCrashProtection::check_crash_protection(sig, t); + SignalHandlerMark shm(t); // Note: it's not uncommon that JNI code uses signal/sigset to install @@ -454,16 +451,10 @@ JVM_handle_bsd_signal(int sig, if (info != NULL && uc != NULL && thread != NULL) { pc = (address) os::Bsd::ucontext_get_pc(uc); - if (pc == (address) Fetch32PFI) { - uc->context_pc = intptr_t(Fetch32Resume) ; - return 1 ; + if (StubRoutines::is_safefetch_fault(pc)) { + uc->context_pc = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); + return 1; } -#ifdef AMD64 - if (pc == (address) FetchNPFI) { - uc->context_pc = intptr_t (FetchNResume) ; - return 1 ; - } -#endif // AMD64 // Handle ALL stack overflow variations here if (sig == SIGSEGV || sig == SIGBUS) { diff --git a/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s b/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s index e04f871f49e..d7c2ce87414 100644 --- a/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s +++ b/hotspot/src/os_cpu/linux_sparc/vm/linux_sparc.s @@ -21,42 +21,6 @@ # questions. # - # Prototype: int SafeFetch32 (int * adr, int ErrValue) - # The "ld" at Fetch32 is potentially faulting instruction. - # If the instruction traps the trap handler will arrange - # for control to resume at Fetch32Resume. - # By convention with the trap handler we ensure there is a non-CTI - # instruction in the trap shadow. - - - .globl SafeFetch32, Fetch32PFI, Fetch32Resume - .globl SafeFetchN - .align 32 - .type SafeFetch32,@function -SafeFetch32: - mov %o0, %g1 - mov %o1, %o0 -Fetch32PFI: - # <-- Potentially faulting instruction - ld [%g1], %o0 -Fetch32Resume: - nop - retl - nop - - .globl SafeFetchN, FetchNPFI, FetchNResume - .type SafeFetchN,@function - .align 32 -SafeFetchN: - mov %o0, %g1 - mov %o1, %o0 -FetchNPFI: - ldn [%g1], %o0 -FetchNResume: - nop - retl - nop - # Possibilities: # -- membar # -- CAS (SP + BIAS, G0, G0) diff --git a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp index d97f0e041bf..e7879bee690 100644 --- a/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp +++ b/hotspot/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp @@ -366,18 +366,9 @@ intptr_t* os::Linux::ucontext_get_fp(ucontext_t *uc) { // Utility functions -extern "C" void Fetch32PFI(); -extern "C" void Fetch32Resume(); -extern "C" void FetchNPFI(); -extern "C" void FetchNResume(); - inline static bool checkPrefetch(sigcontext* uc, address pc) { - if (pc == (address) Fetch32PFI) { - set_cont_address(uc, address(Fetch32Resume)); - return true; - } - if (pc == (address) FetchNPFI) { - set_cont_address(uc, address(FetchNResume)); + if (StubRoutines::is_safefetch_fault(pc)) { + set_cont_address(uc, address(StubRoutines::continuation_for_safefetch_fault(pc))); return true; } return false; @@ -553,6 +544,10 @@ JVM_handle_linux_signal(int sig, Thread* t = ThreadLocalStorage::get_thread_slow(); + // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away + // (no destructors can be run) + os::WatcherThreadCrashProtection::check_crash_protection(sig, t); + SignalHandlerMark shm(t); // Note: it's not uncommon that JNI code uses signal/sigset to install diff --git a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s index d29d31df464..7936cbf52bd 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s +++ b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_32.s @@ -42,24 +42,6 @@ .text - .globl SafeFetch32, Fetch32PFI, Fetch32Resume - .globl SafeFetchN - ## TODO: avoid exposing Fetch32PFI and Fetch32Resume. - ## Instead, the signal handler would call a new SafeFetchTriage(FaultingEIP) - ## routine to vet the address. If the address is the faulting LD then - ## SafeFetchTriage() would return the resume-at EIP, otherwise null. - .type SafeFetch32,@function - .p2align 4,,15 -SafeFetch32: -SafeFetchN: - movl 0x8(%esp), %eax - movl 0x4(%esp), %ecx -Fetch32PFI: - movl (%ecx), %eax -Fetch32Resume: - ret - - .globl SpinPause .type SpinPause,@function .p2align 4,,15 diff --git a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s index 8be68610e80..fb688e7a7b6 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s +++ b/hotspot/src/os_cpu/linux_x86/vm/linux_x86_64.s @@ -38,28 +38,6 @@ .text - .globl SafeFetch32, Fetch32PFI, Fetch32Resume - .align 16 - .type SafeFetch32,@function - // Prototype: int SafeFetch32 (int * Adr, int ErrValue) -SafeFetch32: - movl %esi, %eax -Fetch32PFI: - movl (%rdi), %eax -Fetch32Resume: - ret - - .globl SafeFetchN, FetchNPFI, FetchNResume - .align 16 - .type SafeFetchN,@function - // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) -SafeFetchN: - movq %rsi, %rax -FetchNPFI: - movq (%rdi), %rax -FetchNResume: - ret - .globl SpinPause .align 16 .type SpinPause,@function diff --git a/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp b/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp index 7a9fd1a4413..10240a0b1c2 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp +++ b/hotspot/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp @@ -72,7 +72,7 @@ inline jushort OrderAccess::load_acquire(volatile jushort* p) { return *p; } inline juint OrderAccess::load_acquire(volatile juint* p) { return *p; } inline julong OrderAccess::load_acquire(volatile julong* p) { return Atomic::load((volatile jlong*)p); } inline jfloat OrderAccess::load_acquire(volatile jfloat* p) { return *p; } -inline jdouble OrderAccess::load_acquire(volatile jdouble* p) { return *p; } +inline jdouble OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); } inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t* p) { return *p; } inline void* OrderAccess::load_ptr_acquire(volatile void* p) { return *(void* volatile *)p; } @@ -87,7 +87,7 @@ inline void OrderAccess::release_store(volatile jushort* p, jushort v) { *p inline void OrderAccess::release_store(volatile juint* p, juint v) { *p = v; } inline void OrderAccess::release_store(volatile julong* p, julong v) { Atomic::store((jlong)v, (volatile jlong*)p); } inline void OrderAccess::release_store(volatile jfloat* p, jfloat v) { *p = v; } -inline void OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; } +inline void OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong *)p, jlong_cast(v)); } inline void OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; } inline void OrderAccess::release_store_ptr(volatile void* p, void* v) { *(void* volatile *)p = v; } @@ -129,7 +129,7 @@ inline void OrderAccess::store_fence(jushort* p, jushort v) { store_fence((j inline void OrderAccess::store_fence(juint* p, juint v) { store_fence((jint*)p, (jint)v); } inline void OrderAccess::store_fence(julong* p, julong v) { store_fence((jlong*)p, (jlong)v); } inline void OrderAccess::store_fence(jfloat* p, jfloat v) { *p = v; fence(); } -inline void OrderAccess::store_fence(jdouble* p, jdouble v) { *p = v; fence(); } +inline void OrderAccess::store_fence(jdouble* p, jdouble v) { store_fence((jlong*)p, jlong_cast(v)); } inline void OrderAccess::store_ptr_fence(intptr_t* p, intptr_t v) { #ifdef AMD64 @@ -190,7 +190,7 @@ inline void OrderAccess::release_store_fence(volatile juint* p, juint v) inline void OrderAccess::release_store_fence(volatile julong* p, julong v) { release_store_fence((volatile jlong*)p, (jlong)v); } inline void OrderAccess::release_store_fence(volatile jfloat* p, jfloat v) { *p = v; fence(); } -inline void OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); } +inline void OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); } inline void OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) { #ifdef AMD64 diff --git a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp index 4fc3b76d228..8878c0ea353 100644 --- a/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp +++ b/hotspot/src/os_cpu/linux_x86/vm/os_linux_x86.cpp @@ -209,13 +209,6 @@ enum { trap_page_fault = 0xE }; -extern "C" void Fetch32PFI () ; -extern "C" void Fetch32Resume () ; -#ifdef AMD64 -extern "C" void FetchNPFI () ; -extern "C" void FetchNResume () ; -#endif // AMD64 - extern "C" JNIEXPORT int JVM_handle_linux_signal(int sig, siginfo_t* info, @@ -225,6 +218,10 @@ JVM_handle_linux_signal(int sig, Thread* t = ThreadLocalStorage::get_thread_slow(); + // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away + // (no destructors can be run) + os::WatcherThreadCrashProtection::check_crash_protection(sig, t); + SignalHandlerMark shm(t); // Note: it's not uncommon that JNI code uses signal/sigset to install @@ -278,16 +275,10 @@ JVM_handle_linux_signal(int sig, if (info != NULL && uc != NULL && thread != NULL) { pc = (address) os::Linux::ucontext_get_pc(uc); - if (pc == (address) Fetch32PFI) { - uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ; - return 1 ; + if (StubRoutines::is_safefetch_fault(pc)) { + uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); + return 1; } -#ifdef AMD64 - if (pc == (address) FetchNPFI) { - uc->uc_mcontext.gregs[REG_PC] = intptr_t (FetchNResume) ; - return 1 ; - } -#endif // AMD64 #ifndef AMD64 // Halt if SI_KERNEL before more crashes get misdiagnosed as Java bugs diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp index 939def32fec..d8c08fd4a63 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp +++ b/hotspot/src/os_cpu/solaris_sparc/vm/os_solaris_sparc.cpp @@ -303,11 +303,6 @@ bool os::is_allocatable(size_t bytes) { #endif } -extern "C" void Fetch32PFI () ; -extern "C" void Fetch32Resume () ; -extern "C" void FetchNPFI () ; -extern "C" void FetchNResume () ; - extern "C" JNIEXPORT int JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, int abort_if_unrecognized) { @@ -315,6 +310,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, Thread* t = ThreadLocalStorage::get_thread_slow(); + // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away + // (no destructors can be run) + os::WatcherThreadCrashProtection::check_crash_protection(sig, t); + SignalHandlerMark shm(t); if(sig == SIGPIPE || sig == SIGXFSZ) { @@ -379,17 +378,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, npc = (address) uc->uc_mcontext.gregs[REG_nPC]; // SafeFetch() support - // Implemented with either a fixed set of addresses such - // as Fetch32*, or with Thread._OnTrap. - if (uc->uc_mcontext.gregs[REG_PC] == intptr_t(Fetch32PFI)) { - uc->uc_mcontext.gregs [REG_PC] = intptr_t(Fetch32Resume) ; - uc->uc_mcontext.gregs [REG_nPC] = intptr_t(Fetch32Resume) + 4 ; - return true ; - } - if (uc->uc_mcontext.gregs[REG_PC] == intptr_t(FetchNPFI)) { - uc->uc_mcontext.gregs [REG_PC] = intptr_t(FetchNResume) ; - uc->uc_mcontext.gregs [REG_nPC] = intptr_t(FetchNResume) + 4 ; - return true ; + if (StubRoutines::is_safefetch_fault(pc)) { + uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); + uc->uc_mcontext.gregs[REG_nPC] = uc->uc_mcontext.gregs[REG_PC] + 4; + return 1; } // Handle ALL stack overflow variations here diff --git a/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s b/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s index aa526a09d08..39aaa77f664 100644 --- a/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s +++ b/hotspot/src/os_cpu/solaris_sparc/vm/solaris_sparc.s @@ -21,47 +21,6 @@ !! questions. !! - !! Prototype: int SafeFetch32 (int * adr, int ErrValue) - !! The "ld" at Fetch32 is potentially faulting instruction. - !! If the instruction traps the trap handler will arrange - !! for control to resume at Fetch32Resume. - !! By convention with the trap handler we ensure there is a non-CTI - !! instruction in the trap shadow. - !! - !! The reader might be tempted to move this service to .il. - !! Don't. Sun's CC back-end reads and optimize code emitted - !! by the .il "call", in some cases optimizing the code, completely eliding it, - !! or by moving the code from the "call site". - - !! ASM better know we may use G6 for our own purposes - .register %g6, #ignore - - .globl SafeFetch32 - .align 32 - .global Fetch32PFI, Fetch32Resume -SafeFetch32: - mov %o0, %g1 - mov %o1, %o0 -Fetch32PFI: - ld [%g1], %o0 !! <-- Potentially faulting instruction -Fetch32Resume: - nop - retl - nop - - .globl SafeFetchN - .align 32 - .globl FetchNPFI, FetchNResume -SafeFetchN: - mov %o0, %g1 - mov %o1, %o0 -FetchNPFI: - ldn [%g1], %o0 -FetchNResume: - nop - retl - nop - !! Possibilities: !! -- membar !! -- CAS (SP + BIAS, G0, G0) diff --git a/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp b/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp index c02d98ed991..e7238c27549 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp +++ b/hotspot/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp @@ -88,7 +88,7 @@ inline jushort OrderAccess::load_acquire(volatile jushort* p) { return *p; } inline juint OrderAccess::load_acquire(volatile juint* p) { return *p; } inline julong OrderAccess::load_acquire(volatile julong* p) { return Atomic::load((volatile jlong*)p); } inline jfloat OrderAccess::load_acquire(volatile jfloat* p) { return *p; } -inline jdouble OrderAccess::load_acquire(volatile jdouble* p) { return *p; } +inline jdouble OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); } inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t* p) { return *p; } inline void* OrderAccess::load_ptr_acquire(volatile void* p) { return *(void* volatile *)p; } @@ -103,7 +103,7 @@ inline void OrderAccess::release_store(volatile jushort* p, jushort v) { *p inline void OrderAccess::release_store(volatile juint* p, juint v) { *p = v; } inline void OrderAccess::release_store(volatile julong* p, julong v) { Atomic::store((jlong)v, (volatile jlong*)p); } inline void OrderAccess::release_store(volatile jfloat* p, jfloat v) { *p = v; } -inline void OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; } +inline void OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); } inline void OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; } inline void OrderAccess::release_store_ptr(volatile void* p, void* v) { *(void* volatile *)p = v; } @@ -129,9 +129,9 @@ inline void OrderAccess::release_store_fence(volatile jlong* p, jlong v) inline void OrderAccess::release_store_fence(volatile jubyte* p, jubyte v) { *p = v; fence(); } inline void OrderAccess::release_store_fence(volatile jushort* p, jushort v) { *p = v; fence(); } inline void OrderAccess::release_store_fence(volatile juint* p, juint v) { *p = v; fence(); } -inline void OrderAccess::release_store_fence(volatile julong* p, julong v) { release_store(p, v); fence(); } +inline void OrderAccess::release_store_fence(volatile julong* p, julong v) { release_store((jlong *)p, (jlong)v); fence(); } inline void OrderAccess::release_store_fence(volatile jfloat* p, jfloat v) { *p = v; fence(); } -inline void OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); } +inline void OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); } inline void OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) { *p = v; fence(); } inline void OrderAccess::release_store_ptr_fence(volatile void* p, void* v) { *(void* volatile *)p = v; fence(); } diff --git a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp index 4ed094db734..eb8cbe81918 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp +++ b/hotspot/src/os_cpu/solaris_x86/vm/os_solaris_x86.cpp @@ -352,13 +352,6 @@ bool os::is_allocatable(size_t bytes) { } -extern "C" void Fetch32PFI () ; -extern "C" void Fetch32Resume () ; -#ifdef AMD64 -extern "C" void FetchNPFI () ; -extern "C" void FetchNResume () ; -#endif // AMD64 - extern "C" JNIEXPORT int JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, int abort_if_unrecognized) { @@ -374,6 +367,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, Thread* t = ThreadLocalStorage::get_thread_slow(); // slow & steady + // Must do this before SignalHandlerMark, if crash protection installed we will longjmp away + // (no destructors can be run) + os::WatcherThreadCrashProtection::check_crash_protection(sig, t); + SignalHandlerMark shm(t); if(sig == SIGPIPE || sig == SIGXFSZ) { @@ -436,17 +433,10 @@ JVM_handle_solaris_signal(int sig, siginfo_t* info, void* ucVoid, // factor me: getPCfromContext pc = (address) uc->uc_mcontext.gregs[REG_PC]; - // SafeFetch32() support - if (pc == (address) Fetch32PFI) { - uc->uc_mcontext.gregs[REG_PC] = intptr_t(Fetch32Resume) ; - return true ; + if (StubRoutines::is_safefetch_fault(pc)) { + uc->uc_mcontext.gregs[REG_PC] = intptr_t(StubRoutines::continuation_for_safefetch_fault(pc)); + return true; } -#ifdef AMD64 - if (pc == (address) FetchNPFI) { - uc->uc_mcontext.gregs [REG_PC] = intptr_t(FetchNResume) ; - return true ; - } -#endif // AMD64 // Handle ALL stack overflow variations here if (sig == SIGSEGV && info->si_code == SEGV_ACCERR) { diff --git a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s index 1fac3b25f11..19e790b6013 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s +++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_32.s @@ -54,20 +54,6 @@ fixcw: popl %eax ret - .align 16 - .globl SafeFetch32 - .globl SafeFetchN - .globl Fetch32PFI, Fetch32Resume -SafeFetch32: -SafeFetchN: - movl 0x8(%esp), %eax - movl 0x4(%esp), %ecx -Fetch32PFI: - movl (%ecx), %eax -Fetch32Resume: - ret - - .align 16 .globl SpinPause SpinPause: diff --git a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s index 95050af24f0..487b569e58c 100644 --- a/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s +++ b/hotspot/src/os_cpu/solaris_x86/vm/solaris_x86_64.s @@ -21,54 +21,34 @@ / questions. / - .globl fs_load - .globl fs_thread + .globl fs_load + .globl fs_thread // NOTE WELL! The _Copy functions are called directly - // from server-compiler-generated code via CallLeafNoFP, - // which means that they *must* either not use floating - // point or use it in the same manner as does the server - // compiler. + // from server-compiler-generated code via CallLeafNoFP, + // which means that they *must* either not use floating + // point or use it in the same manner as does the server + // compiler. .globl _Copy_arrayof_conjoint_bytes .globl _Copy_conjoint_jshorts_atomic - .globl _Copy_arrayof_conjoint_jshorts + .globl _Copy_arrayof_conjoint_jshorts .globl _Copy_conjoint_jints_atomic .globl _Copy_arrayof_conjoint_jints - .globl _Copy_conjoint_jlongs_atomic + .globl _Copy_conjoint_jlongs_atomic .globl _Copy_arrayof_conjoint_jlongs - .section .text,"ax" + .section .text,"ax" / Fast thread accessors, used by threadLS_solaris_amd64.cpp - .align 16 + .align 16 fs_load: - movq %fs:(%rdi),%rax - ret - - .align 16 -fs_thread: - movq %fs:0x0,%rax - ret - - .globl SafeFetch32, Fetch32PFI, Fetch32Resume - .align 16 - // Prototype: int SafeFetch32 (int * Adr, int ErrValue) -SafeFetch32: - movl %esi, %eax -Fetch32PFI: - movl (%rdi), %eax -Fetch32Resume: + movq %fs:(%rdi),%rax ret - .globl SafeFetchN, FetchNPFI, FetchNResume - .align 16 - // Prototype: intptr_t SafeFetchN (intptr_t * Adr, intptr_t ErrValue) -SafeFetchN: - movq %rsi, %rax -FetchNPFI: - movq (%rdi), %rax -FetchNResume: + .align 16 +fs_thread: + movq %fs:0x0,%rax ret .globl SpinPause @@ -78,7 +58,7 @@ SpinPause: nop movq $1, %rax ret - + / Support for void Copy::arrayof_conjoint_bytes(void* from, / void* to, @@ -340,7 +320,7 @@ aci_CopyLeft: addq $4,%rdx jg 1b ret - + / Support for void Copy::arrayof_conjoint_jlongs(jlong* from, / jlong* to, / size_t count) diff --git a/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp b/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp index 639b8ad9d9d..ea0ed143e98 100644 --- a/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp +++ b/hotspot/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp @@ -71,7 +71,7 @@ inline jushort OrderAccess::load_acquire(volatile jushort* p) { return *p; } inline juint OrderAccess::load_acquire(volatile juint* p) { return *p; } inline julong OrderAccess::load_acquire(volatile julong* p) { return Atomic::load((volatile jlong*)p); } inline jfloat OrderAccess::load_acquire(volatile jfloat* p) { return *p; } -inline jdouble OrderAccess::load_acquire(volatile jdouble* p) { return *p; } +inline jdouble OrderAccess::load_acquire(volatile jdouble* p) { return jdouble_cast(Atomic::load((volatile jlong*)p)); } inline intptr_t OrderAccess::load_ptr_acquire(volatile intptr_t* p) { return *p; } inline void* OrderAccess::load_ptr_acquire(volatile void* p) { return *(void* volatile *)p; } @@ -86,7 +86,7 @@ inline void OrderAccess::release_store(volatile jushort* p, jushort v) { *p inline void OrderAccess::release_store(volatile juint* p, juint v) { *p = v; } inline void OrderAccess::release_store(volatile julong* p, julong v) { Atomic::store((jlong)v, (volatile jlong*)p); } inline void OrderAccess::release_store(volatile jfloat* p, jfloat v) { *p = v; } -inline void OrderAccess::release_store(volatile jdouble* p, jdouble v) { *p = v; } +inline void OrderAccess::release_store(volatile jdouble* p, jdouble v) { release_store((volatile jlong*)p, jlong_cast(v)); } inline void OrderAccess::release_store_ptr(volatile intptr_t* p, intptr_t v) { *p = v; } inline void OrderAccess::release_store_ptr(volatile void* p, void* v) { *(void* volatile *)p = v; } @@ -195,7 +195,7 @@ inline void OrderAccess::release_store_fence(volatile jushort* p, jushort v) inline void OrderAccess::release_store_fence(volatile juint* p, juint v) { release_store_fence((volatile jint*)p, (jint)v); } inline void OrderAccess::release_store_fence(volatile julong* p, julong v) { release_store_fence((volatile jlong*)p, (jlong)v); } inline void OrderAccess::release_store_fence(volatile jfloat* p, jfloat v) { *p = v; fence(); } -inline void OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { *p = v; fence(); } +inline void OrderAccess::release_store_fence(volatile jdouble* p, jdouble v) { release_store_fence((volatile jlong*)p, jlong_cast(v)); } inline void OrderAccess::release_store_ptr_fence(volatile intptr_t* p, intptr_t v) { #ifdef AMD64 diff --git a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp index 1ef29f99a55..a0f2a7680be 100644 --- a/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp +++ b/hotspot/src/os_cpu/windows_x86/vm/os_windows_x86.cpp @@ -518,24 +518,6 @@ void os::print_register_info(outputStream *st, void *context) { st->cr(); } -extern "C" int SafeFetch32 (int * adr, int Err) { - int rv = Err ; - _try { - rv = *((volatile int *) adr) ; - } __except(EXCEPTION_EXECUTE_HANDLER) { - } - return rv ; -} - -extern "C" intptr_t SafeFetchN (intptr_t * adr, intptr_t Err) { - intptr_t rv = Err ; - _try { - rv = *((volatile intptr_t *) adr) ; - } __except(EXCEPTION_EXECUTE_HANDLER) { - } - return rv ; -} - extern "C" int SpinPause () { #ifdef AMD64 return 0 ; diff --git a/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp b/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp index 00b9b6c305d..f4ea83debf4 100644 --- a/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp +++ b/hotspot/src/os_cpu/windows_x86/vm/unwind_windows_x86.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2004, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2004, 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 @@ -29,10 +29,15 @@ #ifdef AMD64 typedef unsigned char UBYTE; +#if _MSC_VER < 1700 + +/* Not needed for VS2012 compiler, comes from winnt.h. */ #define UNW_FLAG_EHANDLER 0x01 #define UNW_FLAG_UHANDLER 0x02 #define UNW_FLAG_CHAININFO 0x04 +#endif + // This structure is used to define an UNWIND_INFO that // only has an ExceptionHandler. There are no UnwindCodes // declared. @@ -59,6 +64,9 @@ typedef struct _RUNTIME_FUNCTION { } RUNTIME_FUNCTION, *PRUNTIME_FUNCTION; */ +#if _MSC_VER < 1700 + +/* Not needed for VS2012 compiler, comes from winnt.h. */ typedef struct _DISPATCHER_CONTEXT { ULONG64 ControlPc; ULONG64 ImageBase; @@ -71,6 +79,8 @@ typedef struct _DISPATCHER_CONTEXT { PVOID HandlerData; } DISPATCHER_CONTEXT, *PDISPATCHER_CONTEXT; +#endif + #if _MSC_VER < 1500 /* Not needed for VS2008 compiler, comes from winnt.h. */ diff --git a/hotspot/src/share/vm/adlc/forms.hpp b/hotspot/src/share/vm/adlc/forms.hpp index a682e65a36f..63e367dd730 100644 --- a/hotspot/src/share/vm/adlc/forms.hpp +++ b/hotspot/src/share/vm/adlc/forms.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -146,7 +146,7 @@ public: // Public Methods Form(int formType=0, int line=0) : _next(NULL), _linenum(line), _ftype(formType) { }; - ~Form() {}; + virtual ~Form() {}; virtual bool ideal_only() const { assert(0,"Check of ideal status on non-instruction/operand form.\n"); diff --git a/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp b/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp index 8d7619eedd6..b84c8911e4c 100644 --- a/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp +++ b/hotspot/src/share/vm/c1/c1_GraphBuilder.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1999, 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 @@ -3461,6 +3461,14 @@ bool GraphBuilder::try_inline_intrinsics(ciMethod* callee) { preserves_state = true; break; + case vmIntrinsics::_updateCRC32: + case vmIntrinsics::_updateBytesCRC32: + case vmIntrinsics::_updateByteBufferCRC32: + if (!UseCRC32Intrinsics) return false; + cantrap = false; + preserves_state = true; + break; + case vmIntrinsics::_loadFence : case vmIntrinsics::_storeFence: case vmIntrinsics::_fullFence : diff --git a/hotspot/src/share/vm/c1/c1_LIR.cpp b/hotspot/src/share/vm/c1/c1_LIR.cpp index e2611534ea1..cb0ceab90c0 100644 --- a/hotspot/src/share/vm/c1/c1_LIR.cpp +++ b/hotspot/src/share/vm/c1/c1_LIR.cpp @@ -430,6 +430,11 @@ LIR_OpArrayCopy::LIR_OpArrayCopy(LIR_Opr src, LIR_Opr src_pos, LIR_Opr dst, LIR_ _stub = new ArrayCopyStub(this); } +LIR_OpUpdateCRC32::LIR_OpUpdateCRC32(LIR_Opr crc, LIR_Opr val, LIR_Opr res) + : LIR_Op(lir_updatecrc32, res, NULL) + , _crc(crc) + , _val(val) { +} //-------------------verify-------------------------- @@ -876,6 +881,20 @@ void LIR_OpVisitState::visit(LIR_Op* op) { } +// LIR_OpUpdateCRC32 + case lir_updatecrc32: { + assert(op->as_OpUpdateCRC32() != NULL, "must be"); + LIR_OpUpdateCRC32* opUp = (LIR_OpUpdateCRC32*)op; + + assert(opUp->_crc->is_valid(), "used"); do_input(opUp->_crc); do_temp(opUp->_crc); + assert(opUp->_val->is_valid(), "used"); do_input(opUp->_val); do_temp(opUp->_val); + assert(opUp->_result->is_valid(), "used"); do_output(opUp->_result); + assert(opUp->_info == NULL, "no info for LIR_OpUpdateCRC32"); + + break; + } + + // LIR_OpLock case lir_lock: case lir_unlock: { @@ -1056,6 +1075,10 @@ void LIR_OpArrayCopy::emit_code(LIR_Assembler* masm) { masm->emit_code_stub(stub()); } +void LIR_OpUpdateCRC32::emit_code(LIR_Assembler* masm) { + masm->emit_updatecrc32(this); +} + void LIR_Op0::emit_code(LIR_Assembler* masm) { masm->emit_op0(this); } @@ -1763,6 +1786,8 @@ const char * LIR_Op::name() const { case lir_dynamic_call: s = "dynamic"; break; // LIR_OpArrayCopy case lir_arraycopy: s = "arraycopy"; break; + // LIR_OpUpdateCRC32 + case lir_updatecrc32: s = "updatecrc32"; break; // LIR_OpLock case lir_lock: s = "lock"; break; case lir_unlock: s = "unlock"; break; @@ -1815,6 +1840,13 @@ void LIR_OpArrayCopy::print_instr(outputStream* out) const { tmp()->print(out); out->print(" "); } +// LIR_OpUpdateCRC32 +void LIR_OpUpdateCRC32::print_instr(outputStream* out) const { + crc()->print(out); out->print(" "); + val()->print(out); out->print(" "); + result_opr()->print(out); out->print(" "); +} + // LIR_OpCompareAndSwap void LIR_OpCompareAndSwap::print_instr(outputStream* out) const { addr()->print(out); out->print(" "); diff --git a/hotspot/src/share/vm/c1/c1_LIR.hpp b/hotspot/src/share/vm/c1/c1_LIR.hpp index 61dd59e3fe9..fab85e5750f 100644 --- a/hotspot/src/share/vm/c1/c1_LIR.hpp +++ b/hotspot/src/share/vm/c1/c1_LIR.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -877,6 +877,7 @@ class LIR_OpCall; class LIR_OpJavaCall; class LIR_OpRTCall; class LIR_OpArrayCopy; +class LIR_OpUpdateCRC32; class LIR_OpLock; class LIR_OpTypeCheck; class LIR_OpCompareAndSwap; @@ -982,6 +983,9 @@ enum LIR_Code { , begin_opArrayCopy , lir_arraycopy , end_opArrayCopy + , begin_opUpdateCRC32 + , lir_updatecrc32 + , end_opUpdateCRC32 , begin_opLock , lir_lock , lir_unlock @@ -1137,6 +1141,7 @@ class LIR_Op: public CompilationResourceObj { virtual LIR_Op2* as_Op2() { return NULL; } virtual LIR_Op3* as_Op3() { return NULL; } virtual LIR_OpArrayCopy* as_OpArrayCopy() { return NULL; } + virtual LIR_OpUpdateCRC32* as_OpUpdateCRC32() { return NULL; } virtual LIR_OpTypeCheck* as_OpTypeCheck() { return NULL; } virtual LIR_OpCompareAndSwap* as_OpCompareAndSwap() { return NULL; } virtual LIR_OpProfileCall* as_OpProfileCall() { return NULL; } @@ -1293,6 +1298,25 @@ public: void print_instr(outputStream* out) const PRODUCT_RETURN; }; +// LIR_OpUpdateCRC32 +class LIR_OpUpdateCRC32: public LIR_Op { + friend class LIR_OpVisitState; + +private: + LIR_Opr _crc; + LIR_Opr _val; + +public: + + LIR_OpUpdateCRC32(LIR_Opr crc, LIR_Opr val, LIR_Opr res); + + LIR_Opr crc() const { return _crc; } + LIR_Opr val() const { return _val; } + + virtual void emit_code(LIR_Assembler* masm); + virtual LIR_OpUpdateCRC32* as_OpUpdateCRC32() { return this; } + void print_instr(outputStream* out) const PRODUCT_RETURN; +}; // -------------------------------------------------- // LIR_Op0 @@ -2212,6 +2236,8 @@ class LIR_List: public CompilationResourceObj { void arraycopy(LIR_Opr src, LIR_Opr src_pos, LIR_Opr dst, LIR_Opr dst_pos, LIR_Opr length, LIR_Opr tmp, ciArrayKlass* expected_type, int flags, CodeEmitInfo* info) { append(new LIR_OpArrayCopy(src, src_pos, dst, dst_pos, length, tmp, expected_type, flags, info)); } + void update_crc32(LIR_Opr crc, LIR_Opr val, LIR_Opr res) { append(new LIR_OpUpdateCRC32(crc, val, res)); } + void fpop_raw() { append(new LIR_Op0(lir_fpop_raw)); } void instanceof(LIR_Opr result, LIR_Opr object, ciKlass* klass, LIR_Opr tmp1, LIR_Opr tmp2, LIR_Opr tmp3, bool fast_check, CodeEmitInfo* info_for_patch, ciMethod* profiled_method, int profiled_bci); diff --git a/hotspot/src/share/vm/c1/c1_LIRAssembler.hpp b/hotspot/src/share/vm/c1/c1_LIRAssembler.hpp index 87dd8dbae15..4ced297c07b 100644 --- a/hotspot/src/share/vm/c1/c1_LIRAssembler.hpp +++ b/hotspot/src/share/vm/c1/c1_LIRAssembler.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -195,6 +195,7 @@ class LIR_Assembler: public CompilationResourceObj { void emit_opBranch(LIR_OpBranch* op); void emit_opLabel(LIR_OpLabel* op); void emit_arraycopy(LIR_OpArrayCopy* op); + void emit_updatecrc32(LIR_OpUpdateCRC32* op); void emit_opConvert(LIR_OpConvert* op); void emit_alloc_obj(LIR_OpAllocObj* op); void emit_alloc_array(LIR_OpAllocArray* op); diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp index fcd6910ed95..3af2d23b7d6 100644 --- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp +++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp @@ -2994,6 +2994,12 @@ void LIRGenerator::do_Intrinsic(Intrinsic* x) { do_Reference_get(x); break; + case vmIntrinsics::_updateCRC32: + case vmIntrinsics::_updateBytesCRC32: + case vmIntrinsics::_updateByteBufferCRC32: + do_update_CRC32(x); + break; + default: ShouldNotReachHere(); break; } } diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.hpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.hpp index d3c76865dbd..0a029207308 100644 --- a/hotspot/src/share/vm/c1/c1_LIRGenerator.hpp +++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -247,6 +247,7 @@ class LIRGenerator: public InstructionVisitor, public BlockClosure { void do_NIOCheckIndex(Intrinsic* x); void do_FPIntrinsics(Intrinsic* x); void do_Reference_get(Intrinsic* x); + void do_update_CRC32(Intrinsic* x); void do_UnsafePrefetch(UnsafePrefetch* x, bool is_store); diff --git a/hotspot/src/share/vm/c1/c1_Runtime1.cpp b/hotspot/src/share/vm/c1/c1_Runtime1.cpp index 53d1f5326a8..908571f6cc4 100644 --- a/hotspot/src/share/vm/c1/c1_Runtime1.cpp +++ b/hotspot/src/share/vm/c1/c1_Runtime1.cpp @@ -299,6 +299,7 @@ const char* Runtime1::name_for_address(address entry) { #ifdef TRACE_HAVE_INTRINSICS FUNCTION_CASE(entry, TRACE_TIME_METHOD); #endif + FUNCTION_CASE(entry, StubRoutines::updateBytesCRC32()); #undef FUNCTION_CASE diff --git a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp index 32dc35d8059..e2fca4845b1 100644 --- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp +++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.cpp @@ -138,6 +138,16 @@ bool BCEscapeAnalyzer::is_arg_stack(ArgumentMap vars){ return false; } +// return true if all argument elements of vars are returned +bool BCEscapeAnalyzer::returns_all(ArgumentMap vars) { + for (int i = 0; i < _arg_size; i++) { + if (vars.contains(i) && !_arg_returned.test(i)) { + return false; + } + } + return true; +} + void BCEscapeAnalyzer::clear_bits(ArgumentMap vars, VectorSet &bm) { for (int i = 0; i < _arg_size; i++) { if (vars.contains(i)) { @@ -166,6 +176,11 @@ void BCEscapeAnalyzer::set_global_escape(ArgumentMap vars, bool merge) { if (vars.contains_unknown() || vars.contains_vars()) { _return_allocated = false; } + if (_return_local && vars.contains_vars() && !returns_all(vars)) { + // Return result should be invalidated if args in new + // state are not recorded in return state. + _return_local = false; + } } } diff --git a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp index 99a8adccbf7..3c701b6a4e8 100644 --- a/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp +++ b/hotspot/src/share/vm/ci/bcEscapeAnalyzer.hpp @@ -80,6 +80,7 @@ class BCEscapeAnalyzer : public ResourceObj { void set_returned(ArgumentMap vars); bool is_argument(ArgumentMap vars); bool is_arg_stack(ArgumentMap vars); + bool returns_all(ArgumentMap vars); void clear_bits(ArgumentMap vars, VectorSet &bs); void set_method_escape(ArgumentMap vars); void set_global_escape(ArgumentMap vars, bool merge = false); diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp index 65cd2333a9d..3ffacd39aff 100644 --- a/hotspot/src/share/vm/classfile/classFileParser.cpp +++ b/hotspot/src/share/vm/classfile/classFileParser.cpp @@ -3647,8 +3647,7 @@ instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name, // If RedefineClasses() was used before the retransformable // agent attached, then the cached class bytes may not be the // original class bytes. - unsigned char *cached_class_file_bytes = NULL; - jint cached_class_file_length; + JvmtiCachedClassFileData *cached_class_file = NULL; Handle class_loader(THREAD, loader_data->class_loader()); bool has_default_methods = false; ResourceMark rm(THREAD); @@ -3680,10 +3679,7 @@ instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name, if (h_class_being_redefined != NULL) { instanceKlassHandle ikh_class_being_redefined = instanceKlassHandle(THREAD, (*h_class_being_redefined)()); - cached_class_file_bytes = - ikh_class_being_redefined->get_cached_class_file_bytes(); - cached_class_file_length = - ikh_class_being_redefined->get_cached_class_file_len(); + cached_class_file = ikh_class_being_redefined->get_cached_class_file(); } } @@ -3691,9 +3687,7 @@ instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name, unsigned char* end_ptr = cfs->buffer() + cfs->length(); JvmtiExport::post_class_file_load_hook(name, class_loader(), protection_domain, - &ptr, &end_ptr, - &cached_class_file_bytes, - &cached_class_file_length); + &ptr, &end_ptr, &cached_class_file); if (ptr != cfs->buffer()) { // JVMTI agent has modified class file data. @@ -4011,10 +4005,9 @@ instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name, } } - if (cached_class_file_bytes != NULL) { + if (cached_class_file != NULL) { // JVMTI: we have an InstanceKlass now, tell it about the cached bytes - this_klass->set_cached_class_file(cached_class_file_bytes, - cached_class_file_length); + this_klass->set_cached_class_file(cached_class_file); } // Fill in field values obtained by parse_classfile_attributes diff --git a/hotspot/src/share/vm/classfile/defaultMethods.cpp b/hotspot/src/share/vm/classfile/defaultMethods.cpp index d6529ca4439..3ff2996b3ed 100644 --- a/hotspot/src/share/vm/classfile/defaultMethods.cpp +++ b/hotspot/src/share/vm/classfile/defaultMethods.cpp @@ -318,17 +318,17 @@ class KeepAliveVisitor : public HierarchyVisitor { } }; + // A method family contains a set of all methods that implement a single -// language-level method. Because of erasure, these methods may have different -// signatures. As members of the set are collected while walking over the +// erased method. As members of the set are collected while walking over the // hierarchy, they are tagged with a qualification state. The qualification // state for an erased method is set to disqualified if there exists a path // from the root of hierarchy to the method that contains an interleaving -// language-equivalent method defined in an interface. +// erased method defined in an interface. + class MethodFamily : public ResourceObj { private: - generic::MethodDescriptor* _descriptor; // language-level description GrowableArray > _members; ResourceHashtable _member_index; @@ -358,15 +358,8 @@ class MethodFamily : public ResourceObj { public: - MethodFamily(generic::MethodDescriptor* canonical_desc) - : _descriptor(canonical_desc), _selected_target(NULL), - _exception_message(NULL) {} - - generic::MethodDescriptor* descriptor() const { return _descriptor; } - - bool descriptor_matches(generic::MethodDescriptor* md, generic::Context* ctx) { - return descriptor()->covariant_match(md, ctx); - } + MethodFamily() + : _selected_target(NULL), _exception_message(NULL) {} void set_target_if_empty(Method* m) { if (_selected_target == NULL && !m->is_overpass()) { @@ -441,16 +434,10 @@ class MethodFamily : public ResourceObj { } #ifndef PRODUCT - void print_on(outputStream* str) const { - print_on(str, 0); - } - - void print_on(outputStream* str, int indent) const { + void print_sig_on(outputStream* str, Symbol* signature, int indent) const { streamIndentor si(str, indent * 2); - generic::Context ctx(NULL); // empty, as _descriptor already canonicalized - TempNewSymbol family = descriptor()->reify_signature(&ctx, Thread::current()); - str->indent().print_cr("Logical Method %s:", family->as_C_string()); + str->indent().print_cr("Logical Method %s:", signature->as_C_string()); streamIndentor si2(str); for (int i = 0; i < _members.length(); ++i) { @@ -516,38 +503,94 @@ Symbol* MethodFamily::generate_conflicts_message(GrowableArray* methods return SymbolTable::new_symbol(ss.base(), (int)ss.size(), CHECK_NULL); } +// A generic method family contains a set of all methods that implement a single +// language-level method. Because of erasure, these methods may have different +// signatures. As members of the set are collected while walking over the +// hierarchy, they are tagged with a qualification state. The qualification +// state for an erased method is set to disqualified if there exists a path +// from the root of hierarchy to the method that contains an interleaving +// language-equivalent method defined in an interface. +class GenericMethodFamily : public MethodFamily { + private: + + generic::MethodDescriptor* _descriptor; // language-level description + + public: + + GenericMethodFamily(generic::MethodDescriptor* canonical_desc) + : _descriptor(canonical_desc) {} + + generic::MethodDescriptor* descriptor() const { return _descriptor; } + + bool descriptor_matches(generic::MethodDescriptor* md, generic::Context* ctx) { + return descriptor()->covariant_match(md, ctx); + } + +#ifndef PRODUCT + Symbol* get_generic_sig() const { + + generic::Context ctx(NULL); // empty, as _descriptor already canonicalized + TempNewSymbol sig = descriptor()->reify_signature(&ctx, Thread::current()); + return sig; + } +#endif // ndef PRODUCT +}; + class StateRestorer; -// StatefulMethodFamily is a wrapper around MethodFamily that maintains the +// StatefulMethodFamily is a wrapper around a MethodFamily that maintains the // qualification state during hierarchy visitation, and applies that state -// when adding members to the MethodFamily. +// when adding members to the MethodFamily class StatefulMethodFamily : public ResourceObj { friend class StateRestorer; private: - MethodFamily* _method; QualifiedState _qualification_state; void set_qualification_state(QualifiedState state) { _qualification_state = state; } + protected: + MethodFamily* _method_family; + public: - StatefulMethodFamily(generic::MethodDescriptor* md, generic::Context* ctx) { - _method = new MethodFamily(md->canonicalize(ctx)); - _qualification_state = QUALIFIED; + StatefulMethodFamily() { + _method_family = new MethodFamily(); + _qualification_state = QUALIFIED; } - void set_target_if_empty(Method* m) { _method->set_target_if_empty(m); } - - MethodFamily* get_method_family() { return _method; } - - bool descriptor_matches(generic::MethodDescriptor* md, generic::Context* ctx) { - return _method->descriptor_matches(md, ctx); + StatefulMethodFamily(MethodFamily* mf) { + _method_family = mf; + _qualification_state = QUALIFIED; } + void set_target_if_empty(Method* m) { _method_family->set_target_if_empty(m); } + + MethodFamily* get_method_family() { return _method_family; } + StateRestorer* record_method_and_dq_further(Method* mo); }; + +// StatefulGenericMethodFamily is a wrapper around GenericMethodFamily that maintains the +// qualification state during hierarchy visitation, and applies that state +// when adding members to the GenericMethodFamily. +class StatefulGenericMethodFamily : public StatefulMethodFamily { + + public: + StatefulGenericMethodFamily(generic::MethodDescriptor* md, generic::Context* ctx) + : StatefulMethodFamily(new GenericMethodFamily(md->canonicalize(ctx))) { + + } + GenericMethodFamily* get_method_family() { + return (GenericMethodFamily*)_method_family; + } + + bool descriptor_matches(generic::MethodDescriptor* md, generic::Context* ctx) { + return get_method_family()->descriptor_matches(md, ctx); + } +}; + class StateRestorer : public PseudoScopeMark { private: StatefulMethodFamily* _method; @@ -563,9 +606,9 @@ class StateRestorer : public PseudoScopeMark { StateRestorer* StatefulMethodFamily::record_method_and_dq_further(Method* mo) { StateRestorer* mark = new StateRestorer(this, _qualification_state); if (_qualification_state == QUALIFIED) { - _method->record_qualified_method(mo); + _method_family->record_qualified_method(mo); } else { - _method->record_disqualified_method(mo); + _method_family->record_disqualified_method(mo); } // Everything found "above"??? this method in the hierarchy walk is set to // disqualified @@ -573,15 +616,15 @@ StateRestorer* StatefulMethodFamily::record_method_and_dq_further(Method* mo) { return mark; } -class StatefulMethodFamilies : public ResourceObj { +class StatefulGenericMethodFamilies : public ResourceObj { private: - GrowableArray _methods; + GrowableArray _methods; public: - StatefulMethodFamily* find_matching( + StatefulGenericMethodFamily* find_matching( generic::MethodDescriptor* md, generic::Context* ctx) { for (int i = 0; i < _methods.length(); ++i) { - StatefulMethodFamily* existing = _methods.at(i); + StatefulGenericMethodFamily* existing = _methods.at(i); if (existing->descriptor_matches(md, ctx)) { return existing; } @@ -589,17 +632,17 @@ class StatefulMethodFamilies : public ResourceObj { return NULL; } - StatefulMethodFamily* find_matching_or_create( + StatefulGenericMethodFamily* find_matching_or_create( generic::MethodDescriptor* md, generic::Context* ctx) { - StatefulMethodFamily* method = find_matching(md, ctx); + StatefulGenericMethodFamily* method = find_matching(md, ctx); if (method == NULL) { - method = new StatefulMethodFamily(md, ctx); + method = new StatefulGenericMethodFamily(md, ctx); _methods.append(method); } return method; } - void extract_families_into(GrowableArray* array) { + void extract_families_into(GrowableArray* array) { for (int i = 0; i < _methods.length(); ++i) { array->append(_methods.at(i)->get_method_family()); } @@ -683,26 +726,79 @@ static GrowableArray* find_empty_vtable_slots( return slots; } +// Iterates over the superinterface type hierarchy looking for all methods +// with a specific erased signature. +class FindMethodsByErasedSig : public HierarchyVisitor { + private: + // Context data + Symbol* _method_name; + Symbol* _method_signature; + StatefulMethodFamily* _family; + + public: + FindMethodsByErasedSig(Symbol* name, Symbol* signature) : + _method_name(name), _method_signature(signature), + _family(NULL) {} + + void get_discovered_family(MethodFamily** family) { + if (_family != NULL) { + *family = _family->get_method_family(); + } else { + *family = NULL; + } + } + + void* new_node_data(InstanceKlass* cls) { return new PseudoScope(); } + void free_node_data(void* node_data) { + PseudoScope::cast(node_data)->destroy(); + } + + // Find all methods on this hierarchy that match this + // method's erased (name, signature) + bool visit() { + PseudoScope* scope = PseudoScope::cast(current_data()); + InstanceKlass* iklass = current_class(); + + Method* m = iklass->find_method(_method_name, _method_signature); + if (m != NULL) { + if (_family == NULL) { + _family = new StatefulMethodFamily(); + } + + if (iklass->is_interface()) { + StateRestorer* restorer = _family->record_method_and_dq_further(m); + scope->add_mark(restorer); + } else { + // This is the rule that methods in classes "win" (bad word) over + // methods in interfaces. This works because of single inheritance + _family->set_target_if_empty(m); + } + } + return true; + } + +}; + // Iterates over the type hierarchy looking for all methods with a specific // method name. The result of this is a set of method families each of // which is populated with a set of methods that implement the same // language-level signature. -class FindMethodsByName : public HierarchyVisitor { +class FindMethodsByGenericSig : public HierarchyVisitor { private: // Context data Thread* THREAD; generic::DescriptorCache* _cache; Symbol* _method_name; generic::Context* _ctx; - StatefulMethodFamilies _families; + StatefulGenericMethodFamilies _families; public: - FindMethodsByName(generic::DescriptorCache* cache, Symbol* name, + FindMethodsByGenericSig(generic::DescriptorCache* cache, Symbol* name, generic::Context* ctx, Thread* thread) : _cache(cache), _method_name(name), _ctx(ctx), THREAD(thread) {} - void get_discovered_families(GrowableArray* methods) { + void get_discovered_families(GrowableArray* methods) { _families.extract_families_into(methods); } @@ -733,7 +829,7 @@ class FindMethodsByName : public HierarchyVisitor { // Find all methods on this hierarchy that match this method // (name, signature). This class collects other families of this // method name. - StatefulMethodFamily* family = + StatefulGenericMethodFamily* family = _families.find_matching_or_create(md, _ctx); if (klass->is_interface()) { @@ -752,8 +848,8 @@ class FindMethodsByName : public HierarchyVisitor { }; #ifndef PRODUCT -static void print_families( - GrowableArray* methods, Symbol* match) { +static void print_generic_families( + GrowableArray* methods, Symbol* match) { streamIndentor si(tty, 4); if (methods->length() == 0) { tty->indent(); @@ -761,22 +857,87 @@ static void print_families( } for (int i = 0; i < methods->length(); ++i) { tty->indent(); - MethodFamily* lm = methods->at(i); + GenericMethodFamily* lm = methods->at(i); if (lm->contains_signature(match)) { tty->print_cr(""); } else { tty->print_cr(""); } - lm->print_on(tty, 1); + lm->print_sig_on(tty, lm->get_generic_sig(), 1); } } #endif // ndef PRODUCT -static void merge_in_new_methods(InstanceKlass* klass, - GrowableArray* new_methods, TRAPS); static void create_overpasses( GrowableArray* slots, InstanceKlass* klass, TRAPS); +static void generate_generic_defaults( + InstanceKlass* klass, GrowableArray* empty_slots, + EmptyVtableSlot* slot, int current_slot_index, TRAPS) { + + if (slot->is_bound()) { +#ifndef PRODUCT + if (TraceDefaultMethods) { + streamIndentor si(tty, 4); + tty->indent().print_cr("Already bound to logical method:"); + GenericMethodFamily* lm = (GenericMethodFamily*)(slot->get_binding()); + lm->print_sig_on(tty, lm->get_generic_sig(), 1); + } +#endif // ndef PRODUCT + return; // covered by previous processing + } + + generic::DescriptorCache cache; + + generic::Context ctx(&cache); + FindMethodsByGenericSig visitor(&cache, slot->name(), &ctx, CHECK); + visitor.run(klass); + + GrowableArray discovered_families; + visitor.get_discovered_families(&discovered_families); + +#ifndef PRODUCT + if (TraceDefaultMethods) { + print_generic_families(&discovered_families, slot->signature()); + } +#endif // ndef PRODUCT + + // Find and populate any other slots that match the discovered families + for (int j = current_slot_index; j < empty_slots->length(); ++j) { + EmptyVtableSlot* open_slot = empty_slots->at(j); + + if (slot->name() == open_slot->name()) { + for (int k = 0; k < discovered_families.length(); ++k) { + GenericMethodFamily* lm = discovered_families.at(k); + + if (lm->contains_signature(open_slot->signature())) { + lm->determine_target(klass, CHECK); + open_slot->bind_family(lm); + } + } + } + } +} + +static void generate_erased_defaults( + InstanceKlass* klass, GrowableArray* empty_slots, + EmptyVtableSlot* slot, TRAPS) { + + // sets up a set of methods with the same exact erased signature + FindMethodsByErasedSig visitor(slot->name(), slot->signature()); + visitor.run(klass); + + MethodFamily* family; + visitor.get_discovered_family(&family); + if (family != NULL) { + family->determine_target(klass, CHECK); + slot->bind_family(family); + } +} + +static void merge_in_new_methods(InstanceKlass* klass, + GrowableArray* new_methods, TRAPS); + // This is the guts of the default methods implementation. This is called just // after the classfile has been parsed if some ancestor has default methods. // @@ -807,8 +968,6 @@ void DefaultMethods::generate_default_methods( // whatever scope it's in. ResourceMark rm(THREAD); - generic::DescriptorCache cache; - // Keep entire hierarchy alive for the duration of the computation KeepAliveRegistrar keepAlive(THREAD); KeepAliveVisitor loadKeepAlive(&keepAlive); @@ -837,47 +996,13 @@ void DefaultMethods::generate_default_methods( tty->print_cr(""); } #endif // ndef PRODUCT - if (slot->is_bound()) { -#ifndef PRODUCT - if (TraceDefaultMethods) { - streamIndentor si(tty, 4); - tty->indent().print_cr("Already bound to logical method:"); - slot->get_binding()->print_on(tty, 1); - } -#endif // ndef PRODUCT - continue; // covered by previous processing + + if (ParseGenericDefaults) { + generate_generic_defaults(klass, empty_slots, slot, i, CHECK); + } else { + generate_erased_defaults(klass, empty_slots, slot, CHECK); } - - generic::Context ctx(&cache); - FindMethodsByName visitor(&cache, slot->name(), &ctx, CHECK); - visitor.run(klass); - - GrowableArray discovered_families; - visitor.get_discovered_families(&discovered_families); - -#ifndef PRODUCT - if (TraceDefaultMethods) { - print_families(&discovered_families, slot->signature()); - } -#endif // ndef PRODUCT - - // Find and populate any other slots that match the discovered families - for (int j = i; j < empty_slots->length(); ++j) { - EmptyVtableSlot* open_slot = empty_slots->at(j); - - if (slot->name() == open_slot->name()) { - for (int k = 0; k < discovered_families.length(); ++k) { - MethodFamily* lm = discovered_families.at(k); - - if (lm->contains_signature(open_slot->signature())) { - lm->determine_target(klass, CHECK); - open_slot->bind_family(lm); - } - } - } - } - } - + } #ifndef PRODUCT if (TraceDefaultMethods) { tty->print_cr("Creating overpasses..."); @@ -893,7 +1018,6 @@ void DefaultMethods::generate_default_methods( #endif // ndef PRODUCT } - /** * Generic analysis was used upon interface '_target' and found a unique * default method candidate with generic signature '_method_desc'. This @@ -912,17 +1036,85 @@ void DefaultMethods::generate_default_methods( * the selected method along that path. */ class ShadowChecker : public HierarchyVisitor { - private: - generic::DescriptorCache* _cache; + protected: Thread* THREAD; InstanceKlass* _target; Symbol* _method_name; InstanceKlass* _method_holder; - generic::MethodDescriptor* _method_desc; bool _found_shadow; + + public: + + ShadowChecker(Thread* thread, Symbol* name, InstanceKlass* holder, + InstanceKlass* target) + : THREAD(thread), _method_name(name), _method_holder(holder), + _target(target), _found_shadow(false) {} + + void* new_node_data(InstanceKlass* cls) { return NULL; } + void free_node_data(void* data) { return; } + + bool visit() { + InstanceKlass* ik = current_class(); + if (ik == _target && current_depth() == 1) { + return false; // This was the specified super -- no need to search it + } + if (ik == _method_holder || ik == _target) { + // We found a path that should be examined to see if it shadows _method + if (path_has_shadow()) { + _found_shadow = true; + cancel_iteration(); + } + return false; // no need to continue up hierarchy + } + return true; + } + + virtual bool path_has_shadow() = 0; + bool found_shadow() { return _found_shadow; } +}; + +// Used for Invokespecial. +// Invokespecial is allowed to invoke a concrete interface method +// and can be used to disambuiguate among qualified candidates, +// which are methods in immediate superinterfaces, +// but may not be used to invoke a candidate that would be shadowed +// from the perspective of the caller. +// Invokespecial is also used in the overpass generation today +// We re-run the shadowchecker because we can't distinguish this case, +// but it should return the same answer, since the overpass target +// is now the invokespecial caller. +class ErasedShadowChecker : public ShadowChecker { + private: + bool path_has_shadow() { + + for (int i = current_depth() - 1; i > 0; --i) { + InstanceKlass* ik = class_at_depth(i); + + if (ik->is_interface()) { + int end; + int start = ik->find_method_by_name(_method_name, &end); + if (start != -1) { + return true; + } + } + } + return false; + } + public: + + ErasedShadowChecker(Thread* thread, Symbol* name, InstanceKlass* holder, + InstanceKlass* target) + : ShadowChecker(thread, name, holder, target) {} +}; + +class GenericShadowChecker : public ShadowChecker { + private: + generic::DescriptorCache* _cache; + generic::MethodDescriptor* _method_desc; + bool path_has_shadow() { generic::Context ctx(_cache); @@ -950,104 +1142,42 @@ class ShadowChecker : public HierarchyVisitor { public: - ShadowChecker(generic::DescriptorCache* cache, Thread* thread, + GenericShadowChecker(generic::DescriptorCache* cache, Thread* thread, Symbol* name, InstanceKlass* holder, generic::MethodDescriptor* desc, InstanceKlass* target) - : _cache(cache), THREAD(thread), _method_name(name), _method_holder(holder), - _method_desc(desc), _target(target), _found_shadow(false) {} - - void* new_node_data(InstanceKlass* cls) { return NULL; } - void free_node_data(void* data) { return; } - - bool visit() { - InstanceKlass* ik = current_class(); - if (ik == _target && current_depth() == 1) { - return false; // This was the specified super -- no need to search it - } - if (ik == _method_holder || ik == _target) { - // We found a path that should be examined to see if it shadows _method - if (path_has_shadow()) { - _found_shadow = true; - cancel_iteration(); - } - return false; // no need to continue up hierarchy - } - return true; - } - - bool found_shadow() { return _found_shadow; } + : ShadowChecker(thread, name, holder, target) { + _cache = cache; + _method_desc = desc; + } }; -// This is called during linktime when we find an invokespecial call that -// refers to a direct superinterface. It indicates that we should find the -// default method in the hierarchy of that superinterface, and if that method -// would have been a candidate from the point of view of 'this' class, then we -// return that method. -Method* DefaultMethods::find_super_default( - Klass* cls, Klass* super, Symbol* method_name, Symbol* sig, TRAPS) { - ResourceMark rm(THREAD); - assert(cls != NULL && super != NULL, "Need real classes"); +// Find the unique qualified candidate from the perspective of the super_class +// which is the resolved_klass, which must be an immediate superinterface +// of klass +Method* find_erased_super_default(InstanceKlass* current_class, InstanceKlass* super_class, Symbol* method_name, Symbol* sig, TRAPS) { - InstanceKlass* current_class = InstanceKlass::cast(cls); - InstanceKlass* direction = InstanceKlass::cast(super); + FindMethodsByErasedSig visitor(method_name, sig); + visitor.run(super_class); // find candidates from resolved_klass - // Keep entire hierarchy alive for the duration of the computation - KeepAliveRegistrar keepAlive(THREAD); - KeepAliveVisitor loadKeepAlive(&keepAlive); - loadKeepAlive.run(current_class); + MethodFamily* family; + visitor.get_discovered_family(&family); -#ifndef PRODUCT - if (TraceDefaultMethods) { - tty->print_cr("Finding super default method %s.%s%s from %s", - direction->name()->as_C_string(), - method_name->as_C_string(), sig->as_C_string(), - current_class->name()->as_C_string()); - } -#endif // ndef PRODUCT - - if (!direction->is_interface()) { - // We should not be here - return NULL; + if (family != NULL) { + family->determine_target(current_class, CHECK_NULL); // get target from current_class } - generic::DescriptorCache cache; - generic::Context ctx(&cache); - - // Prime the initial generic context for current -> direction - ctx.apply_type_arguments(current_class, direction, CHECK_NULL); - - FindMethodsByName visitor(&cache, method_name, &ctx, CHECK_NULL); - visitor.run(direction); - - GrowableArray families; - visitor.get_discovered_families(&families); - -#ifndef PRODUCT - if (TraceDefaultMethods) { - print_families(&families, sig); - } -#endif // ndef PRODUCT - - MethodFamily* selected_family = NULL; - - for (int i = 0; i < families.length(); ++i) { - MethodFamily* lm = families.at(i); - if (lm->contains_signature(sig)) { - lm->determine_target(current_class, CHECK_NULL); - selected_family = lm; - } - } - - if (selected_family->has_target()) { - Method* target = selected_family->get_selected_target(); + if (family->has_target()) { + Method* target = family->get_selected_target(); InstanceKlass* holder = InstanceKlass::cast(target->method_holder()); // Verify that the identified method is valid from the context of - // the current class - ShadowChecker checker(&cache, THREAD, target->name(), - holder, selected_family->descriptor(), direction); + // the current class, which is the caller class for invokespecial + // link resolution, i.e. ensure there it is not shadowed. + // You can use invokespecial to disambiguate interface methods, but + // you can not use it to skip over an interface method that would shadow it. + ErasedShadowChecker checker(THREAD, target->name(), holder, super_class); checker.run(current_class); if (checker.found_shadow()) { @@ -1061,13 +1191,71 @@ Method* DefaultMethods::find_super_default( } else { #ifndef PRODUCT if (TraceDefaultMethods) { - tty->print(" Returning "); - print_method(tty, target, true); - tty->print_cr(""); + family->print_sig_on(tty, target->signature(), 1); } #endif // ndef PRODUCT return target; } + } else { + assert(family->throws_exception(), "must have target or throw"); + THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(), + family->get_exception_message()->as_C_string(), NULL); + } +} + +// super_class is assumed to be the direct super of current_class +Method* find_generic_super_default( InstanceKlass* current_class, + InstanceKlass* super_class, + Symbol* method_name, Symbol* sig, TRAPS) { + generic::DescriptorCache cache; + generic::Context ctx(&cache); + + // Prime the initial generic context for current -> super_class + ctx.apply_type_arguments(current_class, super_class, CHECK_NULL); + + FindMethodsByGenericSig visitor(&cache, method_name, &ctx, CHECK_NULL); + visitor.run(super_class); + + GrowableArray families; + visitor.get_discovered_families(&families); + +#ifndef PRODUCT + if (TraceDefaultMethods) { + print_generic_families(&families, sig); + } +#endif // ndef PRODUCT + + GenericMethodFamily* selected_family = NULL; + + for (int i = 0; i < families.length(); ++i) { + GenericMethodFamily* lm = families.at(i); + if (lm->contains_signature(sig)) { + lm->determine_target(current_class, CHECK_NULL); + selected_family = lm; + } + } + + if (selected_family->has_target()) { + Method* target = selected_family->get_selected_target(); + InstanceKlass* holder = InstanceKlass::cast(target->method_holder()); + + // Verify that the identified method is valid from the context of + // the current class + GenericShadowChecker checker(&cache, THREAD, target->name(), + holder, selected_family->descriptor(), super_class); + checker.run(current_class); + + if (checker.found_shadow()) { +#ifndef PRODUCT + if (TraceDefaultMethods) { + tty->print_cr(" Only candidate found was shadowed."); + } +#endif // ndef PRODUCT + THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(), + "Accessible default method not found", NULL); + } else { + return target; + } } else { assert(selected_family->throws_exception(), "must have target or throw"); THROW_MSG_(vmSymbols::java_lang_AbstractMethodError(), @@ -1075,6 +1263,71 @@ Method* DefaultMethods::find_super_default( } } +// This is called during linktime when we find an invokespecial call that +// refers to a direct superinterface. It indicates that we should find the +// default method in the hierarchy of that superinterface, and if that method +// would have been a candidate from the point of view of 'this' class, then we +// return that method. +// This logic assumes that the super is a direct superclass of the caller +Method* DefaultMethods::find_super_default( + Klass* cls, Klass* super, Symbol* method_name, Symbol* sig, TRAPS) { + + ResourceMark rm(THREAD); + + assert(cls != NULL && super != NULL, "Need real classes"); + + InstanceKlass* current_class = InstanceKlass::cast(cls); + InstanceKlass* super_class = InstanceKlass::cast(super); + + // Keep entire hierarchy alive for the duration of the computation + KeepAliveRegistrar keepAlive(THREAD); + KeepAliveVisitor loadKeepAlive(&keepAlive); + loadKeepAlive.run(current_class); // get hierarchy from current class + +#ifndef PRODUCT + if (TraceDefaultMethods) { + tty->print_cr("Finding super default method %s.%s%s from %s", + super_class->name()->as_C_string(), + method_name->as_C_string(), sig->as_C_string(), + current_class->name()->as_C_string()); + } +#endif // ndef PRODUCT + + assert(super_class->is_interface(), "only call for default methods"); + + Method* target = NULL; + if (ParseGenericDefaults) { + target = find_generic_super_default(current_class, super_class, + method_name, sig, CHECK_NULL); + } else { + target = find_erased_super_default(current_class, super_class, + method_name, sig, CHECK_NULL); + } + +#ifndef PRODUCT + if (target != NULL) { + if (TraceDefaultMethods) { + tty->print(" Returning "); + print_method(tty, target, true); + tty->print_cr(""); + } + } +#endif // ndef PRODUCT + return target; +} + +#ifndef PRODUCT +// Return true is broad type is a covariant return of narrow type +static bool covariant_return_type(BasicType narrow, BasicType broad) { + if (narrow == broad) { + return true; + } + if (broad == T_OBJECT) { + return true; + } + return false; +} +#endif // ndef PRODUCT static int assemble_redirect( BytecodeConstantPool* cp, BytecodeBuffer* buffer, @@ -1103,7 +1356,7 @@ static int assemble_redirect( out.next(); } assert(out.at_return_type(), "Parameter counts do not match"); - assert(in.type() == out.type(), "Return types are not compatible"); + assert(covariant_return_type(out.type(), in.type()), "Return types are not compatible"); if (parameter_count == 1 && (in.type() == T_LONG || in.type() == T_DOUBLE)) { ++parameter_count; // need room for return value @@ -1144,10 +1397,15 @@ static Method* new_method( Symbol* sig, AccessFlags flags, int max_stack, int params, ConstMethod::MethodType mt, TRAPS) { - address code_start = static_cast
(bytecodes->adr_at(0)); - int code_length = bytecodes->length(); + address code_start = 0; + int code_length = 0; InlineTableSizes sizes; + if (bytecodes != NULL && bytecodes->length() > 0) { + code_start = static_cast
(bytecodes->adr_at(0)); + code_length = bytecodes->length(); + } + Method* m = Method::allocate(cp->pool_holder()->class_loader_data(), code_length, flags, &sizes, mt, CHECK_NULL); diff --git a/hotspot/src/share/vm/classfile/javaClasses.hpp b/hotspot/src/share/vm/classfile/javaClasses.hpp index 81f5705816c..899d3ba48a3 100644 --- a/hotspot/src/share/vm/classfile/javaClasses.hpp +++ b/hotspot/src/share/vm/classfile/javaClasses.hpp @@ -234,6 +234,7 @@ class java_lang_Class : AllStatic { static GrowableArray* _fixup_mirror_list; static void set_init_lock(oop java_class, oop init_lock); + static void set_protection_domain(oop java_class, oop protection_domain); public: static void compute_offsets(); @@ -272,7 +273,6 @@ class java_lang_Class : AllStatic { // Support for embedded per-class oops static oop protection_domain(oop java_class); - static void set_protection_domain(oop java_class, oop protection_domain); static oop init_lock(oop java_class); static objArrayOop signers(oop java_class); static void set_signers(oop java_class, objArrayOop signers); diff --git a/hotspot/src/share/vm/classfile/vmSymbols.hpp b/hotspot/src/share/vm/classfile/vmSymbols.hpp index 49def1e8d26..df370237167 100644 --- a/hotspot/src/share/vm/classfile/vmSymbols.hpp +++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp @@ -53,8 +53,6 @@ template(java_lang_Object, "java/lang/Object") \ template(java_lang_Class, "java/lang/Class") \ template(java_lang_String, "java/lang/String") \ - template(java_lang_StringValue, "java/lang/StringValue") \ - template(java_lang_StringCache, "java/lang/StringValue$StringCache") \ template(java_lang_Thread, "java/lang/Thread") \ template(java_lang_ThreadGroup, "java/lang/ThreadGroup") \ template(java_lang_Cloneable, "java/lang/Cloneable") \ @@ -106,7 +104,6 @@ template(java_util_Vector, "java/util/Vector") \ template(java_util_AbstractList, "java/util/AbstractList") \ template(java_util_Hashtable, "java/util/Hashtable") \ - template(java_util_HashMap, "java/util/HashMap") \ template(java_lang_Compiler, "java/lang/Compiler") \ template(sun_misc_Signal, "sun/misc/Signal") \ template(java_lang_AssertionStatusDirectives, "java/lang/AssertionStatusDirectives") \ @@ -367,8 +364,6 @@ template(offset_name, "offset") \ template(count_name, "count") \ template(hash_name, "hash") \ - template(frontCacheEnabled_name, "frontCacheEnabled") \ - template(stringCacheEnabled_name, "stringCacheEnabled") \ template(numberOfLeadingZeros_name, "numberOfLeadingZeros") \ template(numberOfTrailingZeros_name, "numberOfTrailingZeros") \ template(bitCount_name, "bitCount") \ @@ -771,6 +766,17 @@ do_name( decrypt_name, "decrypt") \ do_signature(byteArray_int_int_byteArray_int_signature, "([BII[BI)V") \ \ + /* support for java.util.zip */ \ + do_class(java_util_zip_CRC32, "java/util/zip/CRC32") \ + do_intrinsic(_updateCRC32, java_util_zip_CRC32, update_name, int2_int_signature, F_SN) \ + do_name( update_name, "update") \ + do_intrinsic(_updateBytesCRC32, java_util_zip_CRC32, updateBytes_name, updateBytes_signature, F_SN) \ + do_name( updateBytes_name, "updateBytes") \ + do_signature(updateBytes_signature, "(I[BII)I") \ + do_intrinsic(_updateByteBufferCRC32, java_util_zip_CRC32, updateByteBuffer_name, updateByteBuffer_signature, F_SN) \ + do_name( updateByteBuffer_name, "updateByteBuffer") \ + do_signature(updateByteBuffer_signature, "(IJII)I") \ + \ /* support for sun.misc.Unsafe */ \ do_class(sun_misc_Unsafe, "sun/misc/Unsafe") \ \ diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp index d91f907a2c0..b87efd7bc2a 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp @@ -2017,12 +2017,6 @@ oop_since_save_marks_iterate##nv_suffix(OopClosureType* blk) { \ ALL_SINCE_SAVE_MARKS_CLOSURES(CFLS_OOP_SINCE_SAVE_MARKS_DEFN) - -void CompactibleFreeListSpace::object_iterate_since_last_GC(ObjectClosure* cl) { - // ugghh... how would one do this efficiently for a non-contiguous space? - guarantee(false, "NYI"); -} - bool CompactibleFreeListSpace::linearAllocationWouldFail() const { return _smallLinearAllocBlock._word_size == 0; } diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp index 23c95897cfa..74c97e8df9d 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp @@ -396,7 +396,6 @@ class CompactibleFreeListSpace: public CompactibleSpace { // iteration support for promotion void save_marks(); bool no_allocs_since_save_marks(); - void object_iterate_since_last_GC(ObjectClosure* cl); // iteration support for sweeping void save_sweep_limit() { diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp index 85c7b73172e..ced79cbcf69 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp @@ -3129,26 +3129,6 @@ oop_since_save_marks_iterate##nv_suffix(OopClosureType* cl) { \ ALL_SINCE_SAVE_MARKS_CLOSURES(CMS_SINCE_SAVE_MARKS_DEFN) -void -ConcurrentMarkSweepGeneration::object_iterate_since_last_GC(ObjectClosure* blk) -{ - // Not currently implemented; need to do the following. -- ysr. - // dld -- I think that is used for some sort of allocation profiler. So it - // really means the objects allocated by the mutator since the last - // GC. We could potentially implement this cheaply by recording only - // the direct allocations in a side data structure. - // - // I think we probably ought not to be required to support these - // iterations at any arbitrary point; I think there ought to be some - // call to enable/disable allocation profiling in a generation/space, - // and the iterator ought to return the objects allocated in the - // gen/space since the enable call, or the last iterator call (which - // will probably be at a GC.) That way, for gens like CM&S that would - // require some extra data structure to support this, we only pay the - // cost when it's in use... - cmsSpace()->object_iterate_since_last_GC(blk); -} - void ConcurrentMarkSweepGeneration::younger_refs_iterate(OopsInGenClosure* cl) { cl->set_generation(this); diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp index bb485f4a83e..3806b896d26 100644 --- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp +++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp @@ -1273,7 +1273,6 @@ class ConcurrentMarkSweepGeneration: public CardGeneration { // Iteration support and related enquiries void save_marks(); bool no_allocs_since_save_marks(); - void object_iterate_since_last_GC(ObjectClosure* cl); void younger_refs_iterate(OopsInGenClosure* cl); // Iteration support specific to CMS generations diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CardCounts.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CardCounts.cpp index 00ea5b54850..f75e518facc 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CardCounts.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CardCounts.cpp @@ -152,12 +152,9 @@ uint G1CardCounts::add_card_count(jbyte* card_ptr) { if (card_num < _committed_max_card_num) { count = (uint) _card_counts[card_num]; if (count < G1ConcRSHotCardLimit) { - _card_counts[card_num] += 1; + _card_counts[card_num] = + (jubyte)(MIN2((uintx)(_card_counts[card_num] + 1), G1ConcRSHotCardLimit)); } - assert(_card_counts[card_num] <= G1ConcRSHotCardLimit, - err_msg("Refinement count overflow? " - "new count: "UINT32_FORMAT, - (uint) _card_counts[card_num])); } } return count; diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp index db8f863ad25..bdd3027b995 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp @@ -54,7 +54,6 @@ #include "memory/referenceProcessor.hpp" #include "oops/oop.inline.hpp" #include "oops/oop.pcgc.inline.hpp" -#include "runtime/aprofiler.hpp" #include "runtime/vmThread.hpp" size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0; @@ -2665,11 +2664,6 @@ void G1CollectedHeap::object_iterate(ObjectClosure* cl) { heap_region_iterate(&blk); } -void G1CollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) { - // FIXME: is this right? - guarantee(false, "object_iterate_since_last_GC not supported by G1 heap"); -} - // Calls a SpaceClosure on a HeapRegion. class SpaceClosureRegionClosure: public HeapRegionClosure { @@ -3598,8 +3592,6 @@ G1CollectedHeap* G1CollectedHeap::heap() { void G1CollectedHeap::gc_prologue(bool full /* Ignored */) { // always_do_update_barrier = false; assert(InlineCacheBuffer::is_empty(), "should have cleaned up ICBuffer"); - // Call allocation profiler - AllocationProfiler::iterate_since_last_gc(); // Fill TLAB's and such ensure_parsability(true); } diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp index 6843d13f736..9b52304c996 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp @@ -1360,11 +1360,6 @@ public: object_iterate(cl); } - // Iterate over all objects allocated since the last collection, calling - // "cl.do_object" on each. The heap must have been initialized properly - // to support this function, or else this call will fail. - virtual void object_iterate_since_last_GC(ObjectClosure* cl); - // Iterate over all spaces in use in the heap, in ascending address order. virtual void space_iterate(SpaceClosure* cl); diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp index 3bd04281955..4c6d2bbf877 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp @@ -873,7 +873,7 @@ bool G1CollectorPolicy::need_to_start_conc_mark(const char* source, size_t alloc size_t alloc_byte_size = alloc_word_size * HeapWordSize; if ((cur_used_bytes + alloc_byte_size) > marking_initiating_used_threshold) { - if (gcs_are_young()) { + if (gcs_are_young() && !_last_young_gc) { ergo_verbose5(ErgoConcCycles, "request concurrent cycle initiation", ergo_format_reason("occupancy higher than threshold") @@ -931,7 +931,7 @@ void G1CollectorPolicy::record_collection_pause_end(double pause_time_ms, Evacua last_pause_included_initial_mark = during_initial_mark_pause(); if (last_pause_included_initial_mark) { record_concurrent_mark_init_end(0.0); - } else if (!_last_young_gc && need_to_start_conc_mark("end of GC")) { + } else if (need_to_start_conc_mark("end of GC")) { // Note: this might have already been set, if during the last // pause we decided to start a cycle but at the beginning of // this pause we decided to postpone it. That's OK. diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp index adde08f2177..74aabc1298d 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1MarkSweep.cpp @@ -43,7 +43,6 @@ #include "oops/instanceRefKlass.hpp" #include "oops/oop.inline.hpp" #include "prims/jvmtiExport.hpp" -#include "runtime/aprofiler.hpp" #include "runtime/biasedLocking.hpp" #include "runtime/fprofiler.hpp" #include "runtime/synchronizer.hpp" diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp index 9cee1eb1ba2..218be0c0e40 100644 --- a/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp +++ b/hotspot/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.cpp @@ -47,7 +47,7 @@ void G1SATBCardTableModRefBS::enqueue(oop pre_val) { JavaThread* jt = (JavaThread*)thr; jt->satb_mark_queue().enqueue(pre_val); } else { - MutexLocker x(Shared_SATB_Q_lock); + MutexLockerEx x(Shared_SATB_Q_lock, Mutex::_no_safepoint_check_flag); JavaThread::satb_mark_queue_set().shared_satb_queue()->enqueue(pre_val); } } diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcTrace.cpp b/hotspot/src/share/vm/gc_implementation/shared/gcTrace.cpp index 6c53670425b..555e2ed9cf8 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/gcTrace.cpp +++ b/hotspot/src/share/vm/gc_implementation/shared/gcTrace.cpp @@ -23,12 +23,14 @@ */ #include "precompiled.hpp" +#include "gc_implementation/shared/copyFailedInfo.hpp" #include "gc_implementation/shared/gcHeapSummary.hpp" #include "gc_implementation/shared/gcTimer.hpp" #include "gc_implementation/shared/gcTrace.hpp" -#include "gc_implementation/shared/copyFailedInfo.hpp" +#include "gc_implementation/shared/objectCountEventSender.hpp" #include "memory/heapInspection.hpp" #include "memory/referenceProcessorStats.hpp" +#include "runtime/os.hpp" #include "utilities/globalDefinitions.hpp" #if INCLUDE_ALL_GCS @@ -38,7 +40,7 @@ #define assert_unset_gc_id() assert(_shared_gc_info.id() == SharedGCInfo::UNSET_GCID, "GC already started?") #define assert_set_gc_id() assert(_shared_gc_info.id() != SharedGCInfo::UNSET_GCID, "GC not started?") -static jlong GCTracer_next_gc_id = 0; +static GCId GCTracer_next_gc_id = 0; static GCId create_new_gc_id() { return GCTracer_next_gc_id++; } @@ -91,26 +93,38 @@ void GCTracer::report_gc_reference_stats(const ReferenceProcessorStats& rps) con } #if INCLUDE_SERVICES -void ObjectCountEventSenderClosure::do_cinfo(KlassInfoEntry* entry) { - if (should_send_event(entry)) { - send_event(entry); +class ObjectCountEventSenderClosure : public KlassInfoClosure { + const GCId _gc_id; + const double _size_threshold_percentage; + const size_t _total_size_in_words; + const jlong _timestamp; + + public: + ObjectCountEventSenderClosure(GCId gc_id, size_t total_size_in_words, jlong timestamp) : + _gc_id(gc_id), + _size_threshold_percentage(ObjectCountCutOffPercent / 100), + _total_size_in_words(total_size_in_words), + _timestamp(timestamp) + {} + + virtual void do_cinfo(KlassInfoEntry* entry) { + if (should_send_event(entry)) { + ObjectCountEventSender::send(entry, _gc_id, _timestamp); + } } -} -void ObjectCountEventSenderClosure::send_event(KlassInfoEntry* entry) { - _gc_tracer->send_object_count_after_gc_event(entry->klass(), entry->count(), - entry->words() * BytesPerWord); -} - -bool ObjectCountEventSenderClosure::should_send_event(KlassInfoEntry* entry) const { - double percentage_of_heap = ((double) entry->words()) / _total_size_in_words; - return percentage_of_heap > _size_threshold_percentage; -} + private: + bool should_send_event(const KlassInfoEntry* entry) const { + double percentage_of_heap = ((double) entry->words()) / _total_size_in_words; + return percentage_of_heap >= _size_threshold_percentage; + } +}; void GCTracer::report_object_count_after_gc(BoolObjectClosure* is_alive_cl) { assert_set_gc_id(); + assert(is_alive_cl != NULL, "Must supply function to check liveness"); - if (should_send_object_count_after_gc_event()) { + if (ObjectCountEventSender::should_send_event()) { ResourceMark rm; KlassInfoTable cit(false); @@ -118,12 +132,13 @@ void GCTracer::report_object_count_after_gc(BoolObjectClosure* is_alive_cl) { HeapInspection hi(false, false, false, NULL); hi.populate_table(&cit, is_alive_cl); - ObjectCountEventSenderClosure event_sender(this, cit.size_of_instances_in_words()); + jlong timestamp = os::elapsed_counter(); + ObjectCountEventSenderClosure event_sender(_shared_gc_info.id(), cit.size_of_instances_in_words(), timestamp); cit.iterate(&event_sender); } } } -#endif +#endif // INCLUDE_SERVICES void GCTracer::report_gc_heap_summary(GCWhen::Type when, const GCHeapSummary& heap_summary, const MetaspaceSummary& meta_space_summary) const { assert_set_gc_id(); diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcTrace.hpp b/hotspot/src/share/vm/gc_implementation/shared/gcTrace.hpp index 29ee55b685d..c157d86e7a3 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/gcTrace.hpp +++ b/hotspot/src/share/vm/gc_implementation/shared/gcTrace.hpp @@ -30,7 +30,6 @@ #include "gc_implementation/shared/gcWhen.hpp" #include "gc_implementation/shared/copyFailedInfo.hpp" #include "memory/allocation.hpp" -#include "memory/klassInfoClosure.hpp" #include "memory/referenceType.hpp" #if INCLUDE_ALL_GCS #include "gc_implementation/g1/g1YCTypes.hpp" @@ -113,7 +112,6 @@ class G1YoungGCInfo VALUE_OBJ_CLASS_SPEC { #endif // INCLUDE_ALL_GCS class GCTracer : public ResourceObj { - friend class ObjectCountEventSenderClosure; protected: SharedGCInfo _shared_gc_info; @@ -123,7 +121,6 @@ class GCTracer : public ResourceObj { void report_gc_heap_summary(GCWhen::Type when, const GCHeapSummary& heap_summary, const MetaspaceSummary& meta_space_summary) const; void report_gc_reference_stats(const ReferenceProcessorStats& rp) const; void report_object_count_after_gc(BoolObjectClosure* object_filter) NOT_SERVICES_RETURN; - bool has_reported_gc_start() const; protected: @@ -137,25 +134,6 @@ class GCTracer : public ResourceObj { void send_meta_space_summary_event(GCWhen::Type when, const MetaspaceSummary& meta_space_summary) const; void send_reference_stats_event(ReferenceType type, size_t count) const; void send_phase_events(TimePartitions* time_partitions) const; - void send_object_count_after_gc_event(Klass* klass, jlong count, julong total_size) const NOT_SERVICES_RETURN; - bool should_send_object_count_after_gc_event() const; -}; - -class ObjectCountEventSenderClosure : public KlassInfoClosure { - GCTracer* _gc_tracer; - const double _size_threshold_percentage; - const size_t _total_size_in_words; - public: - ObjectCountEventSenderClosure(GCTracer* gc_tracer, size_t total_size_in_words) : - _gc_tracer(gc_tracer), - _size_threshold_percentage(ObjectCountCutOffPercent / 100), - _total_size_in_words(total_size_in_words) - {} - virtual void do_cinfo(KlassInfoEntry* entry); - protected: - virtual void send_event(KlassInfoEntry* entry); - private: - bool should_send_event(KlassInfoEntry* entry) const; }; class YoungGCTracer : public GCTracer { diff --git a/hotspot/src/share/vm/gc_implementation/shared/gcTraceSend.cpp b/hotspot/src/share/vm/gc_implementation/shared/gcTraceSend.cpp index 4af7e3c2fbf..da0c3856dd6 100644 --- a/hotspot/src/share/vm/gc_implementation/shared/gcTraceSend.cpp +++ b/hotspot/src/share/vm/gc_implementation/shared/gcTraceSend.cpp @@ -123,27 +123,6 @@ void OldGCTracer::send_concurrent_mode_failure_event() { } } -#if INCLUDE_SERVICES -void GCTracer::send_object_count_after_gc_event(Klass* klass, jlong count, julong total_size) const { - EventObjectCountAfterGC e; - if (e.should_commit()) { - e.set_gcId(_shared_gc_info.id()); - e.set_class(klass); - e.set_count(count); - e.set_totalSize(total_size); - e.commit(); - } -} -#endif - -bool GCTracer::should_send_object_count_after_gc_event() const { -#if INCLUDE_TRACE - return Tracing::is_event_enabled(EventObjectCountAfterGC::eventId); -#else - return false; -#endif -} - #if INCLUDE_ALL_GCS void G1NewTracer::send_g1_young_gc_event() { EventGCG1GarbageCollection e(UNTIMED); diff --git a/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.cpp b/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.cpp new file mode 100644 index 00000000000..cf95bdd505e --- /dev/null +++ b/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.cpp @@ -0,0 +1,55 @@ +/* + * 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 + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + + +#include "precompiled.hpp" +#include "gc_implementation/shared/objectCountEventSender.hpp" +#include "memory/heapInspection.hpp" +#include "trace/tracing.hpp" +#include "utilities/globalDefinitions.hpp" + +#if INCLUDE_SERVICES + +void ObjectCountEventSender::send(const KlassInfoEntry* entry, GCId gc_id, jlong timestamp) { + assert(Tracing::is_event_enabled(EventObjectCountAfterGC::eventId), + "Only call this method if the event is enabled"); + + EventObjectCountAfterGC event(UNTIMED); + event.set_gcId(gc_id); + event.set_class(entry->klass()); + event.set_count(entry->count()); + event.set_totalSize(entry->words() * BytesPerWord); + event.set_endtime(timestamp); + event.commit(); +} + +bool ObjectCountEventSender::should_send_event() { +#if INCLUDE_TRACE + return Tracing::is_event_enabled(EventObjectCountAfterGC::eventId); +#else + return false; +#endif // INCLUDE_TRACE +} + +#endif // INCLUDE_SERVICES diff --git a/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.hpp b/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.hpp new file mode 100644 index 00000000000..b83e1fa737d --- /dev/null +++ b/hotspot/src/share/vm/gc_implementation/shared/objectCountEventSender.hpp @@ -0,0 +1,44 @@ +/* + * 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 + * under the terms of the GNU General Public License version 2 only, as + * published by the Free Software Foundation. + * + * This code is distributed in the hope that it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License + * version 2 for more details (a copy is included in the LICENSE file that + * accompanied this code). + * + * You should have received a copy of the GNU General Public License version + * 2 along with this work; if not, write to the Free Software Foundation, + * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. + * + * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA + * or visit www.oracle.com if you need additional information or have any + * questions. + * + */ + +#ifndef SHARE_VM_OBJECT_COUNT_EVENT_SENDER_HPP +#define SHARE_VM_OBJECT_COUNT_EVENT_SENDER_HPP + +#include "gc_implementation/shared/gcTrace.hpp" +#include "memory/allocation.hpp" +#include "utilities/macros.hpp" + +#if INCLUDE_SERVICES + +class KlassInfoEntry; + +class ObjectCountEventSender : public AllStatic { + public: + static void send(const KlassInfoEntry* entry, GCId gc_id, jlong timestamp); + static bool should_send_event(); +}; + +#endif // INCLUDE_SERVICES + +#endif // SHARE_VM_OBJECT_COUNT_EVENT_SENDER diff --git a/hotspot/src/share/vm/gc_interface/collectedHeap.cpp b/hotspot/src/share/vm/gc_interface/collectedHeap.cpp index 4c6c026e74b..dfc963c3bc4 100644 --- a/hotspot/src/share/vm/gc_interface/collectedHeap.cpp +++ b/hotspot/src/share/vm/gc_interface/collectedHeap.cpp @@ -85,16 +85,16 @@ GCHeapSummary CollectedHeap::create_heap_summary() { MetaspaceSummary CollectedHeap::create_metaspace_summary() { const MetaspaceSizes meta_space( - 0, /*MetaspaceAux::capacity_in_bytes(),*/ - 0, /*MetaspaceAux::used_in_bytes(),*/ + MetaspaceAux::allocated_capacity_bytes(), + MetaspaceAux::allocated_used_bytes(), MetaspaceAux::reserved_in_bytes()); const MetaspaceSizes data_space( - 0, /*MetaspaceAux::capacity_in_bytes(Metaspace::NonClassType),*/ - 0, /*MetaspaceAux::used_in_bytes(Metaspace::NonClassType),*/ + MetaspaceAux::allocated_capacity_bytes(Metaspace::NonClassType), + MetaspaceAux::allocated_used_bytes(Metaspace::NonClassType), MetaspaceAux::reserved_in_bytes(Metaspace::NonClassType)); const MetaspaceSizes class_space( - 0, /*MetaspaceAux::capacity_in_bytes(Metaspace::ClassType),*/ - 0, /*MetaspaceAux::used_in_bytes(Metaspace::ClassType),*/ + MetaspaceAux::allocated_capacity_bytes(Metaspace::ClassType), + MetaspaceAux::allocated_used_bytes(Metaspace::ClassType), MetaspaceAux::reserved_in_bytes(Metaspace::ClassType)); return MetaspaceSummary(meta_space, data_space, class_space); diff --git a/hotspot/src/share/vm/interpreter/abstractInterpreter.hpp b/hotspot/src/share/vm/interpreter/abstractInterpreter.hpp index 264d4fffbf6..77471ad3d5f 100644 --- a/hotspot/src/share/vm/interpreter/abstractInterpreter.hpp +++ b/hotspot/src/share/vm/interpreter/abstractInterpreter.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -102,6 +102,9 @@ class AbstractInterpreter: AllStatic { java_lang_math_pow, // implementation of java.lang.Math.pow (x,y) java_lang_math_exp, // implementation of java.lang.Math.exp (x) java_lang_ref_reference_get, // implementation of java.lang.ref.Reference.get() + java_util_zip_CRC32_update, // implementation of java.util.zip.CRC32.update() + java_util_zip_CRC32_updateBytes, // implementation of java.util.zip.CRC32.updateBytes() + java_util_zip_CRC32_updateByteBuffer, // implementation of java.util.zip.CRC32.updateByteBuffer() number_of_method_entries, invalid = -1 }; diff --git a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp index b51ba870568..538b836f08a 100644 --- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp +++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp @@ -1581,7 +1581,7 @@ run: #define ARRAY_LOADTO32(T, T2, format, stackRes, extra) \ { \ ARRAY_INTRO(-2); \ - extra; \ + (void)extra; \ SET_ ## stackRes(*(T2 *)(((address) arrObj->base(T)) + index * sizeof(T2)), \ -2); \ UPDATE_PC_AND_TOS_AND_CONTINUE(1, -1); \ @@ -1592,8 +1592,8 @@ run: { \ ARRAY_INTRO(-2); \ SET_ ## stackRes(*(T2 *)(((address) arrObj->base(T)) + index * sizeof(T2)), -1); \ - extra; \ - UPDATE_PC_AND_CONTINUE(1); \ + (void)extra; \ + UPDATE_PC_AND_CONTINUE(1); \ } CASE(_iaload): @@ -1617,7 +1617,7 @@ run: #define ARRAY_STOREFROM32(T, T2, format, stackSrc, extra) \ { \ ARRAY_INTRO(-3); \ - extra; \ + (void)extra; \ *(T2 *)(((address) arrObj->base(T)) + index * sizeof(T2)) = stackSrc( -1); \ UPDATE_PC_AND_TOS_AND_CONTINUE(1, -3); \ } @@ -1626,7 +1626,7 @@ run: #define ARRAY_STOREFROM64(T, T2, stackSrc, extra) \ { \ ARRAY_INTRO(-4); \ - extra; \ + (void)extra; \ *(T2 *)(((address) arrObj->base(T)) + index * sizeof(T2)) = stackSrc( -1); \ UPDATE_PC_AND_TOS_AND_CONTINUE(1, -4); \ } diff --git a/hotspot/src/share/vm/interpreter/interpreter.cpp b/hotspot/src/share/vm/interpreter/interpreter.cpp index 06554172bf1..dfd8b5b145a 100644 --- a/hotspot/src/share/vm/interpreter/interpreter.cpp +++ b/hotspot/src/share/vm/interpreter/interpreter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -195,6 +195,17 @@ AbstractInterpreter::MethodKind AbstractInterpreter::method_kind(methodHandle m) return kind; } +#ifndef CC_INTERP + if (UseCRC32Intrinsics && m->is_native()) { + // Use optimized stub code for CRC32 native methods. + switch (m->intrinsic_id()) { + case vmIntrinsics::_updateCRC32 : return java_util_zip_CRC32_update; + case vmIntrinsics::_updateBytesCRC32 : return java_util_zip_CRC32_updateBytes; + case vmIntrinsics::_updateByteBufferCRC32 : return java_util_zip_CRC32_updateByteBuffer; + } + } +#endif + // Native method? // Note: This test must come _before_ the test for intrinsic // methods. See also comments below. @@ -297,6 +308,9 @@ void AbstractInterpreter::print_method_kind(MethodKind kind) { case java_lang_math_sqrt : tty->print("java_lang_math_sqrt" ); break; case java_lang_math_log : tty->print("java_lang_math_log" ); break; case java_lang_math_log10 : tty->print("java_lang_math_log10" ); break; + case java_util_zip_CRC32_update : tty->print("java_util_zip_CRC32_update"); break; + case java_util_zip_CRC32_updateBytes : tty->print("java_util_zip_CRC32_updateBytes"); break; + case java_util_zip_CRC32_updateByteBuffer : tty->print("java_util_zip_CRC32_updateByteBuffer"); break; default: if (kind >= method_handle_invoke_FIRST && kind <= method_handle_invoke_LAST) { diff --git a/hotspot/src/share/vm/interpreter/templateInterpreter.cpp b/hotspot/src/share/vm/interpreter/templateInterpreter.cpp index 53e50b1c7fe..9f7ed4c7e97 100644 --- a/hotspot/src/share/vm/interpreter/templateInterpreter.cpp +++ b/hotspot/src/share/vm/interpreter/templateInterpreter.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -373,6 +373,12 @@ void TemplateInterpreterGenerator::generate_all() { method_entry(java_lang_math_pow ) method_entry(java_lang_ref_reference_get) + if (UseCRC32Intrinsics) { + method_entry(java_util_zip_CRC32_update) + method_entry(java_util_zip_CRC32_updateBytes) + method_entry(java_util_zip_CRC32_updateByteBuffer) + } + initialize_method_handle_entries(); // all native method kinds (must be one contiguous block) diff --git a/hotspot/src/share/vm/memory/allocation.cpp b/hotspot/src/share/vm/memory/allocation.cpp index c45dab1c4c5..6a80c47385e 100644 --- a/hotspot/src/share/vm/memory/allocation.cpp +++ b/hotspot/src/share/vm/memory/allocation.cpp @@ -236,10 +236,11 @@ class ChunkPool: public CHeapObj { size_t _num_used; // number of chunks currently checked out const size_t _size; // size of each chunk (must be uniform) - // Our three static pools + // Our four static pools static ChunkPool* _large_pool; static ChunkPool* _medium_pool; static ChunkPool* _small_pool; + static ChunkPool* _tiny_pool; // return first element or null void* get_first() { @@ -319,15 +320,18 @@ class ChunkPool: public CHeapObj { static ChunkPool* large_pool() { assert(_large_pool != NULL, "must be initialized"); return _large_pool; } static ChunkPool* medium_pool() { assert(_medium_pool != NULL, "must be initialized"); return _medium_pool; } static ChunkPool* small_pool() { assert(_small_pool != NULL, "must be initialized"); return _small_pool; } + static ChunkPool* tiny_pool() { assert(_tiny_pool != NULL, "must be initialized"); return _tiny_pool; } static void initialize() { _large_pool = new ChunkPool(Chunk::size + Chunk::aligned_overhead_size()); _medium_pool = new ChunkPool(Chunk::medium_size + Chunk::aligned_overhead_size()); _small_pool = new ChunkPool(Chunk::init_size + Chunk::aligned_overhead_size()); + _tiny_pool = new ChunkPool(Chunk::tiny_size + Chunk::aligned_overhead_size()); } static void clean() { enum { BlocksToKeep = 5 }; + _tiny_pool->free_all_but(BlocksToKeep); _small_pool->free_all_but(BlocksToKeep); _medium_pool->free_all_but(BlocksToKeep); _large_pool->free_all_but(BlocksToKeep); @@ -337,6 +341,7 @@ class ChunkPool: public CHeapObj { ChunkPool* ChunkPool::_large_pool = NULL; ChunkPool* ChunkPool::_medium_pool = NULL; ChunkPool* ChunkPool::_small_pool = NULL; +ChunkPool* ChunkPool::_tiny_pool = NULL; void chunkpool_init() { ChunkPool::initialize(); @@ -376,6 +381,7 @@ void* Chunk::operator new (size_t requested_size, AllocFailType alloc_failmode, case Chunk::size: return ChunkPool::large_pool()->allocate(bytes, alloc_failmode); case Chunk::medium_size: return ChunkPool::medium_pool()->allocate(bytes, alloc_failmode); case Chunk::init_size: return ChunkPool::small_pool()->allocate(bytes, alloc_failmode); + case Chunk::tiny_size: return ChunkPool::tiny_pool()->allocate(bytes, alloc_failmode); default: { void* p = os::malloc(bytes, mtChunk, CALLER_PC); if (p == NULL && alloc_failmode == AllocFailStrategy::EXIT_OOM) { @@ -392,6 +398,7 @@ void Chunk::operator delete(void* p) { case Chunk::size: ChunkPool::large_pool()->free(c); break; case Chunk::medium_size: ChunkPool::medium_pool()->free(c); break; case Chunk::init_size: ChunkPool::small_pool()->free(c); break; + case Chunk::tiny_size: ChunkPool::tiny_pool()->free(c); break; default: os::free(c, mtChunk); } } diff --git a/hotspot/src/share/vm/memory/allocation.hpp b/hotspot/src/share/vm/memory/allocation.hpp index 17654f06984..aa916660d8b 100644 --- a/hotspot/src/share/vm/memory/allocation.hpp +++ b/hotspot/src/share/vm/memory/allocation.hpp @@ -353,7 +353,8 @@ class Chunk: CHeapObj { slack = 20, // suspected sizeof(Chunk) + internal malloc headers #endif - init_size = 1*K - slack, // Size of first chunk + tiny_size = 256 - slack, // Size of first chunk (tiny) + init_size = 1*K - slack, // Size of first chunk (normal aka small) medium_size= 10*K - slack, // Size of medium-sized chunk size = 32*K - slack, // Default size of an Arena chunk (following the first) non_pool_size = init_size + 32 // An initial size which is not one of above diff --git a/hotspot/src/share/vm/memory/defNewGeneration.cpp b/hotspot/src/share/vm/memory/defNewGeneration.cpp index 88afd70a739..177569294af 100644 --- a/hotspot/src/share/vm/memory/defNewGeneration.cpp +++ b/hotspot/src/share/vm/memory/defNewGeneration.cpp @@ -450,11 +450,6 @@ void DefNewGeneration::compute_new_size() { } } -void DefNewGeneration::object_iterate_since_last_GC(ObjectClosure* cl) { - // $$$ This may be wrong in case of "scavenge failure"? - eden()->object_iterate(cl); -} - void DefNewGeneration::younger_refs_iterate(OopsInGenClosure* cl) { assert(false, "NYI -- are you sure you want to call this?"); } diff --git a/hotspot/src/share/vm/memory/defNewGeneration.hpp b/hotspot/src/share/vm/memory/defNewGeneration.hpp index c538e0a4f35..0623d446ad3 100644 --- a/hotspot/src/share/vm/memory/defNewGeneration.hpp +++ b/hotspot/src/share/vm/memory/defNewGeneration.hpp @@ -252,7 +252,6 @@ protected: // Iteration void object_iterate(ObjectClosure* blk); - void object_iterate_since_last_GC(ObjectClosure* cl); void younger_refs_iterate(OopsInGenClosure* cl); diff --git a/hotspot/src/share/vm/memory/filemap.cpp b/hotspot/src/share/vm/memory/filemap.cpp index dbc0c87edce..5dfaf6f9701 100644 --- a/hotspot/src/share/vm/memory/filemap.cpp +++ b/hotspot/src/share/vm/memory/filemap.cpp @@ -549,3 +549,13 @@ bool FileMapInfo::is_in_shared_space(const void* p) { return false; } + +void FileMapInfo::print_shared_spaces() { + gclog_or_tty->print_cr("Shared Spaces:"); + for (int i = 0; i < MetaspaceShared::n_regions; i++) { + struct FileMapInfo::FileMapHeader::space_info* si = &_header._space[i]; + gclog_or_tty->print(" %s " INTPTR_FORMAT "-" INTPTR_FORMAT, + shared_region_name[i], + si->_base, si->_base + si->_used); + } +} diff --git a/hotspot/src/share/vm/memory/filemap.hpp b/hotspot/src/share/vm/memory/filemap.hpp index a11914b9c01..ee4ccec5bfe 100644 --- a/hotspot/src/share/vm/memory/filemap.hpp +++ b/hotspot/src/share/vm/memory/filemap.hpp @@ -149,6 +149,7 @@ public: // Return true if given address is in the mapped shared space. bool is_in_shared_space(const void* p) NOT_CDS_RETURN_(false); + void print_shared_spaces() NOT_CDS_RETURN; }; #endif // SHARE_VM_MEMORY_FILEMAP_HPP diff --git a/hotspot/src/share/vm/memory/genCollectedHeap.cpp b/hotspot/src/share/vm/memory/genCollectedHeap.cpp index a74533d4321..ebdb77f6734 100644 --- a/hotspot/src/share/vm/memory/genCollectedHeap.cpp +++ b/hotspot/src/share/vm/memory/genCollectedHeap.cpp @@ -42,7 +42,6 @@ #include "memory/space.hpp" #include "oops/oop.inline.hpp" #include "oops/oop.inline2.hpp" -#include "runtime/aprofiler.hpp" #include "runtime/biasedLocking.hpp" #include "runtime/fprofiler.hpp" #include "runtime/handles.hpp" @@ -873,12 +872,6 @@ void GenCollectedHeap::safe_object_iterate(ObjectClosure* cl) { } } -void GenCollectedHeap::object_iterate_since_last_GC(ObjectClosure* cl) { - for (int i = 0; i < _n_gens; i++) { - _gens[i]->object_iterate_since_last_GC(cl); - } -} - Space* GenCollectedHeap::space_containing(const void* addr) const { for (int i = 0; i < _n_gens; i++) { Space* res = _gens[i]->space_containing(addr); @@ -1186,8 +1179,6 @@ void GenCollectedHeap::gc_prologue(bool full) { CollectedHeap::accumulate_statistics_all_tlabs(); ensure_parsability(true); // retire TLABs - // Call allocation profiler - AllocationProfiler::iterate_since_last_gc(); // Walk generations GenGCPrologueClosure blk(full); generation_iterate(&blk, false); // not old-to-young. diff --git a/hotspot/src/share/vm/memory/genCollectedHeap.hpp b/hotspot/src/share/vm/memory/genCollectedHeap.hpp index 783cd372d7c..43338c4da46 100644 --- a/hotspot/src/share/vm/memory/genCollectedHeap.hpp +++ b/hotspot/src/share/vm/memory/genCollectedHeap.hpp @@ -222,7 +222,6 @@ public: void oop_iterate(MemRegion mr, ExtendedOopClosure* cl); void object_iterate(ObjectClosure* cl); void safe_object_iterate(ObjectClosure* cl); - void object_iterate_since_last_GC(ObjectClosure* cl); Space* space_containing(const void* addr) const; // A CollectedHeap is divided into a dense sequence of "blocks"; that is, diff --git a/hotspot/src/share/vm/memory/generation.cpp b/hotspot/src/share/vm/memory/generation.cpp index 9fa46b34af4..f9c986fa7a0 100644 --- a/hotspot/src/share/vm/memory/generation.cpp +++ b/hotspot/src/share/vm/memory/generation.cpp @@ -811,16 +811,6 @@ void OneContigSpaceCardGeneration::space_iterate(SpaceClosure* blk, blk->do_space(_the_space); } -void OneContigSpaceCardGeneration::object_iterate_since_last_GC(ObjectClosure* blk) { - // Deal with delayed initialization of _the_space, - // and lack of initialization of _last_gc. - if (_last_gc.space() == NULL) { - assert(the_space() != NULL, "shouldn't be NULL"); - _last_gc = the_space()->bottom_mark(); - } - the_space()->object_iterate_from(_last_gc, blk); -} - void OneContigSpaceCardGeneration::younger_refs_iterate(OopsInGenClosure* blk) { blk->set_generation(this); younger_refs_in_space_iterate(_the_space, blk); diff --git a/hotspot/src/share/vm/memory/generation.hpp b/hotspot/src/share/vm/memory/generation.hpp index feb4fde18af..44d641feedd 100644 --- a/hotspot/src/share/vm/memory/generation.hpp +++ b/hotspot/src/share/vm/memory/generation.hpp @@ -551,12 +551,6 @@ class Generation: public CHeapObj { // the heap. This defaults to object_iterate() unless overridden. virtual void safe_object_iterate(ObjectClosure* cl); - // Iterate over all objects allocated in the generation since the last - // collection, calling "cl.do_object" on each. The generation must have - // been initialized properly to support this function, or else this call - // will fail. - virtual void object_iterate_since_last_GC(ObjectClosure* cl) = 0; - // Apply "cl->do_oop" to (the address of) all and only all the ref fields // in the current generation that contain pointers to objects in younger // generations. Objects allocated since the last "save_marks" call are @@ -724,7 +718,6 @@ class OneContigSpaceCardGeneration: public CardGeneration { // Iteration void object_iterate(ObjectClosure* blk); void space_iterate(SpaceClosure* blk, bool usedOnly = false); - void object_iterate_since_last_GC(ObjectClosure* cl); void younger_refs_iterate(OopsInGenClosure* blk); diff --git a/hotspot/src/share/vm/memory/heapInspection.hpp b/hotspot/src/share/vm/memory/heapInspection.hpp index c286e48658f..09558b0a2a9 100644 --- a/hotspot/src/share/vm/memory/heapInspection.hpp +++ b/hotspot/src/share/vm/memory/heapInspection.hpp @@ -26,7 +26,6 @@ #define SHARE_VM_MEMORY_HEAPINSPECTION_HPP #include "memory/allocation.inline.hpp" -#include "memory/klassInfoClosure.hpp" #include "oops/oop.inline.hpp" #include "oops/annotations.hpp" #include "utilities/macros.hpp" @@ -204,6 +203,12 @@ class KlassInfoEntry: public CHeapObj { const char* name() const; }; +class KlassInfoClosure : public StackObj { + public: + // Called for each KlassInfoEntry. + virtual void do_cinfo(KlassInfoEntry* cie) = 0; +}; + class KlassInfoBucket: public CHeapObj { private: KlassInfoEntry* _list; diff --git a/hotspot/src/share/vm/memory/metaspace.cpp b/hotspot/src/share/vm/memory/metaspace.cpp index 638f848513a..1522eddb76b 100644 --- a/hotspot/src/share/vm/memory/metaspace.cpp +++ b/hotspot/src/share/vm/memory/metaspace.cpp @@ -70,7 +70,7 @@ enum ChunkSizes { // in words. SpecializedChunk = 128, ClassSmallChunk = 256, SmallChunk = 512, - ClassMediumChunk = 1 * K, + ClassMediumChunk = 4 * K, MediumChunk = 8 * K, HumongousChunkGranularity = 8 }; @@ -580,7 +580,6 @@ class SpaceManager : public CHeapObj { // Number of small chunks to allocate to a manager // If class space manager, small chunks are unlimited static uint const _small_chunk_limit; - bool has_small_chunk_limit() { return !vs_list()->is_class(); } // Sum of all space in allocated chunks size_t _allocated_blocks_words; @@ -1298,13 +1297,18 @@ size_t MetaspaceGC::delta_capacity_until_GC(size_t word_size) { bool MetaspaceGC::should_expand(VirtualSpaceList* vsl, size_t word_size) { - size_t committed_capacity_bytes = MetaspaceAux::allocated_capacity_bytes(); // If the user wants a limit, impose one. - size_t max_metaspace_size_bytes = MaxMetaspaceSize; - size_t metaspace_size_bytes = MetaspaceSize; - if (!FLAG_IS_DEFAULT(MaxMetaspaceSize) && - MetaspaceAux::reserved_in_bytes() >= MaxMetaspaceSize) { - return false; + // The reason for someone using this flag is to limit reserved space. So + // for non-class virtual space, compare against virtual spaces that are reserved. + // For class virtual space, we only compare against the committed space, not + // reserved space, because this is a larger space prereserved for compressed + // class pointers. + if (!FLAG_IS_DEFAULT(MaxMetaspaceSize)) { + size_t real_allocated = Metaspace::space_list()->virtual_space_total() + + MetaspaceAux::allocated_capacity_bytes(Metaspace::ClassType); + if (real_allocated >= MaxMetaspaceSize) { + return false; + } } // Class virtual space should always be expanded. Call GC for the other @@ -1318,11 +1322,12 @@ bool MetaspaceGC::should_expand(VirtualSpaceList* vsl, size_t word_size) { } - // If the capacity is below the minimum capacity, allow the // expansion. Also set the high-water-mark (capacity_until_GC) // to that minimum capacity so that a GC will not be induced // until that minimum capacity is exceeded. + size_t committed_capacity_bytes = MetaspaceAux::allocated_capacity_bytes(); + size_t metaspace_size_bytes = MetaspaceSize; if (committed_capacity_bytes < metaspace_size_bytes || capacity_until_GC() == 0) { set_capacity_until_GC(metaspace_size_bytes); @@ -1854,13 +1859,11 @@ size_t SpaceManager::sum_waste_in_chunks_in_use(ChunkIndex index) const { Metachunk* chunk = chunks_in_use(index); // Count the free space in all the chunk but not the // current chunk from which allocations are still being done. - if (chunk != NULL) { - Metachunk* prev = chunk; - while (chunk != NULL && chunk != current_chunk()) { + while (chunk != NULL) { + if (chunk != current_chunk()) { result += chunk->free_word_size(); - prev = chunk; - chunk = chunk->next(); } + chunk = chunk->next(); } return result; } @@ -1949,8 +1952,7 @@ size_t SpaceManager::calc_chunk_size(size_t word_size) { // chunks will be allocated. size_t chunk_word_size; if (chunks_in_use(MediumIndex) == NULL && - (!has_small_chunk_limit() || - sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit)) { + sum_count_in_chunks_in_use(SmallIndex) < _small_chunk_limit) { chunk_word_size = (size_t) small_chunk_size(); if (word_size + Metachunk::overhead() > small_chunk_size()) { chunk_word_size = medium_chunk_size(); @@ -2659,10 +2661,10 @@ void MetaspaceAux::print_on(outputStream* out, Metaspace::MetadataType mdtype) { // Print total fragmentation for class and data metaspaces separately void MetaspaceAux::print_waste(outputStream* out) { - size_t specialized_waste = 0, small_waste = 0, medium_waste = 0, large_waste = 0; - size_t specialized_count = 0, small_count = 0, medium_count = 0, large_count = 0; - size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0, cls_large_waste = 0; - size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_large_count = 0; + size_t specialized_waste = 0, small_waste = 0, medium_waste = 0; + size_t specialized_count = 0, small_count = 0, medium_count = 0, humongous_count = 0; + size_t cls_specialized_waste = 0, cls_small_waste = 0, cls_medium_waste = 0; + size_t cls_specialized_count = 0, cls_small_count = 0, cls_medium_count = 0, cls_humongous_count = 0; ClassLoaderDataGraphMetaspaceIterator iter; while (iter.repeat()) { @@ -2674,8 +2676,7 @@ void MetaspaceAux::print_waste(outputStream* out) { small_count += msp->vsm()->sum_count_in_chunks_in_use(SmallIndex); medium_waste += msp->vsm()->sum_waste_in_chunks_in_use(MediumIndex); medium_count += msp->vsm()->sum_count_in_chunks_in_use(MediumIndex); - large_waste += msp->vsm()->sum_waste_in_chunks_in_use(HumongousIndex); - large_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex); + humongous_count += msp->vsm()->sum_count_in_chunks_in_use(HumongousIndex); cls_specialized_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(SpecializedIndex); cls_specialized_count += msp->class_vsm()->sum_count_in_chunks_in_use(SpecializedIndex); @@ -2683,20 +2684,23 @@ void MetaspaceAux::print_waste(outputStream* out) { cls_small_count += msp->class_vsm()->sum_count_in_chunks_in_use(SmallIndex); cls_medium_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(MediumIndex); cls_medium_count += msp->class_vsm()->sum_count_in_chunks_in_use(MediumIndex); - cls_large_waste += msp->class_vsm()->sum_waste_in_chunks_in_use(HumongousIndex); - cls_large_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex); + cls_humongous_count += msp->class_vsm()->sum_count_in_chunks_in_use(HumongousIndex); } } out->print_cr("Total fragmentation waste (words) doesn't count free space"); out->print_cr(" data: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", " SIZE_FORMAT " small(s) " SIZE_FORMAT ", " - SIZE_FORMAT " medium(s) " SIZE_FORMAT, + SIZE_FORMAT " medium(s) " SIZE_FORMAT ", " + "large count " SIZE_FORMAT, specialized_count, specialized_waste, small_count, - small_waste, medium_count, medium_waste); + small_waste, medium_count, medium_waste, humongous_count); out->print_cr(" class: " SIZE_FORMAT " specialized(s) " SIZE_FORMAT ", " - SIZE_FORMAT " small(s) " SIZE_FORMAT, + SIZE_FORMAT " small(s) " SIZE_FORMAT ", " + SIZE_FORMAT " medium(s) " SIZE_FORMAT ", " + "large count " SIZE_FORMAT, cls_specialized_count, cls_specialized_waste, - cls_small_count, cls_small_waste); + cls_small_count, cls_small_waste, + cls_medium_count, cls_medium_waste, cls_humongous_count); } // Dump global metaspace things from the end of ClassLoaderDataGraph @@ -3037,18 +3041,24 @@ Metablock* Metaspace::allocate(ClassLoaderData* loader_data, size_t word_size, if (Verbose && TraceMetadataChunkAllocation) { gclog_or_tty->print_cr("Metaspace allocation failed for size " SIZE_FORMAT, word_size); - if (loader_data->metaspace_or_null() != NULL) loader_data->metaspace_or_null()->dump(gclog_or_tty); + if (loader_data->metaspace_or_null() != NULL) loader_data->dump(gclog_or_tty); MetaspaceAux::dump(gclog_or_tty); } // -XX:+HeapDumpOnOutOfMemoryError and -XX:OnOutOfMemoryError support - report_java_out_of_memory("Metadata space"); + const char* space_string = (mdtype == ClassType) ? "Class Metadata space" : + "Metadata space"; + report_java_out_of_memory(space_string); if (JvmtiExport::should_post_resource_exhausted()) { JvmtiExport::post_resource_exhausted( JVMTI_RESOURCE_EXHAUSTED_OOM_ERROR, - "Metadata space"); + space_string); + } + if (mdtype == ClassType) { + THROW_OOP_0(Universe::out_of_memory_error_class_metaspace()); + } else { + THROW_OOP_0(Universe::out_of_memory_error_metaspace()); } - THROW_OOP_0(Universe::out_of_memory_error_perm_gen()); } } return Metablock::initialize(result, word_size); diff --git a/hotspot/src/share/vm/memory/metaspaceShared.cpp b/hotspot/src/share/vm/memory/metaspaceShared.cpp index d2c91827485..c7d61f7b732 100644 --- a/hotspot/src/share/vm/memory/metaspaceShared.cpp +++ b/hotspot/src/share/vm/memory/metaspaceShared.cpp @@ -826,35 +826,15 @@ public: bool reading() const { return true; } }; - -// Save bounds of shared spaces mapped in. -static char* _ro_base = NULL; -static char* _rw_base = NULL; -static char* _md_base = NULL; -static char* _mc_base = NULL; - // Return true if given address is in the mapped shared space. bool MetaspaceShared::is_in_shared_space(const void* p) { - if (_ro_base == NULL || _rw_base == NULL) { - return false; - } else { - return ((p >= _ro_base && p < (_ro_base + SharedReadOnlySize)) || - (p >= _rw_base && p < (_rw_base + SharedReadWriteSize))); - } + return UseSharedSpaces && FileMapInfo::current_info()->is_in_shared_space(p); } void MetaspaceShared::print_shared_spaces() { - gclog_or_tty->print_cr("Shared Spaces:"); - gclog_or_tty->print(" read-only " INTPTR_FORMAT "-" INTPTR_FORMAT, - _ro_base, _ro_base + SharedReadOnlySize); - gclog_or_tty->print(" read-write " INTPTR_FORMAT "-" INTPTR_FORMAT, - _rw_base, _rw_base + SharedReadWriteSize); - gclog_or_tty->cr(); - gclog_or_tty->print(" misc-data " INTPTR_FORMAT "-" INTPTR_FORMAT, - _md_base, _md_base + SharedMiscDataSize); - gclog_or_tty->print(" misc-code " INTPTR_FORMAT "-" INTPTR_FORMAT, - _mc_base, _mc_base + SharedMiscCodeSize); - gclog_or_tty->cr(); + if (UseSharedSpaces) { + FileMapInfo::current_info()->print_shared_spaces(); + } } @@ -874,6 +854,11 @@ bool MetaspaceShared::map_shared_spaces(FileMapInfo* mapinfo) { assert(!DumpSharedSpaces, "Should not be called with DumpSharedSpaces"); + char* _ro_base = NULL; + char* _rw_base = NULL; + char* _md_base = NULL; + char* _mc_base = NULL; + // Map each shared region if ((_ro_base = mapinfo->map_region(ro)) != NULL && (_rw_base = mapinfo->map_region(rw)) != NULL && diff --git a/hotspot/src/share/vm/memory/referenceProcessorStats.hpp b/hotspot/src/share/vm/memory/referenceProcessorStats.hpp index 73208331bac..7497c09b92f 100644 --- a/hotspot/src/share/vm/memory/referenceProcessorStats.hpp +++ b/hotspot/src/share/vm/memory/referenceProcessorStats.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it diff --git a/hotspot/src/share/vm/memory/resourceArea.hpp b/hotspot/src/share/vm/memory/resourceArea.hpp index 0699334a5e6..1357081fd67 100644 --- a/hotspot/src/share/vm/memory/resourceArea.hpp +++ b/hotspot/src/share/vm/memory/resourceArea.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -83,6 +83,10 @@ protected: Chunk *_chunk; // saved arena chunk char *_hwm, *_max; size_t _size_in_bytes; +#ifdef ASSERT + Thread* _thread; + ResourceMark* _previous_resource_mark; +#endif //ASSERT void initialize(Thread *thread) { _area = thread->resource_area(); @@ -92,6 +96,11 @@ protected: _size_in_bytes = _area->size_in_bytes(); debug_only(_area->_nesting++;) assert( _area->_nesting > 0, "must stack allocate RMs" ); +#ifdef ASSERT + _thread = thread; + _previous_resource_mark = thread->current_resource_mark(); + thread->set_current_resource_mark(this); +#endif // ASSERT } public: @@ -111,6 +120,17 @@ protected: _size_in_bytes = r->_size_in_bytes; debug_only(_area->_nesting++;) assert( _area->_nesting > 0, "must stack allocate RMs" ); +#ifdef ASSERT + Thread* thread = ThreadLocalStorage::thread(); + if (thread != NULL) { + _thread = thread; + _previous_resource_mark = thread->current_resource_mark(); + thread->set_current_resource_mark(this); + } else { + _thread = NULL; + _previous_resource_mark = NULL; + } +#endif // ASSERT } void reset_to_mark() { @@ -137,6 +157,11 @@ protected: assert( _area->_nesting > 0, "must stack allocate RMs" ); debug_only(_area->_nesting--;) reset_to_mark(); +#ifdef ASSERT + if (_thread != NULL) { + _thread->set_current_resource_mark(_previous_resource_mark); + } +#endif // ASSERT } diff --git a/hotspot/src/share/vm/memory/sharedHeap.hpp b/hotspot/src/share/vm/memory/sharedHeap.hpp index b13bf15b846..cd810c036d4 100644 --- a/hotspot/src/share/vm/memory/sharedHeap.hpp +++ b/hotspot/src/share/vm/memory/sharedHeap.hpp @@ -166,11 +166,6 @@ public: // Same as above, restricted to a memory region. virtual void oop_iterate(MemRegion mr, ExtendedOopClosure* cl) = 0; - // Iterate over all objects allocated since the last collection, calling - // "cl->do_object" on each. The heap must have been initialized properly - // to support this function, or else this call will fail. - virtual void object_iterate_since_last_GC(ObjectClosure* cl) = 0; - // Iterate over all spaces in use in the heap, in an undefined order. virtual void space_iterate(SpaceClosure* cl) = 0; diff --git a/hotspot/src/share/vm/memory/universe.cpp b/hotspot/src/share/vm/memory/universe.cpp index b443310b3c3..511610bd3bf 100644 --- a/hotspot/src/share/vm/memory/universe.cpp +++ b/hotspot/src/share/vm/memory/universe.cpp @@ -52,7 +52,6 @@ #include "oops/oop.inline.hpp" #include "oops/typeArrayKlass.hpp" #include "prims/jvmtiRedefineClassesTrace.hpp" -#include "runtime/aprofiler.hpp" #include "runtime/arguments.hpp" #include "runtime/deoptimization.hpp" #include "runtime/fprofiler.hpp" @@ -111,7 +110,8 @@ LatestMethodOopCache* Universe::_loader_addClass_cache = NULL; LatestMethodOopCache* Universe::_pd_implies_cache = NULL; ActiveMethodOopsCache* Universe::_reflect_invoke_cache = NULL; oop Universe::_out_of_memory_error_java_heap = NULL; -oop Universe::_out_of_memory_error_perm_gen = NULL; +oop Universe::_out_of_memory_error_metaspace = NULL; +oop Universe::_out_of_memory_error_class_metaspace = NULL; oop Universe::_out_of_memory_error_array_size = NULL; oop Universe::_out_of_memory_error_gc_overhead_limit = NULL; objArrayOop Universe::_preallocated_out_of_memory_error_array = NULL; @@ -180,7 +180,8 @@ void Universe::oops_do(OopClosure* f, bool do_all) { f->do_oop((oop*)&_the_null_string); f->do_oop((oop*)&_the_min_jint_string); f->do_oop((oop*)&_out_of_memory_error_java_heap); - f->do_oop((oop*)&_out_of_memory_error_perm_gen); + f->do_oop((oop*)&_out_of_memory_error_metaspace); + f->do_oop((oop*)&_out_of_memory_error_class_metaspace); f->do_oop((oop*)&_out_of_memory_error_array_size); f->do_oop((oop*)&_out_of_memory_error_gc_overhead_limit); f->do_oop((oop*)&_preallocated_out_of_memory_error_array); @@ -563,7 +564,8 @@ bool Universe::should_fill_in_stack_trace(Handle throwable) { // a potential loop which could happen if an out of memory occurs when attempting // to allocate the backtrace. return ((throwable() != Universe::_out_of_memory_error_java_heap) && - (throwable() != Universe::_out_of_memory_error_perm_gen) && + (throwable() != Universe::_out_of_memory_error_metaspace) && + (throwable() != Universe::_out_of_memory_error_class_metaspace) && (throwable() != Universe::_out_of_memory_error_array_size) && (throwable() != Universe::_out_of_memory_error_gc_overhead_limit)); } @@ -1014,7 +1016,8 @@ bool universe_post_init() { k = SystemDictionary::resolve_or_fail(vmSymbols::java_lang_OutOfMemoryError(), true, CHECK_false); k_h = instanceKlassHandle(THREAD, k); Universe::_out_of_memory_error_java_heap = k_h->allocate_instance(CHECK_false); - Universe::_out_of_memory_error_perm_gen = k_h->allocate_instance(CHECK_false); + Universe::_out_of_memory_error_metaspace = k_h->allocate_instance(CHECK_false); + Universe::_out_of_memory_error_class_metaspace = k_h->allocate_instance(CHECK_false); Universe::_out_of_memory_error_array_size = k_h->allocate_instance(CHECK_false); Universe::_out_of_memory_error_gc_overhead_limit = k_h->allocate_instance(CHECK_false); @@ -1047,7 +1050,9 @@ bool universe_post_init() { java_lang_Throwable::set_message(Universe::_out_of_memory_error_java_heap, msg()); msg = java_lang_String::create_from_str("Metadata space", CHECK_false); - java_lang_Throwable::set_message(Universe::_out_of_memory_error_perm_gen, msg()); + java_lang_Throwable::set_message(Universe::_out_of_memory_error_metaspace, msg()); + msg = java_lang_String::create_from_str("Class Metadata space", CHECK_false); + java_lang_Throwable::set_message(Universe::_out_of_memory_error_class_metaspace, msg()); msg = java_lang_String::create_from_str("Requested array size exceeds VM limit", CHECK_false); java_lang_Throwable::set_message(Universe::_out_of_memory_error_array_size, msg()); diff --git a/hotspot/src/share/vm/memory/universe.hpp b/hotspot/src/share/vm/memory/universe.hpp index 85397960f8c..24a95e84594 100644 --- a/hotspot/src/share/vm/memory/universe.hpp +++ b/hotspot/src/share/vm/memory/universe.hpp @@ -178,10 +178,12 @@ class Universe: AllStatic { static LatestMethodOopCache* _loader_addClass_cache; // method for registering loaded classes in class loader vector static LatestMethodOopCache* _pd_implies_cache; // method for checking protection domain attributes static ActiveMethodOopsCache* _reflect_invoke_cache; // method for security checks - static oop _out_of_memory_error_java_heap; // preallocated error object (no backtrace) - static oop _out_of_memory_error_perm_gen; // preallocated error object (no backtrace) - static oop _out_of_memory_error_array_size;// preallocated error object (no backtrace) - static oop _out_of_memory_error_gc_overhead_limit; // preallocated error object (no backtrace) + // preallocated error objects (no backtrace) + static oop _out_of_memory_error_java_heap; + static oop _out_of_memory_error_metaspace; + static oop _out_of_memory_error_class_metaspace; + static oop _out_of_memory_error_array_size; + static oop _out_of_memory_error_gc_overhead_limit; static Array* _the_empty_int_array; // Canonicalized int array static Array* _the_empty_short_array; // Canonicalized short array @@ -352,7 +354,8 @@ class Universe: AllStatic { // may or may not have a backtrace. If error has a backtrace then the stack trace is already // filled in. static oop out_of_memory_error_java_heap() { return gen_out_of_memory_error(_out_of_memory_error_java_heap); } - static oop out_of_memory_error_perm_gen() { return gen_out_of_memory_error(_out_of_memory_error_perm_gen); } + static oop out_of_memory_error_metaspace() { return gen_out_of_memory_error(_out_of_memory_error_metaspace); } + static oop out_of_memory_error_class_metaspace() { return gen_out_of_memory_error(_out_of_memory_error_class_metaspace); } static oop out_of_memory_error_array_size() { return gen_out_of_memory_error(_out_of_memory_error_array_size); } static oop out_of_memory_error_gc_overhead_limit() { return gen_out_of_memory_error(_out_of_memory_error_gc_overhead_limit); } diff --git a/hotspot/src/share/vm/oops/arrayKlass.cpp b/hotspot/src/share/vm/oops/arrayKlass.cpp index ef1c20e972b..6e04c3ac145 100644 --- a/hotspot/src/share/vm/oops/arrayKlass.cpp +++ b/hotspot/src/share/vm/oops/arrayKlass.cpp @@ -71,7 +71,6 @@ Method* ArrayKlass::uncached_lookup_method(Symbol* name, Symbol* signature) cons } ArrayKlass::ArrayKlass(Symbol* name) { - set_alloc_size(0); set_name(name); set_super(Universe::is_bootstrapping() ? (Klass*)NULL : SystemDictionary::Object_klass()); @@ -161,12 +160,6 @@ void ArrayKlass::array_klasses_do(void f(Klass* k)) { } } - -void ArrayKlass::with_array_klasses_do(void f(Klass* k)) { - array_klasses_do(f); -} - - // GC support void ArrayKlass::oops_do(OopClosure* cl) { diff --git a/hotspot/src/share/vm/oops/arrayKlass.hpp b/hotspot/src/share/vm/oops/arrayKlass.hpp index acf920e16d1..4b06f1c0ed6 100644 --- a/hotspot/src/share/vm/oops/arrayKlass.hpp +++ b/hotspot/src/share/vm/oops/arrayKlass.hpp @@ -39,7 +39,6 @@ class ArrayKlass: public Klass { Klass* volatile _higher_dimension; // Refers the (n+1)'th-dimensional array (if present). Klass* volatile _lower_dimension; // Refers the (n-1)'th-dimensional array (if present). int _vtable_len; // size of vtable for this klass - juint _alloc_size; // allocation profiling support oop _component_mirror; // component type, as a java/lang/Class protected: @@ -65,10 +64,6 @@ class ArrayKlass: public Klass { void set_lower_dimension(Klass* k) { _lower_dimension = k; } Klass** adr_lower_dimension() { return (Klass**)&this->_lower_dimension;} - // Allocation profiling support - juint alloc_size() const { return _alloc_size; } - void set_alloc_size(juint n) { _alloc_size = n; } - // offset of first element, including any padding for the sake of alignment int array_header_in_bytes() const { return layout_helper_header_size(layout_helper()); } int log2_element_size() const { return layout_helper_log2_element_size(layout_helper()); } @@ -126,7 +121,6 @@ class ArrayKlass: public Klass { // Iterators void array_klasses_do(void f(Klass* k)); void array_klasses_do(void f(Klass* k, TRAPS), TRAPS); - void with_array_klasses_do(void f(Klass* k)); // GC support virtual void oops_do(OopClosure* cl); diff --git a/hotspot/src/share/vm/oops/cpCache.hpp b/hotspot/src/share/vm/oops/cpCache.hpp index 27ca7980c07..c15b4a54bd6 100644 --- a/hotspot/src/share/vm/oops/cpCache.hpp +++ b/hotspot/src/share/vm/oops/cpCache.hpp @@ -140,8 +140,15 @@ class ConstantPoolCacheEntry VALUE_OBJ_CLASS_SPEC { _f1 = f1; } void release_set_f1(Metadata* f1); - void set_f2(intx f2) { assert(_f2 == 0 || _f2 == f2, "illegal field change"); _f2 = f2; } - void set_f2_as_vfinal_method(Method* f2) { assert(_f2 == 0 || _f2 == (intptr_t) f2, "illegal field change"); assert(is_vfinal(), "flags must be set"); _f2 = (intptr_t) f2; } + void set_f2(intx f2) { + intx existing_f2 = _f2; // read once + assert(existing_f2 == 0 || existing_f2 == f2, "illegal field change"); + _f2 = f2; + } + void set_f2_as_vfinal_method(Method* f2) { + assert(is_vfinal(), "flags must be set"); + set_f2((intx)f2); + } int make_flags(TosState state, int option_bits, int field_index_or_method_params); void set_flags(intx flags) { _flags = flags; } bool init_flags_atomic(intx flags); diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp index 886746d6bb6..a2684d84bb1 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.cpp +++ b/hotspot/src/share/vm/oops/instanceKlass.cpp @@ -48,6 +48,7 @@ #include "oops/symbol.hpp" #include "prims/jvmtiExport.hpp" #include "prims/jvmtiRedefineClassesTrace.hpp" +#include "prims/jvmtiRedefineClasses.hpp" #include "prims/methodComparator.hpp" #include "runtime/fieldDescriptor.hpp" #include "runtime/handles.inline.hpp" @@ -291,7 +292,7 @@ InstanceKlass::InstanceKlass(int vtable_len, set_initial_method_idnum(0); _dependencies = NULL; set_jvmti_cached_class_field_map(NULL); - set_cached_class_file(NULL, 0); + set_cached_class_file(NULL); set_initial_method_idnum(0); set_minor_version(0); set_major_version(0); @@ -1321,12 +1322,6 @@ void InstanceKlass::array_klasses_do(void f(Klass* k)) { ArrayKlass::cast(array_klasses())->array_klasses_do(f); } - -void InstanceKlass::with_array_klasses_do(void f(Klass* k)) { - f(this); - array_klasses_do(f); -} - #ifdef ASSERT static int linear_search(Array* methods, Symbol* name, Symbol* signature) { int len = methods->length(); @@ -2363,10 +2358,9 @@ void InstanceKlass::release_C_heap_structures() { } // deallocate the cached class file - if (_cached_class_file_bytes != NULL) { - os::free(_cached_class_file_bytes, mtClass); - _cached_class_file_bytes = NULL; - _cached_class_file_len = 0; + if (_cached_class_file != NULL) { + os::free(_cached_class_file, mtClass); + _cached_class_file = NULL; } // Decrement symbol reference counts associated with the unloaded class. @@ -3536,6 +3530,14 @@ Method* InstanceKlass::method_with_idnum(int idnum) { return m; } +jint InstanceKlass::get_cached_class_file_len() { + return VM_RedefineClasses::get_cached_class_file_len(_cached_class_file); +} + +unsigned char * InstanceKlass::get_cached_class_file_bytes() { + return VM_RedefineClasses::get_cached_class_file_bytes(_cached_class_file); +} + // Construct a PreviousVersionNode entry for the array hung off // the InstanceKlass. diff --git a/hotspot/src/share/vm/oops/instanceKlass.hpp b/hotspot/src/share/vm/oops/instanceKlass.hpp index 6c56a519558..b82b2f83af5 100644 --- a/hotspot/src/share/vm/oops/instanceKlass.hpp +++ b/hotspot/src/share/vm/oops/instanceKlass.hpp @@ -133,6 +133,8 @@ class OopMapBlock VALUE_OBJ_CLASS_SPEC { uint _count; }; +struct JvmtiCachedClassFileData; + class InstanceKlass: public Klass { friend class VMStructs; friend class ClassFileParser; @@ -249,8 +251,8 @@ class InstanceKlass: public Klass { // InstanceKlass. See PreviousVersionWalker below. GrowableArray* _previous_versions; // JVMTI fields can be moved to their own structure - see 6315920 - unsigned char * _cached_class_file_bytes; // JVMTI: cached class file, before retransformable agent modified it in CFLH - jint _cached_class_file_len; // JVMTI: length of above + // JVMTI: cached class file, before retransformable agent modified it in CFLH + JvmtiCachedClassFileData* _cached_class_file; volatile u2 _idnum_allocated_count; // JNI/JVMTI: increments with the addition of methods, old ids don't change @@ -615,11 +617,12 @@ class InstanceKlass: public Klass { static void purge_previous_versions(InstanceKlass* ik); // JVMTI: Support for caching a class file before it is modified by an agent that can do retransformation - void set_cached_class_file(unsigned char *class_file_bytes, - jint class_file_len) { _cached_class_file_len = class_file_len; - _cached_class_file_bytes = class_file_bytes; } - jint get_cached_class_file_len() { return _cached_class_file_len; } - unsigned char * get_cached_class_file_bytes() { return _cached_class_file_bytes; } + void set_cached_class_file(JvmtiCachedClassFileData *data) { + _cached_class_file = data; + } + JvmtiCachedClassFileData * get_cached_class_file() { return _cached_class_file; } + jint get_cached_class_file_len(); + unsigned char * get_cached_class_file_bytes(); // JVMTI: Support for caching of field indices, types, and offsets void set_jvmti_cached_class_field_map(JvmtiCachedClassFieldMap* descriptor) { @@ -794,7 +797,6 @@ class InstanceKlass: public Klass { void methods_do(void f(Method* method)); void array_klasses_do(void f(Klass* k)); void array_klasses_do(void f(Klass* k, TRAPS), TRAPS); - void with_array_klasses_do(void f(Klass* k)); bool super_types_do(SuperTypeClosure* blk); // Casting from Klass* @@ -874,10 +876,6 @@ class InstanceKlass: public Klass { } } - // Allocation profiling support - juint alloc_size() const { return _alloc_count * size_helper(); } - void set_alloc_size(juint n) {} - // Use this to return the size of an instance in heap words: int size_helper() const { return layout_helper_to_size_helper(layout_helper()); diff --git a/hotspot/src/share/vm/oops/klass.cpp b/hotspot/src/share/vm/oops/klass.cpp index a719b88bbbe..41d5ec31c73 100644 --- a/hotspot/src/share/vm/oops/klass.cpp +++ b/hotspot/src/share/vm/oops/klass.cpp @@ -168,7 +168,6 @@ Klass::Klass() { set_subklass(NULL); set_next_sibling(NULL); set_next_link(NULL); - set_alloc_count(0); TRACE_INIT_ID(this); set_prototype_header(markOopDesc::prototype()); @@ -543,12 +542,6 @@ Klass* Klass::array_klass_impl(bool or_null, TRAPS) { return NULL; } - -void Klass::with_array_klasses_do(void f(Klass* k)) { - f(this); -} - - oop Klass::class_loader() const { return class_loader_data()->class_loader(); } const char* Klass::external_name() const { diff --git a/hotspot/src/share/vm/oops/klass.hpp b/hotspot/src/share/vm/oops/klass.hpp index 5f4094d4f1e..1ca027a3762 100644 --- a/hotspot/src/share/vm/oops/klass.hpp +++ b/hotspot/src/share/vm/oops/klass.hpp @@ -79,7 +79,6 @@ // [last_biased_lock_bulk_revocation_time] (64 bits) // [prototype_header] // [biased_lock_revocation_count] -// [alloc_count ] // [_modified_oops] // [_accumulated_modified_oops] // [trace_id] @@ -171,8 +170,6 @@ class Klass : public Metadata { markOop _prototype_header; // Used when biased locking is both enabled and disabled for this type jint _biased_lock_revocation_count; - juint _alloc_count; // allocation profiling support - TRACE_DEFINE_KLASS_TRACE_ID; // Remembered sets support for the oops in the klasses. @@ -290,11 +287,6 @@ class Klass : public Metadata { void set_next_sibling(Klass* s); public: - // Allocation profiling support - juint alloc_count() const { return _alloc_count; } - void set_alloc_count(juint n) { _alloc_count = n; } - virtual juint alloc_size() const = 0; - virtual void set_alloc_size(juint n) = 0; // Compiler support static ByteSize super_offset() { return in_ByteSize(offset_of(Klass, _super)); } @@ -677,7 +669,6 @@ class Klass : public Metadata { #endif // INCLUDE_ALL_GCS virtual void array_klasses_do(void f(Klass* k)) {} - virtual void with_array_klasses_do(void f(Klass* k)); // Return self, except for abstract classes with exactly 1 // implementor. Then return the 1 concrete implementation. diff --git a/hotspot/src/share/vm/oops/method.cpp b/hotspot/src/share/vm/oops/method.cpp index 5941efb3b79..ac210e14834 100644 --- a/hotspot/src/share/vm/oops/method.cpp +++ b/hotspot/src/share/vm/oops/method.cpp @@ -1163,6 +1163,7 @@ methodHandle Method::clone_with_new_data(methodHandle m, u_char* new_code, int n newm->constMethod()->set_constMethod_size(new_const_method_size); newm->set_method_size(new_method_size); assert(newm->code_size() == new_code_length, "check"); + assert(newm->method_parameters_length() == method_parameters_len, "check"); assert(newm->checked_exceptions_length() == checked_exceptions_len, "check"); assert(newm->exception_table_length() == exception_table_len, "check"); assert(newm->localvariable_table_length() == localvariable_len, "check"); @@ -1174,6 +1175,12 @@ methodHandle Method::clone_with_new_data(methodHandle m, u_char* new_code, int n new_compressed_linenumber_table, new_compressed_linenumber_size); } + // Copy method_parameters + if (method_parameters_len > 0) { + memcpy(newm->method_parameters_start(), + m->method_parameters_start(), + method_parameters_len * sizeof(MethodParametersElement)); + } // Copy checked_exceptions if (checked_exceptions_len > 0) { memcpy(newm->checked_exceptions_start(), diff --git a/hotspot/src/share/vm/opto/bytecodeInfo.cpp b/hotspot/src/share/vm/opto/bytecodeInfo.cpp index 9d2a36be28e..45ba8d758b0 100644 --- a/hotspot/src/share/vm/opto/bytecodeInfo.cpp +++ b/hotspot/src/share/vm/opto/bytecodeInfo.cpp @@ -297,15 +297,6 @@ bool InlineTree::should_not_inline(ciMethod *callee_method, } } - if (UseStringCache) { - // Do not inline StringCache::profile() method used only at the beginning. - if (callee_method->name() == ciSymbol::profile_name() && - callee_method->holder()->name() == ciSymbol::java_lang_StringCache()) { - set_msg("profiling method"); - return true; - } - } - // use frequency-based objections only for non-trivial methods if (callee_method->code_size() <= MaxTrivialSize) { return false; diff --git a/hotspot/src/share/vm/opto/escape.cpp b/hotspot/src/share/vm/opto/escape.cpp index fd561a0c20c..c95226f110c 100644 --- a/hotspot/src/share/vm/opto/escape.cpp +++ b/hotspot/src/share/vm/opto/escape.cpp @@ -933,6 +933,7 @@ void ConnectionGraph::process_call_arguments(CallNode *call) { (call->as_CallLeaf()->_name != NULL && (strcmp(call->as_CallLeaf()->_name, "g1_wb_pre") == 0 || strcmp(call->as_CallLeaf()->_name, "g1_wb_post") == 0 || + strcmp(call->as_CallLeaf()->_name, "updateBytesCRC32") == 0 || strcmp(call->as_CallLeaf()->_name, "aescrypt_encryptBlock") == 0 || strcmp(call->as_CallLeaf()->_name, "aescrypt_decryptBlock") == 0 || strcmp(call->as_CallLeaf()->_name, "cipherBlockChaining_encryptAESCrypt") == 0 || diff --git a/hotspot/src/share/vm/opto/graphKit.cpp b/hotspot/src/share/vm/opto/graphKit.cpp index 590770b7c72..a363b11a5b8 100644 --- a/hotspot/src/share/vm/opto/graphKit.cpp +++ b/hotspot/src/share/vm/opto/graphKit.cpp @@ -3332,9 +3332,14 @@ AllocateNode* AllocateNode::Ideal_allocation(Node* ptr, PhaseTransform* phase) { if (ptr == NULL) { // reduce dumb test in callers return NULL; } - ptr = ptr->uncast(); // strip a raw-to-oop cast - if (ptr == NULL) return NULL; - + if (ptr->is_CheckCastPP()) { // strip only one raw-to-oop cast + ptr = ptr->in(1); + if (ptr == NULL) return NULL; + } + // Return NULL for allocations with several casts: + // j.l.reflect.Array.newInstance(jobject, jint) + // Object.clone() + // to keep more precise type from last cast. if (ptr->is_Proj()) { Node* allo = ptr->in(0); if (allo != NULL && allo->is_Allocate()) { diff --git a/hotspot/src/share/vm/opto/library_call.cpp b/hotspot/src/share/vm/opto/library_call.cpp index 728d892534b..df84634832a 100644 --- a/hotspot/src/share/vm/opto/library_call.cpp +++ b/hotspot/src/share/vm/opto/library_call.cpp @@ -291,6 +291,9 @@ class LibraryCallKit : public GraphKit { Node* inline_cipherBlockChaining_AESCrypt_predicate(bool decrypting); Node* get_key_start_from_aescrypt_object(Node* aescrypt_object); bool inline_encodeISOArray(); + bool inline_updateCRC32(); + bool inline_updateBytesCRC32(); + bool inline_updateByteBufferCRC32(); }; @@ -488,6 +491,12 @@ CallGenerator* Compile::make_vm_intrinsic(ciMethod* m, bool is_virtual) { is_predicted = true; break; + case vmIntrinsics::_updateCRC32: + case vmIntrinsics::_updateBytesCRC32: + case vmIntrinsics::_updateByteBufferCRC32: + if (!UseCRC32Intrinsics) return NULL; + break; + default: assert(id <= vmIntrinsics::LAST_COMPILER_INLINE, "caller responsibility"); assert(id != vmIntrinsics::_Object_init && id != vmIntrinsics::_invoke, "enum out of order?"); @@ -807,6 +816,13 @@ bool LibraryCallKit::try_to_inline() { case vmIntrinsics::_encodeISOArray: return inline_encodeISOArray(); + case vmIntrinsics::_updateCRC32: + return inline_updateCRC32(); + case vmIntrinsics::_updateBytesCRC32: + return inline_updateBytesCRC32(); + case vmIntrinsics::_updateByteBufferCRC32: + return inline_updateByteBufferCRC32(); + default: // If you get here, it may be that someone has added a new intrinsic // to the list in vmSymbols.hpp without implementing it here. @@ -884,7 +900,7 @@ Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_ IfNode* iff = create_and_map_if(control(), test, true_prob, COUNT_UNKNOWN); - Node* if_slow = _gvn.transform( new (C) IfTrueNode(iff) ); + Node* if_slow = _gvn.transform(new (C) IfTrueNode(iff)); if (if_slow == top()) { // The slow branch is never taken. No need to build this guard. return NULL; @@ -893,7 +909,7 @@ Node* LibraryCallKit::generate_guard(Node* test, RegionNode* region, float true_ if (region != NULL) region->add_req(if_slow); - Node* if_fast = _gvn.transform( new (C) IfFalseNode(iff) ); + Node* if_fast = _gvn.transform(new (C) IfFalseNode(iff)); set_control(if_fast); return if_slow; @@ -912,8 +928,8 @@ inline Node* LibraryCallKit::generate_negative_guard(Node* index, RegionNode* re return NULL; // already stopped if (_gvn.type(index)->higher_equal(TypeInt::POS)) // [0,maxint] return NULL; // index is already adequately typed - Node* cmp_lt = _gvn.transform( new (C) CmpINode(index, intcon(0)) ); - Node* bol_lt = _gvn.transform( new (C) BoolNode(cmp_lt, BoolTest::lt) ); + Node* cmp_lt = _gvn.transform(new (C) CmpINode(index, intcon(0))); + Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt)); Node* is_neg = generate_guard(bol_lt, region, PROB_MIN); if (is_neg != NULL && pos_index != NULL) { // Emulate effect of Parse::adjust_map_after_if. @@ -930,9 +946,9 @@ inline Node* LibraryCallKit::generate_nonpositive_guard(Node* index, bool never_ return NULL; // already stopped if (_gvn.type(index)->higher_equal(TypeInt::POS1)) // [1,maxint] return NULL; // index is already adequately typed - Node* cmp_le = _gvn.transform( new (C) CmpINode(index, intcon(0)) ); + Node* cmp_le = _gvn.transform(new (C) CmpINode(index, intcon(0))); BoolTest::mask le_or_eq = (never_negative ? BoolTest::eq : BoolTest::le); - Node* bol_le = _gvn.transform( new (C) BoolNode(cmp_le, le_or_eq) ); + Node* bol_le = _gvn.transform(new (C) BoolNode(cmp_le, le_or_eq)); Node* is_notp = generate_guard(bol_le, NULL, PROB_MIN); if (is_notp != NULL && pos_index != NULL) { // Emulate effect of Parse::adjust_map_after_if. @@ -968,9 +984,9 @@ inline Node* LibraryCallKit::generate_limit_guard(Node* offset, return NULL; // common case of whole-array copy Node* last = subseq_length; if (!zero_offset) // last += offset - last = _gvn.transform( new (C) AddINode(last, offset)); - Node* cmp_lt = _gvn.transform( new (C) CmpUNode(array_length, last) ); - Node* bol_lt = _gvn.transform( new (C) BoolNode(cmp_lt, BoolTest::lt) ); + last = _gvn.transform(new (C) AddINode(last, offset)); + Node* cmp_lt = _gvn.transform(new (C) CmpUNode(array_length, last)); + Node* bol_lt = _gvn.transform(new (C) BoolNode(cmp_lt, BoolTest::lt)); Node* is_over = generate_guard(bol_lt, region, PROB_MIN); return is_over; } @@ -1151,8 +1167,8 @@ bool LibraryCallKit::inline_string_equals() { Node* argument_cnt = load_String_length(no_ctrl, argument); // Check for receiver count != argument count - Node* cmp = _gvn.transform( new(C) CmpINode(receiver_cnt, argument_cnt) ); - Node* bol = _gvn.transform( new(C) BoolNode(cmp, BoolTest::ne) ); + Node* cmp = _gvn.transform(new(C) CmpINode(receiver_cnt, argument_cnt)); + Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::ne)); Node* if_ne = generate_slow_guard(bol, NULL); if (if_ne != NULL) { phi->init_req(4, intcon(0)); @@ -1258,7 +1274,7 @@ Node* LibraryCallKit::string_indexOf(Node* string_object, ciTypeArray* target_ar Node* sourceOffset = load_String_offset(no_ctrl, string_object); Node* sourceCount = load_String_length(no_ctrl, string_object); - Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true)) ); + Node* target = _gvn.transform( makecon(TypeOopPtr::make_from_constant(target_array, true))); jint target_length = target_array->length(); const TypeAry* target_array_type = TypeAry::make(TypeInt::CHAR, TypeInt::make(0, target_length, Type::WidenMin)); const TypeAryPtr* target_type = TypeAryPtr::make(TypePtr::BotPTR, target_array_type, target_array->klass(), true, Type::OffsetBot); @@ -1365,8 +1381,8 @@ bool LibraryCallKit::inline_string_indexOf() { Node* substr_cnt = load_String_length(no_ctrl, arg); // Check for substr count > string count - Node* cmp = _gvn.transform( new(C) CmpINode(substr_cnt, source_cnt) ); - Node* bol = _gvn.transform( new(C) BoolNode(cmp, BoolTest::gt) ); + Node* cmp = _gvn.transform(new(C) CmpINode(substr_cnt, source_cnt)); + Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::gt)); Node* if_gt = generate_slow_guard(bol, NULL); if (if_gt != NULL) { result_phi->init_req(2, intcon(-1)); @@ -1375,8 +1391,8 @@ bool LibraryCallKit::inline_string_indexOf() { if (!stopped()) { // Check for substr count == 0 - cmp = _gvn.transform( new(C) CmpINode(substr_cnt, intcon(0)) ); - bol = _gvn.transform( new(C) BoolNode(cmp, BoolTest::eq) ); + cmp = _gvn.transform(new(C) CmpINode(substr_cnt, intcon(0))); + bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq)); Node* if_zero = generate_slow_guard(bol, NULL); if (if_zero != NULL) { result_phi->init_req(3, intcon(0)); @@ -1552,7 +1568,7 @@ bool LibraryCallKit::inline_trig(vmIntrinsics::ID id) { // Check PI/4 : abs(arg) Node *cmp = _gvn.transform(new (C) CmpDNode(pi4,abs)); // Check: If PI/4 < abs(arg) then go slow - Node *bol = _gvn.transform( new (C) BoolNode( cmp, BoolTest::lt ) ); + Node *bol = _gvn.transform(new (C) BoolNode( cmp, BoolTest::lt )); // Branch either way IfNode *iff = create_and_xform_if(control(),bol, PROB_STATIC_FREQUENT, COUNT_UNKNOWN); set_control(opt_iff(r,iff)); @@ -1617,8 +1633,8 @@ void LibraryCallKit::finish_pow_exp(Node* result, Node* x, Node* y, const TypeFu // to the runtime to properly handle corner cases IfNode* iff = create_and_xform_if(control(), bolisnum, PROB_STATIC_FREQUENT, COUNT_UNKNOWN); - Node* if_slow = _gvn.transform( new (C) IfFalseNode(iff) ); - Node* if_fast = _gvn.transform( new (C) IfTrueNode(iff) ); + Node* if_slow = _gvn.transform(new (C) IfFalseNode(iff)); + Node* if_fast = _gvn.transform(new (C) IfTrueNode(iff)); if (!if_slow->is_top()) { RegionNode* result_region = new (C) RegionNode(3); @@ -1704,42 +1720,42 @@ bool LibraryCallKit::inline_pow() { // Check x:0 Node *cmp = _gvn.transform(new (C) CmpDNode(x, zeronode)); // Check: If (x<=0) then go complex path - Node *bol1 = _gvn.transform( new (C) BoolNode( cmp, BoolTest::le ) ); + Node *bol1 = _gvn.transform(new (C) BoolNode( cmp, BoolTest::le )); // Branch either way IfNode *if1 = create_and_xform_if(control(),bol1, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN); // Fast path taken; set region slot 3 - Node *fast_taken = _gvn.transform( new (C) IfFalseNode(if1) ); + Node *fast_taken = _gvn.transform(new (C) IfFalseNode(if1)); r->init_req(3,fast_taken); // Capture fast-control // Fast path not-taken, i.e. slow path - Node *complex_path = _gvn.transform( new (C) IfTrueNode(if1) ); + Node *complex_path = _gvn.transform(new (C) IfTrueNode(if1)); // Set fast path result - Node *fast_result = _gvn.transform( new (C) PowDNode(C, control(), x, y) ); + Node *fast_result = _gvn.transform(new (C) PowDNode(C, control(), x, y)); phi->init_req(3, fast_result); // Complex path // Build the second if node (if y is long) // Node for (long)y - Node *longy = _gvn.transform( new (C) ConvD2LNode(y)); + Node *longy = _gvn.transform(new (C) ConvD2LNode(y)); // Node for (double)((long) y) - Node *doublelongy= _gvn.transform( new (C) ConvL2DNode(longy)); + Node *doublelongy= _gvn.transform(new (C) ConvL2DNode(longy)); // Check (double)((long) y) : y Node *cmplongy= _gvn.transform(new (C) CmpDNode(doublelongy, y)); // Check if (y isn't long) then go to slow path - Node *bol2 = _gvn.transform( new (C) BoolNode( cmplongy, BoolTest::ne ) ); + Node *bol2 = _gvn.transform(new (C) BoolNode( cmplongy, BoolTest::ne )); // Branch either way IfNode *if2 = create_and_xform_if(complex_path,bol2, PROB_STATIC_INFREQUENT, COUNT_UNKNOWN); - Node* ylong_path = _gvn.transform( new (C) IfFalseNode(if2)); + Node* ylong_path = _gvn.transform(new (C) IfFalseNode(if2)); - Node *slow_path = _gvn.transform( new (C) IfTrueNode(if2) ); + Node *slow_path = _gvn.transform(new (C) IfTrueNode(if2)); // Calculate DPow(abs(x), y)*(1 & (long)y) // Node for constant 1 Node *conone = longcon(1); // 1& (long)y - Node *signnode= _gvn.transform( new (C) AndLNode(conone, longy) ); + Node *signnode= _gvn.transform(new (C) AndLNode(conone, longy)); // A huge number is always even. Detect a huge number by checking // if y + 1 == y and set integer to be tested for parity to 0. @@ -1747,9 +1763,9 @@ bool LibraryCallKit::inline_pow() { // (long)9.223372036854776E18 = max_jlong // (double)(long)9.223372036854776E18 = 9.223372036854776E18 // max_jlong is odd but 9.223372036854776E18 is even - Node* yplus1 = _gvn.transform( new (C) AddDNode(y, makecon(TypeD::make(1)))); + Node* yplus1 = _gvn.transform(new (C) AddDNode(y, makecon(TypeD::make(1)))); Node *cmpyplus1= _gvn.transform(new (C) CmpDNode(yplus1, y)); - Node *bolyplus1 = _gvn.transform( new (C) BoolNode( cmpyplus1, BoolTest::eq ) ); + Node *bolyplus1 = _gvn.transform(new (C) BoolNode( cmpyplus1, BoolTest::eq )); Node* correctedsign = NULL; if (ConditionalMoveLimit != 0) { correctedsign = _gvn.transform( CMoveNode::make(C, NULL, bolyplus1, signnode, longcon(0), TypeLong::LONG)); @@ -1757,8 +1773,8 @@ bool LibraryCallKit::inline_pow() { IfNode *ifyplus1 = create_and_xform_if(ylong_path,bolyplus1, PROB_FAIR, COUNT_UNKNOWN); RegionNode *r = new (C) RegionNode(3); Node *phi = new (C) PhiNode(r, TypeLong::LONG); - r->init_req(1, _gvn.transform( new (C) IfFalseNode(ifyplus1))); - r->init_req(2, _gvn.transform( new (C) IfTrueNode(ifyplus1))); + r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyplus1))); + r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyplus1))); phi->init_req(1, signnode); phi->init_req(2, longcon(0)); correctedsign = _gvn.transform(phi); @@ -1771,11 +1787,11 @@ bool LibraryCallKit::inline_pow() { // Check (1&(long)y)==0? Node *cmpeq1 = _gvn.transform(new (C) CmpLNode(correctedsign, conzero)); // Check if (1&(long)y)!=0?, if so the result is negative - Node *bol3 = _gvn.transform( new (C) BoolNode( cmpeq1, BoolTest::ne ) ); + Node *bol3 = _gvn.transform(new (C) BoolNode( cmpeq1, BoolTest::ne )); // abs(x) - Node *absx=_gvn.transform( new (C) AbsDNode(x)); + Node *absx=_gvn.transform(new (C) AbsDNode(x)); // abs(x)^y - Node *absxpowy = _gvn.transform( new (C) PowDNode(C, control(), absx, y) ); + Node *absxpowy = _gvn.transform(new (C) PowDNode(C, control(), absx, y)); // -abs(x)^y Node *negabsxpowy = _gvn.transform(new (C) NegDNode (absxpowy)); // (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y) @@ -1786,8 +1802,8 @@ bool LibraryCallKit::inline_pow() { IfNode *ifyeven = create_and_xform_if(ylong_path,bol3, PROB_FAIR, COUNT_UNKNOWN); RegionNode *r = new (C) RegionNode(3); Node *phi = new (C) PhiNode(r, Type::DOUBLE); - r->init_req(1, _gvn.transform( new (C) IfFalseNode(ifyeven))); - r->init_req(2, _gvn.transform( new (C) IfTrueNode(ifyeven))); + r->init_req(1, _gvn.transform(new (C) IfFalseNode(ifyeven))); + r->init_req(2, _gvn.transform(new (C) IfTrueNode(ifyeven))); phi->init_req(1, absxpowy); phi->init_req(2, negabsxpowy); signresult = _gvn.transform(phi); @@ -1920,7 +1936,7 @@ LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) { int cmp_op = Op_CmpI; Node* xkey = xvalue; Node* ykey = yvalue; - Node* ideal_cmpxy = _gvn.transform( new(C) CmpINode(xkey, ykey) ); + Node* ideal_cmpxy = _gvn.transform(new(C) CmpINode(xkey, ykey)); if (ideal_cmpxy->is_Cmp()) { // E.g., if we have CmpI(length - offset, count), // it might idealize to CmpI(length, count + offset) @@ -2013,7 +2029,7 @@ LibraryCallKit::generate_min_max(vmIntrinsics::ID id, Node* x0, Node* y0) { default: if (cmpxy == NULL) cmpxy = ideal_cmpxy; - best_bol = _gvn.transform( new(C) BoolNode(cmpxy, BoolTest::lt) ); + best_bol = _gvn.transform(new(C) BoolNode(cmpxy, BoolTest::lt)); // and fall through: case BoolTest::lt: // x < y case BoolTest::le: // x <= y @@ -2073,7 +2089,7 @@ LibraryCallKit::classify_unsafe_addr(Node* &base, Node* &offset) { return Type::AnyPtr; } else if (base_type == TypePtr::NULL_PTR) { // Since this is a NULL+long form, we have to switch to a rawptr. - base = _gvn.transform( new (C) CastX2PNode(offset) ); + base = _gvn.transform(new (C) CastX2PNode(offset)); offset = MakeConX(0); return Type::RawPtr; } else if (base_type->base() == Type::RawPtr) { @@ -2467,7 +2483,7 @@ bool LibraryCallKit::inline_unsafe_access(bool is_native_ptr, bool is_store, Bas case T_ADDRESS: // Repackage the long as a pointer. val = ConvL2X(val); - val = _gvn.transform( new (C) CastX2PNode(val) ); + val = _gvn.transform(new (C) CastX2PNode(val)); break; } @@ -2775,7 +2791,7 @@ bool LibraryCallKit::inline_unsafe_load_store(BasicType type, LoadStoreKind kind // SCMemProjNodes represent the memory state of a LoadStore. Their // main role is to prevent LoadStore nodes from being optimized away // when their results aren't used. - Node* proj = _gvn.transform( new (C) SCMemProjNode(load_store)); + Node* proj = _gvn.transform(new (C) SCMemProjNode(load_store)); set_memory(proj, alias_idx); // Add the trailing membar surrounding the access @@ -3010,8 +3026,8 @@ bool LibraryCallKit::inline_native_isInterrupted() { Node* rec_thr = argument(0); Node* tls_ptr = NULL; Node* cur_thr = generate_current_thread(tls_ptr); - Node* cmp_thr = _gvn.transform( new (C) CmpPNode(cur_thr, rec_thr) ); - Node* bol_thr = _gvn.transform( new (C) BoolNode(cmp_thr, BoolTest::ne) ); + Node* cmp_thr = _gvn.transform(new (C) CmpPNode(cur_thr, rec_thr)); + Node* bol_thr = _gvn.transform(new (C) BoolNode(cmp_thr, BoolTest::ne)); generate_slow_guard(bol_thr, slow_region); @@ -3022,36 +3038,36 @@ bool LibraryCallKit::inline_native_isInterrupted() { // Set the control input on the field _interrupted read to prevent it floating up. Node* int_bit = make_load(control(), p, TypeInt::BOOL, T_INT); - Node* cmp_bit = _gvn.transform( new (C) CmpINode(int_bit, intcon(0)) ); - Node* bol_bit = _gvn.transform( new (C) BoolNode(cmp_bit, BoolTest::ne) ); + Node* cmp_bit = _gvn.transform(new (C) CmpINode(int_bit, intcon(0))); + Node* bol_bit = _gvn.transform(new (C) BoolNode(cmp_bit, BoolTest::ne)); IfNode* iff_bit = create_and_map_if(control(), bol_bit, PROB_UNLIKELY_MAG(3), COUNT_UNKNOWN); // First fast path: if (!TLS._interrupted) return false; - Node* false_bit = _gvn.transform( new (C) IfFalseNode(iff_bit) ); + Node* false_bit = _gvn.transform(new (C) IfFalseNode(iff_bit)); result_rgn->init_req(no_int_result_path, false_bit); result_val->init_req(no_int_result_path, intcon(0)); // drop through to next case - set_control( _gvn.transform(new (C) IfTrueNode(iff_bit)) ); + set_control( _gvn.transform(new (C) IfTrueNode(iff_bit))); // (c) Or, if interrupt bit is set and clear_int is false, use 2nd fast path. Node* clr_arg = argument(1); - Node* cmp_arg = _gvn.transform( new (C) CmpINode(clr_arg, intcon(0)) ); - Node* bol_arg = _gvn.transform( new (C) BoolNode(cmp_arg, BoolTest::ne) ); + Node* cmp_arg = _gvn.transform(new (C) CmpINode(clr_arg, intcon(0))); + Node* bol_arg = _gvn.transform(new (C) BoolNode(cmp_arg, BoolTest::ne)); IfNode* iff_arg = create_and_map_if(control(), bol_arg, PROB_FAIR, COUNT_UNKNOWN); // Second fast path: ... else if (!clear_int) return true; - Node* false_arg = _gvn.transform( new (C) IfFalseNode(iff_arg) ); + Node* false_arg = _gvn.transform(new (C) IfFalseNode(iff_arg)); result_rgn->init_req(no_clear_result_path, false_arg); result_val->init_req(no_clear_result_path, intcon(1)); // drop through to next case - set_control( _gvn.transform(new (C) IfTrueNode(iff_arg)) ); + set_control( _gvn.transform(new (C) IfTrueNode(iff_arg))); // (d) Otherwise, go to the slow path. slow_region->add_req(control()); - set_control( _gvn.transform(slow_region) ); + set_control( _gvn.transform(slow_region)); if (stopped()) { // There is no slow path. @@ -3107,7 +3123,7 @@ Node* LibraryCallKit::load_klass_from_mirror_common(Node* mirror, if (region == NULL) never_see_null = true; Node* p = basic_plus_adr(mirror, offset); const TypeKlassPtr* kls_type = TypeKlassPtr::OBJECT_OR_NULL; - Node* kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type) ); + Node* kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, kls_type)); Node* null_ctl = top(); kls = null_check_oop(kls, &null_ctl, never_see_null); if (region != NULL) { @@ -3129,9 +3145,9 @@ Node* LibraryCallKit::generate_access_flags_guard(Node* kls, int modifier_mask, Node* mods = make_load(NULL, modp, TypeInt::INT, T_INT); Node* mask = intcon(modifier_mask); Node* bits = intcon(modifier_bits); - Node* mbit = _gvn.transform( new (C) AndINode(mods, mask) ); - Node* cmp = _gvn.transform( new (C) CmpINode(mbit, bits) ); - Node* bol = _gvn.transform( new (C) BoolNode(cmp, BoolTest::ne) ); + Node* mbit = _gvn.transform(new (C) AndINode(mods, mask)); + Node* cmp = _gvn.transform(new (C) CmpINode(mbit, bits)); + Node* bol = _gvn.transform(new (C) BoolNode(cmp, BoolTest::ne)); return generate_fair_guard(bol, region); } Node* LibraryCallKit::generate_interface_guard(Node* kls, RegionNode* region) { @@ -3282,7 +3298,7 @@ bool LibraryCallKit::inline_native_Class_query(vmIntrinsics::ID id) { phi->add_req(makecon(TypeInstPtr::make(env()->Object_klass()->java_mirror()))); // If we fall through, it's a plain class. Get its _super. p = basic_plus_adr(kls, in_bytes(Klass::super_offset())); - kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL) ); + kls = _gvn.transform( LoadKlassNode::make(_gvn, immutable_memory(), p, TypeRawPtr::BOTTOM, TypeKlassPtr::OBJECT_OR_NULL)); null_ctl = top(); kls = null_check_oop(kls, &null_ctl); if (null_ctl != top()) { @@ -3395,8 +3411,8 @@ bool LibraryCallKit::inline_native_subtype_check() { set_control(region->in(_prim_0_path)); // go back to first null check if (!stopped()) { // Since superc is primitive, make a guard for the superc==subc case. - Node* cmp_eq = _gvn.transform( new (C) CmpPNode(args[0], args[1]) ); - Node* bol_eq = _gvn.transform( new (C) BoolNode(cmp_eq, BoolTest::eq) ); + Node* cmp_eq = _gvn.transform(new (C) CmpPNode(args[0], args[1])); + Node* bol_eq = _gvn.transform(new (C) BoolNode(cmp_eq, BoolTest::eq)); generate_guard(bol_eq, region, PROB_FAIR); if (region->req() == PATH_LIMIT+1) { // A guard was added. If the added guard is taken, superc==subc. @@ -3461,11 +3477,11 @@ Node* LibraryCallKit::generate_array_guard_common(Node* kls, RegionNode* region, ? ((jint)Klass::_lh_array_tag_type_value << Klass::_lh_array_tag_shift) : Klass::_lh_neutral_value); - Node* cmp = _gvn.transform( new(C) CmpINode(layout_val, intcon(nval)) ); + Node* cmp = _gvn.transform(new(C) CmpINode(layout_val, intcon(nval))); BoolTest::mask btest = BoolTest::lt; // correct for testing is_[obj]array // invert the test if we are looking for a non-array if (not_array) btest = BoolTest(btest).negate(); - Node* bol = _gvn.transform( new(C) BoolNode(cmp, btest) ); + Node* bol = _gvn.transform(new(C) BoolNode(cmp, btest)); return generate_fair_guard(bol, region); } @@ -3525,7 +3541,7 @@ bool LibraryCallKit::inline_native_newArray() { // Return the combined state. set_i_o( _gvn.transform(result_io) ); - set_all_memory( _gvn.transform(result_mem) ); + set_all_memory( _gvn.transform(result_mem)); C->set_has_split_ifs(true); // Has chance for split-if optimization set_result(result_reg, result_val); @@ -3678,8 +3694,8 @@ Node* LibraryCallKit::generate_virtual_guard(Node* obj_klass, const TypePtr* native_call_addr = TypeMetadataPtr::make(method); Node* native_call = makecon(native_call_addr); - Node* chk_native = _gvn.transform( new(C) CmpPNode(target_call, native_call) ); - Node* test_native = _gvn.transform( new(C) BoolNode(chk_native, BoolTest::ne) ); + Node* chk_native = _gvn.transform(new(C) CmpPNode(target_call, native_call)); + Node* test_native = _gvn.transform(new(C) BoolNode(chk_native, BoolTest::ne)); return generate_slow_guard(test_native, slow_region); } @@ -3800,10 +3816,10 @@ bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) { // Test the header to see if it is unlocked. Node *lock_mask = _gvn.MakeConX(markOopDesc::biased_lock_mask_in_place); - Node *lmasked_header = _gvn.transform( new (C) AndXNode(header, lock_mask) ); + Node *lmasked_header = _gvn.transform(new (C) AndXNode(header, lock_mask)); Node *unlocked_val = _gvn.MakeConX(markOopDesc::unlocked_value); - Node *chk_unlocked = _gvn.transform( new (C) CmpXNode( lmasked_header, unlocked_val)); - Node *test_unlocked = _gvn.transform( new (C) BoolNode( chk_unlocked, BoolTest::ne) ); + Node *chk_unlocked = _gvn.transform(new (C) CmpXNode( lmasked_header, unlocked_val)); + Node *test_unlocked = _gvn.transform(new (C) BoolNode( chk_unlocked, BoolTest::ne)); generate_slow_guard(test_unlocked, slow_region); @@ -3813,17 +3829,17 @@ bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) { // vm: see markOop.hpp. Node *hash_mask = _gvn.intcon(markOopDesc::hash_mask); Node *hash_shift = _gvn.intcon(markOopDesc::hash_shift); - Node *hshifted_header= _gvn.transform( new (C) URShiftXNode(header, hash_shift) ); + Node *hshifted_header= _gvn.transform(new (C) URShiftXNode(header, hash_shift)); // This hack lets the hash bits live anywhere in the mark object now, as long // as the shift drops the relevant bits into the low 32 bits. Note that // Java spec says that HashCode is an int so there's no point in capturing // an 'X'-sized hashcode (32 in 32-bit build or 64 in 64-bit build). hshifted_header = ConvX2I(hshifted_header); - Node *hash_val = _gvn.transform( new (C) AndINode(hshifted_header, hash_mask) ); + Node *hash_val = _gvn.transform(new (C) AndINode(hshifted_header, hash_mask)); Node *no_hash_val = _gvn.intcon(markOopDesc::no_hash); - Node *chk_assigned = _gvn.transform( new (C) CmpINode( hash_val, no_hash_val)); - Node *test_assigned = _gvn.transform( new (C) BoolNode( chk_assigned, BoolTest::eq) ); + Node *chk_assigned = _gvn.transform(new (C) CmpINode( hash_val, no_hash_val)); + Node *test_assigned = _gvn.transform(new (C) BoolNode( chk_assigned, BoolTest::eq)); generate_slow_guard(test_assigned, slow_region); @@ -3854,7 +3870,7 @@ bool LibraryCallKit::inline_native_hashcode(bool is_virtual, bool is_static) { // Return the combined state. set_i_o( _gvn.transform(result_io) ); - set_all_memory( _gvn.transform(result_mem) ); + set_all_memory( _gvn.transform(result_mem)); set_result(result_reg, result_val); return true; @@ -3982,7 +3998,7 @@ bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) { Node *opt_isnan = _gvn.transform(ifisnan); assert( opt_isnan->is_If(), "Expect an IfNode"); IfNode *opt_ifisnan = (IfNode*)opt_isnan; - Node *iftrue = _gvn.transform( new (C) IfTrueNode(opt_ifisnan) ); + Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan)); set_control(iftrue); @@ -4023,7 +4039,7 @@ bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) { Node *opt_isnan = _gvn.transform(ifisnan); assert( opt_isnan->is_If(), "Expect an IfNode"); IfNode *opt_ifisnan = (IfNode*)opt_isnan; - Node *iftrue = _gvn.transform( new (C) IfTrueNode(opt_ifisnan) ); + Node *iftrue = _gvn.transform(new (C) IfTrueNode(opt_ifisnan)); set_control(iftrue); @@ -4152,8 +4168,8 @@ void LibraryCallKit::copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, b // Compute the length also, if needed: Node* countx = size; - countx = _gvn.transform( new (C) SubXNode(countx, MakeConX(base_off)) ); - countx = _gvn.transform( new (C) URShiftXNode(countx, intcon(LogBytesPerLong) )); + countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(base_off))); + countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong) )); const TypePtr* raw_adr_type = TypeRawPtr::BOTTOM; bool disjoint_bases = true; @@ -4357,9 +4373,9 @@ bool LibraryCallKit::inline_native_clone(bool is_virtual) { } // Return the combined state. - set_control( _gvn.transform(result_reg) ); - set_i_o( _gvn.transform(result_i_o) ); - set_all_memory( _gvn.transform(result_mem) ); + set_control( _gvn.transform(result_reg)); + set_i_o( _gvn.transform(result_i_o)); + set_all_memory( _gvn.transform(result_mem)); } // original reexecute is set back here set_result(_gvn.transform(result_val)); @@ -4684,8 +4700,8 @@ LibraryCallKit::generate_arraycopy(const TypePtr* adr_type, // are dest_head = dest[0..off] and dest_tail = dest[off+len..dest.length]. Node* dest_size = alloc->in(AllocateNode::AllocSize); Node* dest_length = alloc->in(AllocateNode::ALength); - Node* dest_tail = _gvn.transform( new(C) AddINode(dest_offset, - copy_length) ); + Node* dest_tail = _gvn.transform(new(C) AddINode(dest_offset, + copy_length)); // If there is a head section that needs zeroing, do it now. if (find_int_con(dest_offset, -1) != 0) { @@ -4701,8 +4717,8 @@ LibraryCallKit::generate_arraycopy(const TypePtr* adr_type, // the copy to a more hardware-friendly word size of 64 bits. Node* tail_ctl = NULL; if (!stopped() && !dest_tail->eqv_uncast(dest_length)) { - Node* cmp_lt = _gvn.transform( new(C) CmpINode(dest_tail, dest_length) ); - Node* bol_lt = _gvn.transform( new(C) BoolNode(cmp_lt, BoolTest::lt) ); + Node* cmp_lt = _gvn.transform(new(C) CmpINode(dest_tail, dest_length)); + Node* bol_lt = _gvn.transform(new(C) BoolNode(cmp_lt, BoolTest::lt)); tail_ctl = generate_slow_guard(bol_lt, NULL); assert(tail_ctl != NULL || !stopped(), "must be an outcome"); } @@ -4745,7 +4761,7 @@ LibraryCallKit::generate_arraycopy(const TypePtr* adr_type, dest_size); done_ctl->init_req(2, control()); done_mem->init_req(2, memory(adr_type)); - set_control( _gvn.transform(done_ctl) ); + set_control( _gvn.transform(done_ctl)); set_memory( _gvn.transform(done_mem), adr_type ); } } @@ -4832,18 +4848,18 @@ LibraryCallKit::generate_arraycopy(const TypePtr* adr_type, // Clean up after the checked call. // The returned value is either 0 or -1^K, // where K = number of partially transferred array elements. - Node* cmp = _gvn.transform( new(C) CmpINode(checked_value, intcon(0)) ); - Node* bol = _gvn.transform( new(C) BoolNode(cmp, BoolTest::eq) ); + Node* cmp = _gvn.transform(new(C) CmpINode(checked_value, intcon(0))); + Node* bol = _gvn.transform(new(C) BoolNode(cmp, BoolTest::eq)); IfNode* iff = create_and_map_if(control(), bol, PROB_MAX, COUNT_UNKNOWN); // If it is 0, we are done, so transfer to the end. - Node* checks_done = _gvn.transform( new(C) IfTrueNode(iff) ); + Node* checks_done = _gvn.transform(new(C) IfTrueNode(iff)); result_region->init_req(checked_path, checks_done); result_i_o ->init_req(checked_path, checked_i_o); result_memory->init_req(checked_path, checked_mem); // If it is not zero, merge into the slow call. - set_control( _gvn.transform( new(C) IfFalseNode(iff) )); + set_control( _gvn.transform(new(C) IfFalseNode(iff) )); RegionNode* slow_reg2 = new(C) RegionNode(3); PhiNode* slow_i_o2 = new(C) PhiNode(slow_reg2, Type::ABIO); PhiNode* slow_mem2 = new(C) PhiNode(slow_reg2, Type::MEMORY, adr_type); @@ -4866,16 +4882,16 @@ LibraryCallKit::generate_arraycopy(const TypePtr* adr_type, } else { // We must continue the copy exactly where it failed, or else // another thread might see the wrong number of writes to dest. - Node* checked_offset = _gvn.transform( new(C) XorINode(checked_value, intcon(-1)) ); + Node* checked_offset = _gvn.transform(new(C) XorINode(checked_value, intcon(-1))); Node* slow_offset = new(C) PhiNode(slow_reg2, TypeInt::INT); slow_offset->init_req(1, intcon(0)); slow_offset->init_req(2, checked_offset); slow_offset = _gvn.transform(slow_offset); // Adjust the arguments by the conditionally incoming offset. - Node* src_off_plus = _gvn.transform( new(C) AddINode(src_offset, slow_offset) ); - Node* dest_off_plus = _gvn.transform( new(C) AddINode(dest_offset, slow_offset) ); - Node* length_minus = _gvn.transform( new(C) SubINode(copy_length, slow_offset) ); + Node* src_off_plus = _gvn.transform(new(C) AddINode(src_offset, slow_offset)); + Node* dest_off_plus = _gvn.transform(new(C) AddINode(dest_offset, slow_offset)); + Node* length_minus = _gvn.transform(new(C) SubINode(copy_length, slow_offset)); // Tweak the node variables to adjust the code produced below: src_offset = src_off_plus; @@ -4914,7 +4930,7 @@ LibraryCallKit::generate_arraycopy(const TypePtr* adr_type, } // Finished; return the combined state. - set_control( _gvn.transform(result_region) ); + set_control( _gvn.transform(result_region)); set_i_o( _gvn.transform(result_i_o) ); set_memory( _gvn.transform(result_memory), adr_type ); @@ -5096,10 +5112,10 @@ LibraryCallKit::generate_clear_array(const TypePtr* adr_type, int end_round = (-1 << scale) & (BytesPerLong - 1); Node* end = ConvI2X(slice_len); if (scale != 0) - end = _gvn.transform( new(C) LShiftXNode(end, intcon(scale) )); + end = _gvn.transform(new(C) LShiftXNode(end, intcon(scale) )); end_base += end_round; - end = _gvn.transform( new(C) AddXNode(end, MakeConX(end_base)) ); - end = _gvn.transform( new(C) AndXNode(end, MakeConX(~end_round)) ); + end = _gvn.transform(new(C) AddXNode(end, MakeConX(end_base))); + end = _gvn.transform(new(C) AndXNode(end, MakeConX(~end_round))); mem = ClearArrayNode::clear_memory(control(), mem, dest, start_con, end, &_gvn); } else if (start_con < 0 && dest_size != top()) { @@ -5108,8 +5124,8 @@ LibraryCallKit::generate_clear_array(const TypePtr* adr_type, Node* start = slice_idx; start = ConvI2X(start); if (scale != 0) - start = _gvn.transform( new(C) LShiftXNode( start, intcon(scale) )); - start = _gvn.transform( new(C) AddXNode(start, MakeConX(abase)) ); + start = _gvn.transform(new(C) LShiftXNode( start, intcon(scale) )); + start = _gvn.transform(new(C) AddXNode(start, MakeConX(abase))); if ((bump_bit | clear_low) != 0) { int to_clear = (bump_bit | clear_low); // Align up mod 8, then store a jint zero unconditionally @@ -5120,14 +5136,14 @@ LibraryCallKit::generate_clear_array(const TypePtr* adr_type, assert((abase & to_clear) == 0, "array base must be long-aligned"); } else { // Bump 'start' up to (or past) the next jint boundary: - start = _gvn.transform( new(C) AddXNode(start, MakeConX(bump_bit)) ); + start = _gvn.transform(new(C) AddXNode(start, MakeConX(bump_bit))); assert((abase & clear_low) == 0, "array base must be int-aligned"); } // Round bumped 'start' down to jlong boundary in body of array. - start = _gvn.transform( new(C) AndXNode(start, MakeConX(~to_clear)) ); + start = _gvn.transform(new(C) AndXNode(start, MakeConX(~to_clear))); if (bump_bit != 0) { // Store a zero to the immediately preceding jint: - Node* x1 = _gvn.transform( new(C) AddXNode(start, MakeConX(-bump_bit)) ); + Node* x1 = _gvn.transform(new(C) AddXNode(start, MakeConX(-bump_bit))); Node* p1 = basic_plus_adr(dest, x1); mem = StoreNode::make(_gvn, control(), mem, p1, adr_type, intcon(0), T_INT); mem = _gvn.transform(mem); @@ -5194,8 +5210,8 @@ LibraryCallKit::generate_block_arraycopy(const TypePtr* adr_type, Node* sptr = basic_plus_adr(src, src_off); Node* dptr = basic_plus_adr(dest, dest_off); Node* countx = dest_size; - countx = _gvn.transform( new (C) SubXNode(countx, MakeConX(dest_off)) ); - countx = _gvn.transform( new (C) URShiftXNode(countx, intcon(LogBytesPerLong)) ); + countx = _gvn.transform(new (C) SubXNode(countx, MakeConX(dest_off))); + countx = _gvn.transform(new (C) URShiftXNode(countx, intcon(LogBytesPerLong))); bool disjoint_bases = true; // since alloc != NULL generate_unchecked_arraycopy(adr_type, T_LONG, disjoint_bases, @@ -5360,6 +5376,117 @@ bool LibraryCallKit::inline_encodeISOArray() { return true; } +/** + * Calculate CRC32 for byte. + * int java.util.zip.CRC32.update(int crc, int b) + */ +bool LibraryCallKit::inline_updateCRC32() { + assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support"); + assert(callee()->signature()->size() == 2, "update has 2 parameters"); + // no receiver since it is static method + Node* crc = argument(0); // type: int + Node* b = argument(1); // type: int + + /* + * int c = ~ crc; + * b = timesXtoThe32[(b ^ c) & 0xFF]; + * b = b ^ (c >>> 8); + * crc = ~b; + */ + + Node* M1 = intcon(-1); + crc = _gvn.transform(new (C) XorINode(crc, M1)); + Node* result = _gvn.transform(new (C) XorINode(crc, b)); + result = _gvn.transform(new (C) AndINode(result, intcon(0xFF))); + + Node* base = makecon(TypeRawPtr::make(StubRoutines::crc_table_addr())); + Node* offset = _gvn.transform(new (C) LShiftINode(result, intcon(0x2))); + Node* adr = basic_plus_adr(top(), base, ConvI2X(offset)); + result = make_load(control(), adr, TypeInt::INT, T_INT); + + crc = _gvn.transform(new (C) URShiftINode(crc, intcon(8))); + result = _gvn.transform(new (C) XorINode(crc, result)); + result = _gvn.transform(new (C) XorINode(result, M1)); + set_result(result); + return true; +} + +/** + * Calculate CRC32 for byte[] array. + * int java.util.zip.CRC32.updateBytes(int crc, byte[] buf, int off, int len) + */ +bool LibraryCallKit::inline_updateBytesCRC32() { + assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support"); + assert(callee()->signature()->size() == 4, "updateBytes has 4 parameters"); + // no receiver since it is static method + Node* crc = argument(0); // type: int + Node* src = argument(1); // type: oop + Node* offset = argument(2); // type: int + Node* length = argument(3); // type: int + + const Type* src_type = src->Value(&_gvn); + const TypeAryPtr* top_src = src_type->isa_aryptr(); + if (top_src == NULL || top_src->klass() == NULL) { + // failed array check + return false; + } + + // Figure out the size and type of the elements we will be copying. + BasicType src_elem = src_type->isa_aryptr()->klass()->as_array_klass()->element_type()->basic_type(); + if (src_elem != T_BYTE) { + return false; + } + + // 'src_start' points to src array + scaled offset + Node* src_start = array_element_address(src, offset, src_elem); + + // We assume that range check is done by caller. + // TODO: generate range check (offset+length < src.length) in debug VM. + + // Call the stub. + address stubAddr = StubRoutines::updateBytesCRC32(); + const char *stubName = "updateBytesCRC32"; + + Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(), + stubAddr, stubName, TypePtr::BOTTOM, + crc, src_start, length); + Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms)); + set_result(result); + return true; +} + +/** + * Calculate CRC32 for ByteBuffer. + * int java.util.zip.CRC32.updateByteBuffer(int crc, long buf, int off, int len) + */ +bool LibraryCallKit::inline_updateByteBufferCRC32() { + assert(UseCRC32Intrinsics, "need AVX and LCMUL instructions support"); + assert(callee()->signature()->size() == 5, "updateByteBuffer has 4 parameters and one is long"); + // no receiver since it is static method + Node* crc = argument(0); // type: int + Node* src = argument(1); // type: long + Node* offset = argument(3); // type: int + Node* length = argument(4); // type: int + + src = ConvL2X(src); // adjust Java long to machine word + Node* base = _gvn.transform(new (C) CastX2PNode(src)); + offset = ConvI2X(offset); + + // 'src_start' points to src array + scaled offset + Node* src_start = basic_plus_adr(top(), base, offset); + + // Call the stub. + address stubAddr = StubRoutines::updateBytesCRC32(); + const char *stubName = "updateBytesCRC32"; + + Node* call = make_runtime_call(RC_LEAF|RC_NO_FP, OptoRuntime::updateBytesCRC32_Type(), + stubAddr, stubName, TypePtr::BOTTOM, + crc, src_start, length); + Node* result = _gvn.transform(new (C) ProjNode(call, TypeFunc::Parms)); + set_result(result); + return true; +} + //----------------------------inline_reference_get---------------------------- // public T java.lang.ref.Reference.get(); bool LibraryCallKit::inline_reference_get() { diff --git a/hotspot/src/share/vm/opto/matcher.cpp b/hotspot/src/share/vm/opto/matcher.cpp index 58de9b62587..962c3c12894 100644 --- a/hotspot/src/share/vm/opto/matcher.cpp +++ b/hotspot/src/share/vm/opto/matcher.cpp @@ -2305,26 +2305,26 @@ void Matcher::validate_null_checks( ) { // atomic instruction acting as a store_load barrier without any // intervening volatile load, and thus we don't need a barrier here. // We retain the Node to act as a compiler ordering barrier. -bool Matcher::post_store_load_barrier(const Node *vmb) { - Compile *C = Compile::current(); - assert( vmb->is_MemBar(), "" ); - assert( vmb->Opcode() != Op_MemBarAcquire, "" ); - const MemBarNode *mem = (const MemBarNode*)vmb; +bool Matcher::post_store_load_barrier(const Node* vmb) { + Compile* C = Compile::current(); + assert(vmb->is_MemBar(), ""); + assert(vmb->Opcode() != Op_MemBarAcquire, ""); + const MemBarNode* membar = vmb->as_MemBar(); - // Get the Proj node, ctrl, that can be used to iterate forward - Node *ctrl = NULL; - DUIterator_Fast imax, i = mem->fast_outs(imax); - while( true ) { - ctrl = mem->fast_out(i); // Throw out-of-bounds if proj not found - assert( ctrl->is_Proj(), "only projections here" ); - ProjNode *proj = (ProjNode*)ctrl; - if( proj->_con == TypeFunc::Control && - !C->node_arena()->contains(ctrl) ) // Unmatched old-space only + // Get the Ideal Proj node, ctrl, that can be used to iterate forward + Node* ctrl = NULL; + for (DUIterator_Fast imax, i = membar->fast_outs(imax); i < imax; i++) { + Node* p = membar->fast_out(i); + assert(p->is_Proj(), "only projections here"); + if ((p->as_Proj()->_con == TypeFunc::Control) && + !C->node_arena()->contains(p)) { // Unmatched old-space only + ctrl = p; break; - i++; + } } + assert((ctrl != NULL), "missing control projection"); - for( DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++ ) { + for (DUIterator_Fast jmax, j = ctrl->fast_outs(jmax); j < jmax; j++) { Node *x = ctrl->fast_out(j); int xop = x->Opcode(); @@ -2336,37 +2336,36 @@ bool Matcher::post_store_load_barrier(const Node *vmb) { // that a monitor exit operation contains a serializing instruction. if (xop == Op_MemBarVolatile || - xop == Op_FastLock || xop == Op_CompareAndSwapL || xop == Op_CompareAndSwapP || xop == Op_CompareAndSwapN || - xop == Op_CompareAndSwapI) + xop == Op_CompareAndSwapI) { return true; + } + + // Op_FastLock previously appeared in the Op_* list above. + // With biased locking we're no longer guaranteed that a monitor + // enter operation contains a serializing instruction. + if ((xop == Op_FastLock) && !UseBiasedLocking) { + return true; + } if (x->is_MemBar()) { // We must retain this membar if there is an upcoming volatile - // load, which will be preceded by acquire membar. - if (xop == Op_MemBarAcquire) + // load, which will be followed by acquire membar. + if (xop == Op_MemBarAcquire) { return false; - // For other kinds of barriers, check by pretending we - // are them, and seeing if we can be removed. - else - return post_store_load_barrier((const MemBarNode*)x); + } else { + // For other kinds of barriers, check by pretending we + // are them, and seeing if we can be removed. + return post_store_load_barrier(x->as_MemBar()); + } } - // Delicate code to detect case of an upcoming fastlock block - if( x->is_If() && x->req() > 1 && - !C->node_arena()->contains(x) ) { // Unmatched old-space only - Node *iff = x; - Node *bol = iff->in(1); - // The iff might be some random subclass of If or bol might be Con-Top - if (!bol->is_Bool()) return false; - assert( bol->req() > 1, "" ); - return (bol->in(1)->Opcode() == Op_FastUnlock); - } // probably not necessary to check for these - if (x->is_Call() || x->is_SafePoint() || x->is_block_proj()) + if (x->is_Call() || x->is_SafePoint() || x->is_block_proj()) { return false; + } } return false; } diff --git a/hotspot/src/share/vm/opto/parse3.cpp b/hotspot/src/share/vm/opto/parse3.cpp index acabf4985f5..28eb0580bad 100644 --- a/hotspot/src/share/vm/opto/parse3.cpp +++ b/hotspot/src/share/vm/opto/parse3.cpp @@ -294,25 +294,7 @@ void Parse::do_put_xxx(Node* obj, ciField* field, bool is_field) { // If reference is volatile, prevent following volatiles ops from // floating up before the volatile write. if (is_vol) { - // First place the specific membar for THIS volatile index. This first - // membar is dependent on the store, keeping any other membars generated - // below from floating up past the store. - int adr_idx = C->get_alias_index(adr_type); - insert_mem_bar_volatile(Op_MemBarVolatile, adr_idx, store); - - // Now place a membar for AliasIdxBot for the unknown yet-to-be-parsed - // volatile alias indices. Skip this if the membar is redundant. - if (adr_idx != Compile::AliasIdxBot) { - insert_mem_bar_volatile(Op_MemBarVolatile, Compile::AliasIdxBot, store); - } - - // Finally, place alias-index-specific membars for each volatile index - // that isn't the adr_idx membar. Typically there's only 1 or 2. - for( int i = Compile::AliasIdxRaw; i < C->num_alias_types(); i++ ) { - if (i != adr_idx && C->alias_type(i)->is_volatile()) { - insert_mem_bar_volatile(Op_MemBarVolatile, i, store); - } - } + insert_mem_bar(Op_MemBarVolatile); // Use fat membar } // If the field is final, the rules of Java say we are in or . diff --git a/hotspot/src/share/vm/opto/runtime.cpp b/hotspot/src/share/vm/opto/runtime.cpp index d0aefad66b7..9a278c5ac1c 100644 --- a/hotspot/src/share/vm/opto/runtime.cpp +++ b/hotspot/src/share/vm/opto/runtime.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -829,6 +829,28 @@ const TypeFunc* OptoRuntime::aescrypt_block_Type() { return TypeFunc::make(domain, range); } +/** + * int updateBytesCRC32(int crc, byte* b, int len) + */ +const TypeFunc* OptoRuntime::updateBytesCRC32_Type() { + // create input type (domain) + int num_args = 3; + int argcnt = num_args; + const Type** fields = TypeTuple::fields(argcnt); + int argp = TypeFunc::Parms; + fields[argp++] = TypeInt::INT; // crc + fields[argp++] = TypePtr::NOTNULL; // src + fields[argp++] = TypeInt::INT; // len + assert(argp == TypeFunc::Parms+argcnt, "correct decoding"); + const TypeTuple* domain = TypeTuple::make(TypeFunc::Parms+argcnt, fields); + + // result type needed + fields = TypeTuple::fields(1); + fields[TypeFunc::Parms+0] = TypeInt::INT; // crc result + const TypeTuple* range = TypeTuple::make(TypeFunc::Parms+1, fields); + return TypeFunc::make(domain, range); +} + // for cipherBlockChaining calls of aescrypt encrypt/decrypt, four pointers and a length, returning void const TypeFunc* OptoRuntime::cipherBlockChaining_aescrypt_Type() { // create input type (domain) diff --git a/hotspot/src/share/vm/opto/runtime.hpp b/hotspot/src/share/vm/opto/runtime.hpp index 295b7123757..b3f7ff4cb1a 100644 --- a/hotspot/src/share/vm/opto/runtime.hpp +++ b/hotspot/src/share/vm/opto/runtime.hpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1998, 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 @@ -284,6 +284,8 @@ private: static const TypeFunc* aescrypt_block_Type(); static const TypeFunc* cipherBlockChaining_aescrypt_Type(); + static const TypeFunc* updateBytesCRC32_Type(); + // leaf on stack replacement interpreter accessor types static const TypeFunc* osr_end_Type(); diff --git a/hotspot/src/share/vm/prims/forte.cpp b/hotspot/src/share/vm/prims/forte.cpp index 43da7494417..4b1fbebc137 100644 --- a/hotspot/src/share/vm/prims/forte.cpp +++ b/hotspot/src/share/vm/prims/forte.cpp @@ -31,6 +31,7 @@ #include "oops/oop.inline.hpp" #include "oops/oop.inline2.hpp" #include "prims/forte.hpp" +#include "runtime/javaCalls.hpp" #include "runtime/thread.hpp" #include "runtime/vframe.hpp" #include "runtime/vframeArray.hpp" @@ -308,10 +309,14 @@ static bool find_initial_Java_frame(JavaThread* thread, for (loop_count = 0; loop_count < loop_max; loop_count++) { - if (candidate.is_first_frame()) { + if (candidate.is_entry_frame()) { + // jcw is NULL if the java call wrapper couldn't be found + JavaCallWrapper *jcw = candidate.entry_frame_call_wrapper_if_safe(thread); // If initial frame is frame from StubGenerator and there is no // previous anchor, there are no java frames associated with a method - return false; + if (jcw == NULL || jcw->is_first_frame()) { + return false; + } } if (candidate.is_interpreted_frame()) { diff --git a/hotspot/src/share/vm/prims/jni.cpp b/hotspot/src/share/vm/prims/jni.cpp index 85f3e2e0e41..188cf4a6e60 100644 --- a/hotspot/src/share/vm/prims/jni.cpp +++ b/hotspot/src/share/vm/prims/jni.cpp @@ -879,7 +879,7 @@ JNI_ENTRY(jint, jni_PushLocalFrame(JNIEnv *env, jint capacity)) env, capacity); #endif /* USDT2 */ //%note jni_11 - if (capacity < 0 && capacity > MAX_REASONABLE_LOCAL_CAPACITY) { + if (capacity < 0 || capacity > MAX_REASONABLE_LOCAL_CAPACITY) { #ifndef USDT2 DTRACE_PROBE1(hotspot_jni, PushLocalFrame__return, JNI_ERR); #else /* USDT2 */ @@ -5097,7 +5097,7 @@ _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_CreateJavaVM(JavaVM **vm, void **penv, v // function used to determine this will always return false. Atomic::xchg // does not have this problem. if (Atomic::xchg(1, &vm_created) == 1) { - return JNI_ERR; // already created, or create attempt in progress + return JNI_EEXIST; // already created, or create attempt in progress } if (Atomic::xchg(0, &safe_to_recreate_vm) == 0) { return JNI_ERR; // someone tried and failed and retry not allowed. @@ -5138,9 +5138,21 @@ _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_CreateJavaVM(JavaVM **vm, void **penv, v event.commit(); } +#ifndef PRODUCT + #ifndef TARGET_OS_FAMILY_windows + #define CALL_TEST_FUNC_WITH_WRAPPER_IF_NEEDED(f) f() + #endif + // Check if we should compile all classes on bootclasspath - NOT_PRODUCT(if (CompileTheWorld) ClassLoader::compile_the_world();) - NOT_PRODUCT(if (ReplayCompiles) ciReplay::replay(thread);) + if (CompileTheWorld) ClassLoader::compile_the_world(); + if (ReplayCompiles) ciReplay::replay(thread); + + // Some platforms (like Win*) need a wrapper around these test + // functions in order to properly handle error conditions. + CALL_TEST_FUNC_WITH_WRAPPER_IF_NEEDED(test_error_handler); + CALL_TEST_FUNC_WITH_WRAPPER_IF_NEEDED(execute_internal_vm_tests); +#endif + // Since this is not a JVM_ENTRY we have to set the thread state manually before leaving. ThreadStateTransition::transition_and_fence(thread, _thread_in_vm, _thread_in_native); } else { @@ -5157,8 +5169,6 @@ _JNI_IMPORT_OR_EXPORT_ jint JNICALL JNI_CreateJavaVM(JavaVM **vm, void **penv, v OrderAccess::release_store(&vm_created, 0); } - NOT_PRODUCT(test_error_handler(ErrorHandlerTest)); - NOT_PRODUCT(execute_internal_vm_tests()); return result; } diff --git a/hotspot/src/share/vm/prims/jniCheck.cpp b/hotspot/src/share/vm/prims/jniCheck.cpp index ad738b85ef9..c53bf392e6d 100644 --- a/hotspot/src/share/vm/prims/jniCheck.cpp +++ b/hotspot/src/share/vm/prims/jniCheck.cpp @@ -126,6 +126,7 @@ static const char * fatal_wrong_class_or_method = "Wrong object class or methodI static const char * fatal_non_weak_method = "non-weak methodID passed to JNI call"; static const char * fatal_unknown_array_object = "Unknown array object passed to JNI array operations"; static const char * fatal_object_array_expected = "Object array expected but not received for JNI array operation"; +static const char * fatal_prim_type_array_expected = "Primitive type array expected but not received for JNI array operation"; static const char * fatal_non_array = "Non-array passed to JNI array operations"; static const char * fatal_element_type_mismatch = "Array element type mismatch in JNI"; static const char * fatal_should_be_static = "Non-static field ID passed to JNI"; @@ -278,30 +279,49 @@ checkString(JavaThread* thr, jstring js) ReportJNIFatalError(thr, fatal_non_string); } -static inline void -checkArray(JavaThread* thr, jarray jArray, int elementType) +static inline arrayOop +check_is_array(JavaThread* thr, jarray jArray) { ASSERT_OOPS_ALLOWED; arrayOop aOop; aOop = (arrayOop)jniCheck::validate_object(thr, jArray); - if (aOop == NULL || !aOop->is_array()) + if (aOop == NULL || !aOop->is_array()) { ReportJNIFatalError(thr, fatal_non_array); + } + return aOop; +} - if (elementType != -1) { - if (aOop->is_typeArray()) { - BasicType array_type = TypeArrayKlass::cast(aOop->klass())->element_type(); - if (array_type != elementType) - ReportJNIFatalError(thr, fatal_element_type_mismatch); - } else if (aOop->is_objArray()) { - if ( T_OBJECT != elementType) - ReportJNIFatalError(thr, fatal_object_array_expected); - } else { - ReportJNIFatalError(thr, fatal_unknown_array_object); - } +static inline arrayOop +check_is_primitive_array(JavaThread* thr, jarray jArray) { + arrayOop aOop = check_is_array(thr, jArray); + + if (!aOop->is_typeArray()) { + ReportJNIFatalError(thr, fatal_prim_type_array_expected); + } + return aOop; +} + +static inline void +check_primitive_array_type(JavaThread* thr, jarray jArray, BasicType elementType) +{ + BasicType array_type; + arrayOop aOop; + + aOop = check_is_primitive_array(thr, jArray); + array_type = TypeArrayKlass::cast(aOop->klass())->element_type(); + if (array_type != elementType) { + ReportJNIFatalError(thr, fatal_element_type_mismatch); } } +static inline void +check_is_obj_array(JavaThread* thr, jarray jArray) { + arrayOop aOop = check_is_array(thr, jArray); + if (!aOop->is_objArray()) { + ReportJNIFatalError(thr, fatal_object_array_expected); + } +} oop jniCheck::validate_handle(JavaThread* thr, jobject obj) { if (JNIHandles::is_frame_handle(thr, obj) || @@ -1417,7 +1437,7 @@ JNI_ENTRY_CHECKED(jsize, jarray array)) functionEnter(thr); IN_VM( - checkArray(thr, array, -1); + check_is_array(thr, array); ) jsize result = UNCHECKED()->GetArrayLength(env,array); functionExit(env); @@ -1441,7 +1461,7 @@ JNI_ENTRY_CHECKED(jobject, jsize index)) functionEnter(thr); IN_VM( - checkArray(thr, array, T_OBJECT); + check_is_obj_array(thr, array); ) jobject result = UNCHECKED()->GetObjectArrayElement(env,array,index); functionExit(env); @@ -1455,7 +1475,7 @@ JNI_ENTRY_CHECKED(void, jobject val)) functionEnter(thr); IN_VM( - checkArray(thr, array, T_OBJECT); + check_is_obj_array(thr, array); ) UNCHECKED()->SetObjectArrayElement(env,array,index,val); functionExit(env); @@ -1487,7 +1507,7 @@ JNI_ENTRY_CHECKED(ElementType *, \ jboolean *isCopy)) \ functionEnter(thr); \ IN_VM( \ - checkArray(thr, array, ElementTag); \ + check_primitive_array_type(thr, array, ElementTag); \ ) \ ElementType *result = UNCHECKED()->Get##Result##ArrayElements(env, \ array, \ @@ -1513,7 +1533,7 @@ JNI_ENTRY_CHECKED(void, \ jint mode)) \ functionEnterExceptionAllowed(thr); \ IN_VM( \ - checkArray(thr, array, ElementTag); \ + check_primitive_array_type(thr, array, ElementTag); \ ASSERT_OOPS_ALLOWED; \ typeArrayOop a = typeArrayOop(JNIHandles::resolve_non_null(array)); \ /* cannot check validity of copy, unless every request is logged by @@ -1543,7 +1563,7 @@ JNI_ENTRY_CHECKED(void, \ ElementType *buf)) \ functionEnter(thr); \ IN_VM( \ - checkArray(thr, array, ElementTag); \ + check_primitive_array_type(thr, array, ElementTag); \ ) \ UNCHECKED()->Get##Result##ArrayRegion(env,array,start,len,buf); \ functionExit(env); \ @@ -1567,7 +1587,7 @@ JNI_ENTRY_CHECKED(void, \ const ElementType *buf)) \ functionEnter(thr); \ IN_VM( \ - checkArray(thr, array, ElementTag); \ + check_primitive_array_type(thr, array, ElementTag); \ ) \ UNCHECKED()->Set##Result##ArrayRegion(env,array,start,len,buf); \ functionExit(env); \ @@ -1669,7 +1689,7 @@ JNI_ENTRY_CHECKED(void *, jboolean *isCopy)) functionEnterCritical(thr); IN_VM( - checkArray(thr, array, -1); + check_is_primitive_array(thr, array); ) void *result = UNCHECKED()->GetPrimitiveArrayCritical(env, array, isCopy); functionExit(env); @@ -1683,7 +1703,7 @@ JNI_ENTRY_CHECKED(void, jint mode)) functionEnterCriticalExceptionAllowed(thr); IN_VM( - checkArray(thr, array, -1); + check_is_primitive_array(thr, array); ) /* The Hotspot JNI code does not use the parameters, so just check the * array parameter as a minor sanity check diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp index da34f2e1316..caed2d13612 100644 --- a/hotspot/src/share/vm/prims/jvm.cpp +++ b/hotspot/src/share/vm/prims/jvm.cpp @@ -1121,26 +1121,6 @@ JVM_ENTRY(jobject, JVM_GetProtectionDomain(JNIEnv *env, jclass cls)) JVM_END -// Obsolete since 1.2 (Class.setProtectionDomain removed), although -// still defined in core libraries as of 1.5. -JVM_ENTRY(void, JVM_SetProtectionDomain(JNIEnv *env, jclass cls, jobject protection_domain)) - JVMWrapper("JVM_SetProtectionDomain"); - if (JNIHandles::resolve(cls) == NULL) { - THROW(vmSymbols::java_lang_NullPointerException()); - } - if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) { - // Call is ignored for primitive types - Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls)); - - // cls won't be an array, as this called only from ClassLoader.defineClass - if (k->oop_is_instance()) { - oop pd = JNIHandles::resolve(protection_domain); - assert(pd == NULL || pd->is_oop(), "just checking"); - java_lang_Class::set_protection_domain(k->java_mirror(), pd); - } - } -JVM_END - static bool is_authorized(Handle context, instanceKlassHandle klass, TRAPS) { // If there is a security manager and protection domain, check the access // in the protection domain, otherwise it is authorized. diff --git a/hotspot/src/share/vm/prims/jvm.h b/hotspot/src/share/vm/prims/jvm.h index 486b13531af..6248f4d793d 100644 --- a/hotspot/src/share/vm/prims/jvm.h +++ b/hotspot/src/share/vm/prims/jvm.h @@ -471,9 +471,6 @@ JVM_SetClassSigners(JNIEnv *env, jclass cls, jobjectArray signers); JNIEXPORT jobject JNICALL JVM_GetProtectionDomain(JNIEnv *env, jclass cls); -JNIEXPORT void JNICALL -JVM_SetProtectionDomain(JNIEnv *env, jclass cls, jobject protection_domain); - JNIEXPORT jboolean JNICALL JVM_IsArrayClass(JNIEnv *env, jclass cls); diff --git a/hotspot/src/share/vm/prims/jvmtiExport.cpp b/hotspot/src/share/vm/prims/jvmtiExport.cpp index f20dd4e492a..e823f376ad8 100644 --- a/hotspot/src/share/vm/prims/jvmtiExport.cpp +++ b/hotspot/src/share/vm/prims/jvmtiExport.cpp @@ -41,6 +41,7 @@ #include "prims/jvmtiRawMonitor.hpp" #include "prims/jvmtiTagMap.hpp" #include "prims/jvmtiThreadState.inline.hpp" +#include "prims/jvmtiRedefineClasses.hpp" #include "runtime/arguments.hpp" #include "runtime/handles.hpp" #include "runtime/interfaceSupport.hpp" @@ -516,8 +517,7 @@ class JvmtiClassFileLoadHookPoster : public StackObj { jint _curr_len; unsigned char * _curr_data; JvmtiEnv * _curr_env; - jint * _cached_length_ptr; - unsigned char ** _cached_data_ptr; + JvmtiCachedClassFileData ** _cached_class_file_ptr; JvmtiThreadState * _state; KlassHandle * _h_class_being_redefined; JvmtiClassLoadKind _load_kind; @@ -526,8 +526,7 @@ class JvmtiClassFileLoadHookPoster : public StackObj { inline JvmtiClassFileLoadHookPoster(Symbol* h_name, Handle class_loader, Handle h_protection_domain, unsigned char **data_ptr, unsigned char **end_ptr, - unsigned char **cached_data_ptr, - jint *cached_length_ptr) { + JvmtiCachedClassFileData **cache_ptr) { _h_name = h_name; _class_loader = class_loader; _h_protection_domain = h_protection_domain; @@ -537,8 +536,7 @@ class JvmtiClassFileLoadHookPoster : public StackObj { _curr_len = *end_ptr - *data_ptr; _curr_data = *data_ptr; _curr_env = NULL; - _cached_length_ptr = cached_length_ptr; - _cached_data_ptr = cached_data_ptr; + _cached_class_file_ptr = cache_ptr; _state = _thread->jvmti_thread_state(); if (_state != NULL) { @@ -615,15 +613,20 @@ class JvmtiClassFileLoadHookPoster : public StackObj { } if (new_data != NULL) { // this agent has modified class data. - if (caching_needed && *_cached_data_ptr == NULL) { + if (caching_needed && *_cached_class_file_ptr == NULL) { // data has been changed by the new retransformable agent // and it hasn't already been cached, cache it - *_cached_data_ptr = (unsigned char *)os::malloc(_curr_len, mtInternal); - if (*_cached_data_ptr == NULL) { - vm_exit_out_of_memory(_curr_len, OOM_MALLOC_ERROR, "unable to allocate cached copy of original class bytes"); + JvmtiCachedClassFileData *p; + p = (JvmtiCachedClassFileData *)os::malloc( + offset_of(JvmtiCachedClassFileData, data) + _curr_len, mtInternal); + if (p == NULL) { + vm_exit_out_of_memory(offset_of(JvmtiCachedClassFileData, data) + _curr_len, + OOM_MALLOC_ERROR, + "unable to allocate cached copy of original class bytes"); } - memcpy(*_cached_data_ptr, _curr_data, _curr_len); - *_cached_length_ptr = _curr_len; + p->length = _curr_len; + memcpy(p->data, _curr_data, _curr_len); + *_cached_class_file_ptr = p; } if (_curr_data != *_data_ptr) { @@ -662,13 +665,11 @@ void JvmtiExport::post_class_file_load_hook(Symbol* h_name, Handle h_protection_domain, unsigned char **data_ptr, unsigned char **end_ptr, - unsigned char **cached_data_ptr, - jint *cached_length_ptr) { + JvmtiCachedClassFileData **cache_ptr) { JvmtiClassFileLoadHookPoster poster(h_name, class_loader, h_protection_domain, data_ptr, end_ptr, - cached_data_ptr, - cached_length_ptr); + cache_ptr); poster.post(); } diff --git a/hotspot/src/share/vm/prims/jvmtiExport.hpp b/hotspot/src/share/vm/prims/jvmtiExport.hpp index a1e0e0bd44a..dc52a32f8ea 100644 --- a/hotspot/src/share/vm/prims/jvmtiExport.hpp +++ b/hotspot/src/share/vm/prims/jvmtiExport.hpp @@ -323,8 +323,7 @@ class JvmtiExport : public AllStatic { static void post_class_file_load_hook(Symbol* h_name, Handle class_loader, Handle h_protection_domain, unsigned char **data_ptr, unsigned char **end_ptr, - unsigned char **cached_data_ptr, - jint *cached_length_ptr) NOT_JVMTI_RETURN; + JvmtiCachedClassFileData **cache_ptr) NOT_JVMTI_RETURN; static void post_native_method_bind(Method* method, address* function_ptr) NOT_JVMTI_RETURN; static void post_compiled_method_load(nmethod *nm) NOT_JVMTI_RETURN; static void post_dynamic_code_generated(const char *name, const void *code_begin, const void *code_end) NOT_JVMTI_RETURN; diff --git a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp index e9279697262..877ed0e02fb 100644 --- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp +++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.cpp @@ -3342,9 +3342,7 @@ void VM_RedefineClasses::redefine_single_class(jclass the_jclass, // should get cleared in the_class too. if (the_class->get_cached_class_file_bytes() == 0) { // the_class doesn't have a cache yet so copy it - the_class->set_cached_class_file( - scratch_class->get_cached_class_file_bytes(), - scratch_class->get_cached_class_file_len()); + the_class->set_cached_class_file(scratch_class->get_cached_class_file()); } #ifndef PRODUCT else { @@ -3357,7 +3355,7 @@ void VM_RedefineClasses::redefine_single_class(jclass the_jclass, // NULL out in scratch class to not delete twice. The class to be redefined // always owns these bytes. - scratch_class->set_cached_class_file(NULL, 0); + scratch_class->set_cached_class_file(NULL); // Replace inner_classes Array* old_inner_classes = the_class->inner_classes(); diff --git a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp index 3457e935bd8..97aa8143e66 100644 --- a/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp +++ b/hotspot/src/share/vm/prims/jvmtiRedefineClasses.hpp @@ -331,6 +331,11 @@ // coordinate a cleanup of these constants with Runtime. // +struct JvmtiCachedClassFileData { + jint length; + unsigned char data[1]; +}; + class VM_RedefineClasses: public VM_Operation { private: // These static fields are needed by ClassLoaderDataGraph::classes_do() @@ -509,5 +514,12 @@ class VM_RedefineClasses: public VM_Operation { // Modifiable test must be shared between IsModifiableClass query // and redefine implementation static bool is_modifiable_class(oop klass_mirror); + + static jint get_cached_class_file_len(JvmtiCachedClassFileData *cache) { + return cache == NULL ? 0 : cache->length; + } + static unsigned char * get_cached_class_file_bytes(JvmtiCachedClassFileData *cache) { + return cache == NULL ? NULL : cache->data; + } }; #endif // SHARE_VM_PRIMS_JVMTIREDEFINECLASSES_HPP diff --git a/hotspot/src/share/vm/prims/methodHandles.cpp b/hotspot/src/share/vm/prims/methodHandles.cpp index bb9da0034e4..ac1c796eb31 100644 --- a/hotspot/src/share/vm/prims/methodHandles.cpp +++ b/hotspot/src/share/vm/prims/methodHandles.cpp @@ -1137,7 +1137,12 @@ JVM_ENTRY(jobject, MHN_resolve_Mem(JNIEnv *env, jobject igcls, jobject mname_jh, if (VerifyMethodHandles && caller_jh != NULL && java_lang_invoke_MemberName::clazz(mname()) != NULL) { Klass* reference_klass = java_lang_Class::as_Klass(java_lang_invoke_MemberName::clazz(mname())); - if (reference_klass != NULL) { + if (reference_klass != NULL && reference_klass->oop_is_objArray()) { + reference_klass = ObjArrayKlass::cast(reference_klass)->bottom_klass(); + } + + // Reflection::verify_class_access can only handle instance classes. + if (reference_klass != NULL && reference_klass->oop_is_instance()) { // Emulate LinkResolver::check_klass_accessability. Klass* caller = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh)); if (!Reflection::verify_class_access(caller, diff --git a/hotspot/src/share/vm/runtime/aprofiler.cpp b/hotspot/src/share/vm/runtime/aprofiler.cpp deleted file mode 100644 index e71bfb587ef..00000000000 --- a/hotspot/src/share/vm/runtime/aprofiler.cpp +++ /dev/null @@ -1,143 +0,0 @@ -/* - * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved. - * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. - * - * This code is free software; you can redistribute it and/or modify it - * under the terms of the GNU General Public License version 2 only, as - * published by the Free Software Foundation. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - * - */ - -#include "precompiled.hpp" -#include "classfile/systemDictionary.hpp" -#include "gc_interface/collectedHeap.inline.hpp" -#include "memory/resourceArea.hpp" -#include "memory/space.hpp" -#include "oops/oop.inline.hpp" -#include "oops/oop.inline2.hpp" -#include "runtime/aprofiler.hpp" - - -bool AllocationProfiler::_active = false; -GrowableArray* AllocationProfiler::_print_array = NULL; - - -class AllocProfClosure : public ObjectClosure { - public: - void do_object(oop obj) { - Klass* k = obj->klass(); - k->set_alloc_count(k->alloc_count() + 1); - k->set_alloc_size(k->alloc_size() + obj->size()); - } -}; - - -void AllocationProfiler::iterate_since_last_gc() { - if (is_active()) { - AllocProfClosure blk; - GenCollectedHeap* heap = GenCollectedHeap::heap(); - heap->object_iterate_since_last_GC(&blk); - } -} - - -void AllocationProfiler::engage() { - _active = true; -} - - -void AllocationProfiler::disengage() { - _active = false; -} - - -void AllocationProfiler::add_class_to_array(Klass* k) { - _print_array->append(k); -} - - -void AllocationProfiler::add_classes_to_array(Klass* k) { - // Iterate over klass and all array klasses for klass - k->with_array_klasses_do(&AllocationProfiler::add_class_to_array); -} - - -int AllocationProfiler::compare_classes(Klass** k1, Klass** k2) { - // Sort by total allocation size - return (*k2)->alloc_size() - (*k1)->alloc_size(); -} - - -int AllocationProfiler::average(size_t alloc_size, int alloc_count) { - return (int) ((double) (alloc_size * BytesPerWord) / MAX2(alloc_count, 1) + 0.5); -} - - -void AllocationProfiler::sort_and_print_array(size_t cutoff) { - _print_array->sort(&AllocationProfiler::compare_classes); - tty->print_cr("________________Size" - "__Instances" - "__Average" - "__Class________________"); - size_t total_alloc_size = 0; - int total_alloc_count = 0; - for (int index = 0; index < _print_array->length(); index++) { - Klass* k = _print_array->at(index); - size_t alloc_size = k->alloc_size(); - if (alloc_size > cutoff) { - int alloc_count = k->alloc_count(); -#ifdef PRODUCT - const char* name = k->external_name(); -#else - const char* name = k->internal_name(); -#endif - tty->print_cr("%20u %10u %8u %s", - alloc_size * BytesPerWord, - alloc_count, - average(alloc_size, alloc_count), - name); - total_alloc_size += alloc_size; - total_alloc_count += alloc_count; - } - k->set_alloc_count(0); - k->set_alloc_size(0); - } - tty->print_cr("%20u %10u %8u --total--", - total_alloc_size * BytesPerWord, - total_alloc_count, - average(total_alloc_size, total_alloc_count)); - tty->cr(); -} - - -void AllocationProfiler::print(size_t cutoff) { - ResourceMark rm; - assert(!is_active(), "AllocationProfiler cannot be active while printing profile"); - - tty->cr(); - tty->print_cr("Allocation profile (sizes in bytes, cutoff = " SIZE_FORMAT " bytes):", cutoff * BytesPerWord); - tty->cr(); - - // Print regular instance klasses and basic type array klasses - _print_array = new GrowableArray(SystemDictionary::number_of_classes()*2); - SystemDictionary::classes_do(&add_classes_to_array); - Universe::basic_type_classes_do(&add_classes_to_array); - sort_and_print_array(cutoff); - - // This used to print metadata in the permgen but since there isn't a permgen - // anymore, it is not yet implemented. -} diff --git a/hotspot/src/share/vm/runtime/aprofiler.hpp b/hotspot/src/share/vm/runtime/aprofiler.hpp deleted file mode 100644 index ba4dd7aa5c4..00000000000 --- a/hotspot/src/share/vm/runtime/aprofiler.hpp +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Copyright (c) 1997, 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. - * - * This code is distributed in the hope that it will be useful, but WITHOUT - * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or - * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License - * version 2 for more details (a copy is included in the LICENSE file that - * accompanied this code). - * - * You should have received a copy of the GNU General Public License version - * 2 along with this work; if not, write to the Free Software Foundation, - * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. - * - * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA - * or visit www.oracle.com if you need additional information or have any - * questions. - * - */ - -#ifndef SHARE_VM_RUNTIME_APROFILER_HPP -#define SHARE_VM_RUNTIME_APROFILER_HPP - -#include "memory/allocation.hpp" -#include "memory/universe.hpp" -#include "oops/klass.hpp" -#include "utilities/top.hpp" - -// A simple allocation profiler for Java. The profiler collects and prints -// the number and total size of instances allocated per class, including -// array classes. -// -// The profiler is currently global for all threads. It can be changed to a -// per threads profiler by keeping a more elaborate data structure and calling -// iterate_since_last_scavenge at thread switches. - - -class AllocationProfiler: AllStatic { - friend class GenCollectedHeap; - friend class G1CollectedHeap; - friend class MarkSweep; - private: - static bool _active; // tells whether profiler is active - static GrowableArray* _print_array; // temporary array for printing - - // Utility printing functions - static void add_class_to_array(Klass* k); - static void add_classes_to_array(Klass* k); - static int compare_classes(Klass** k1, Klass** k2); - static int average(size_t alloc_size, int alloc_count); - static void sort_and_print_array(size_t cutoff); - - // Call for collecting allocation information. Called at scavenge, mark-sweep and disengage. - static void iterate_since_last_gc(); - - public: - // Start profiler - static void engage(); - // Stop profiler - static void disengage(); - // Tells whether profiler is active - static bool is_active() { return _active; } - // Print profile - static void print(size_t cutoff); // Cutoff in total allocation size (in words) -}; - -#endif // SHARE_VM_RUNTIME_APROFILER_HPP diff --git a/hotspot/src/share/vm/runtime/arguments.cpp b/hotspot/src/share/vm/runtime/arguments.cpp index 625feda03f9..5353d36c0e4 100644 --- a/hotspot/src/share/vm/runtime/arguments.cpp +++ b/hotspot/src/share/vm/runtime/arguments.cpp @@ -68,7 +68,6 @@ char* Arguments::_java_command = NULL; SystemProperty* Arguments::_system_properties = NULL; const char* Arguments::_gc_log_filename = NULL; bool Arguments::_has_profile = false; -bool Arguments::_has_alloc_profile = false; uintx Arguments::_min_heap_size = 0; Arguments::Mode Arguments::_mode = _mixed; bool Arguments::_java_compiler = false; @@ -261,6 +260,10 @@ static ObsoleteFlag obsolete_jvm_flags[] = { { "PrintRevisitStats", JDK_Version::jdk(8), JDK_Version::jdk(9) }, { "UseVectoredExceptions", JDK_Version::jdk(8), JDK_Version::jdk(9) }, { "UseSplitVerifier", JDK_Version::jdk(8), JDK_Version::jdk(9) }, + { "UseISM", JDK_Version::jdk(8), JDK_Version::jdk(9) }, + { "UsePermISM", JDK_Version::jdk(8), JDK_Version::jdk(9) }, + { "UseMPSS", JDK_Version::jdk(8), JDK_Version::jdk(9) }, + { "UseStringCache", JDK_Version::jdk(8), JDK_Version::jdk(9) }, #ifdef PRODUCT { "DesiredMethodLimit", JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) }, @@ -849,7 +852,7 @@ bool Arguments::process_argument(const char* arg, arg_len = equal_sign - argname; } - Flag* found_flag = Flag::find_flag((char*)argname, arg_len, true); + Flag* found_flag = Flag::find_flag((const char*)argname, arg_len, true); if (found_flag != NULL) { char locked_message_buf[BUFLEN]; found_flag->get_locked_message(locked_message_buf, BUFLEN); @@ -870,6 +873,14 @@ bool Arguments::process_argument(const char* arg, } else { jio_fprintf(defaultStream::error_stream(), "Unrecognized VM option '%s'\n", argname); + Flag* fuzzy_matched = Flag::fuzzy_match((const char*)argname, arg_len, true); + if (fuzzy_matched != NULL) { + jio_fprintf(defaultStream::error_stream(), + "Did you mean '%s%s%s'?\n", + (fuzzy_matched->is_bool()) ? "(+/-)" : "", + fuzzy_matched->name, + (fuzzy_matched->is_bool()) ? "" : "="); + } } // allow for commandline "commenting out" options like -XX:#+Verbose @@ -1571,7 +1582,9 @@ void Arguments::set_heap_base_min_address() { // By default HeapBaseMinAddress is 2G on all platforms except Solaris x86. // G1 currently needs a lot of C-heap, so on Solaris we have to give G1 // some extra space for the C-heap compared to other collectors. - FLAG_SET_ERGO(uintx, HeapBaseMinAddress, 1*G); + // Use FLAG_SET_DEFAULT here rather than FLAG_SET_ERGO to make sure that + // code that checks for default values work correctly. + FLAG_SET_DEFAULT(HeapBaseMinAddress, 1*G); } } @@ -1845,8 +1858,13 @@ bool Arguments::check_gc_consistency() { "please refer to the release notes for the combinations " "allowed\n"); status = false; + } else if (ReservedCodeCacheSize > 2*G) { + // Code cache size larger than MAXINT is not supported. + jio_fprintf(defaultStream::error_stream(), + "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M, + (2*G)/M); + status = false; } - return status; } @@ -1976,23 +1994,6 @@ bool Arguments::check_vm_args_consistency() { status = status && check_gc_consistency(); status = status && check_stack_pages(); - if (_has_alloc_profile) { - if (UseParallelGC || UseParallelOldGC) { - jio_fprintf(defaultStream::error_stream(), - "error: invalid argument combination.\n" - "Allocation profiling (-Xaprof) cannot be used together with " - "Parallel GC (-XX:+UseParallelGC or -XX:+UseParallelOldGC).\n"); - status = false; - } - if (UseConcMarkSweepGC) { - jio_fprintf(defaultStream::error_stream(), - "error: invalid argument combination.\n" - "Allocation profiling (-Xaprof) cannot be used together with " - "the CMS collector (-XX:+UseConcMarkSweepGC).\n"); - status = false; - } - } - if (CMSIncrementalMode) { if (!UseConcMarkSweepGC) { jio_fprintf(defaultStream::error_stream(), @@ -2211,13 +2212,31 @@ bool Arguments::check_vm_args_consistency() { status = false; } - if (ReservedCodeCacheSize < InitialCodeCacheSize) { + // Check lower bounds of the code cache + // Template Interpreter code is approximately 3X larger in debug builds. + uint min_code_cache_size = (CodeCacheMinimumUseSpace DEBUG_ONLY(* 3)) + CodeCacheMinimumFreeSpace; + if (InitialCodeCacheSize < (uintx)os::vm_page_size()) { jio_fprintf(defaultStream::error_stream(), - "Invalid ReservedCodeCacheSize: %dK. Should be greater than InitialCodeCacheSize=%dK\n", + "Invalid InitialCodeCacheSize=%dK. Must be at least %dK.\n", InitialCodeCacheSize/K, + os::vm_page_size()/K); + status = false; + } else if (ReservedCodeCacheSize < InitialCodeCacheSize) { + jio_fprintf(defaultStream::error_stream(), + "Invalid ReservedCodeCacheSize: %dK. Must be at least InitialCodeCacheSize=%dK.\n", ReservedCodeCacheSize/K, InitialCodeCacheSize/K); status = false; + } else if (ReservedCodeCacheSize < min_code_cache_size) { + jio_fprintf(defaultStream::error_stream(), + "Invalid ReservedCodeCacheSize=%dK. Must be at least %uK.\n", ReservedCodeCacheSize/K, + min_code_cache_size/K); + status = false; + } else if (ReservedCodeCacheSize > 2*G) { + // Code cache size larger than MAXINT is not supported. + jio_fprintf(defaultStream::error_stream(), + "Invalid ReservedCodeCacheSize=%dM. Must be at most %uM.\n", ReservedCodeCacheSize/M, + (2*G)/M); + status = false; } - return status; } @@ -2616,10 +2635,20 @@ jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, // -Xoss } else if (match_option(option, "-Xoss", &tail)) { // HotSpot does not have separate native and Java stacks, ignore silently for compatibility - // -Xmaxjitcodesize + } else if (match_option(option, "-XX:CodeCacheExpansionSize=", &tail)) { + julong long_CodeCacheExpansionSize = 0; + ArgsRange errcode = parse_memory_size(tail, &long_CodeCacheExpansionSize, os::vm_page_size()); + if (errcode != arg_in_range) { + jio_fprintf(defaultStream::error_stream(), + "Invalid argument: %s. Must be at least %luK.\n", option->optionString, + os::vm_page_size()/K); + return JNI_EINVAL; + } + FLAG_SET_CMDLINE(uintx, CodeCacheExpansionSize, (uintx)long_CodeCacheExpansionSize); } else if (match_option(option, "-Xmaxjitcodesize", &tail) || match_option(option, "-XX:ReservedCodeCacheSize=", &tail)) { julong long_ReservedCodeCacheSize = 0; + ArgsRange errcode = parse_memory_size(tail, &long_ReservedCodeCacheSize, 1); if (errcode != arg_in_range) { jio_fprintf(defaultStream::error_stream(), @@ -2667,9 +2696,6 @@ jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, "Flat profiling is not supported in this VM.\n"); return JNI_ERR; #endif // INCLUDE_FPROF - // -Xaprof - } else if (match_option(option, "-Xaprof", &tail)) { - _has_alloc_profile = true; // -Xconcurrentio } else if (match_option(option, "-Xconcurrentio", &tail)) { FLAG_SET_CMDLINE(bool, UseLWPSynchronization, true); @@ -2924,13 +2950,6 @@ jint Arguments::parse_each_vm_init_arg(const JavaVMInitArgs* args, FLAG_SET_CMDLINE(bool, UseTLAB, true); } else if (match_option(option, "-XX:-UseTLE", &tail)) { FLAG_SET_CMDLINE(bool, UseTLAB, false); -SOLARIS_ONLY( - } else if (match_option(option, "-XX:+UsePermISM", &tail)) { - warning("-XX:+UsePermISM is obsolete."); - FLAG_SET_CMDLINE(bool, UseISM, true); - } else if (match_option(option, "-XX:-UsePermISM", &tail)) { - FLAG_SET_CMDLINE(bool, UseISM, false); -) } else if (match_option(option, "-XX:+DisplayVMOutputToStderr", &tail)) { FLAG_SET_CMDLINE(bool, DisplayVMOutputToStdout, false); FLAG_SET_CMDLINE(bool, DisplayVMOutputToStderr, true); @@ -3103,8 +3122,6 @@ jint Arguments::finalize_vm_init_args(SysClassPath* scp_p, bool scp_assembly_req // Note that large pages are enabled/disabled for both the // Java heap and the code cache. FLAG_SET_DEFAULT(UseLargePages, false); - SOLARIS_ONLY(FLAG_SET_DEFAULT(UseMPSS, false)); - SOLARIS_ONLY(FLAG_SET_DEFAULT(UseISM, false)); } // Tiered compilation is undefined with C1. diff --git a/hotspot/src/share/vm/runtime/arguments.hpp b/hotspot/src/share/vm/runtime/arguments.hpp index 0e84208a218..89b171f0d46 100644 --- a/hotspot/src/share/vm/runtime/arguments.hpp +++ b/hotspot/src/share/vm/runtime/arguments.hpp @@ -262,7 +262,6 @@ class Arguments : AllStatic { // Option flags static bool _has_profile; - static bool _has_alloc_profile; static const char* _gc_log_filename; static uintx _min_heap_size; @@ -464,9 +463,8 @@ class Arguments : AllStatic { // -Xloggc:, if not specified will be NULL static const char* gc_log_filename() { return _gc_log_filename; } - // -Xprof/-Xaprof + // -Xprof static bool has_profile() { return _has_profile; } - static bool has_alloc_profile() { return _has_alloc_profile; } // -Xms, -Xmx static uintx min_heap_size() { return _min_heap_size; } diff --git a/hotspot/src/share/vm/runtime/frame.cpp b/hotspot/src/share/vm/runtime/frame.cpp index 92af92e92eb..9ea7421cf06 100644 --- a/hotspot/src/share/vm/runtime/frame.cpp +++ b/hotspot/src/share/vm/runtime/frame.cpp @@ -221,9 +221,20 @@ bool frame::is_first_java_frame() const { bool frame::entry_frame_is_first() const { - return entry_frame_call_wrapper()->anchor()->last_Java_sp() == NULL; + return entry_frame_call_wrapper()->is_first_frame(); } +JavaCallWrapper* frame::entry_frame_call_wrapper_if_safe(JavaThread* thread) const { + JavaCallWrapper** jcw = entry_frame_call_wrapper_addr(); + address addr = (address) jcw; + + // addr must be within the usable part of the stack + if (thread->is_in_usable_stack(addr)) { + return *jcw; + } + + return NULL; +} bool frame::should_be_deoptimized() const { if (_deopt_state == is_deoptimized || diff --git a/hotspot/src/share/vm/runtime/frame.hpp b/hotspot/src/share/vm/runtime/frame.hpp index 87581ab8da1..096b467b5f8 100644 --- a/hotspot/src/share/vm/runtime/frame.hpp +++ b/hotspot/src/share/vm/runtime/frame.hpp @@ -353,7 +353,9 @@ class frame VALUE_OBJ_CLASS_SPEC { public: // Entry frames - JavaCallWrapper* entry_frame_call_wrapper() const; + JavaCallWrapper* entry_frame_call_wrapper() const { return *entry_frame_call_wrapper_addr(); } + JavaCallWrapper* entry_frame_call_wrapper_if_safe(JavaThread* thread) const; + JavaCallWrapper** entry_frame_call_wrapper_addr() const; intptr_t* entry_frame_argument_at(int offset) const; // tells whether there is another chunk of Delta stack above diff --git a/hotspot/src/share/vm/runtime/globals.cpp b/hotspot/src/share/vm/runtime/globals.cpp index b45e15c9560..a6c47bfe1de 100644 --- a/hotspot/src/share/vm/runtime/globals.cpp +++ b/hotspot/src/share/vm/runtime/globals.cpp @@ -276,14 +276,14 @@ static Flag flagTable[] = { Flag* Flag::flags = flagTable; size_t Flag::numFlags = (sizeof(flagTable) / sizeof(Flag)); -inline bool str_equal(const char* s, char* q, size_t len) { +inline bool str_equal(const char* s, const char* q, size_t len) { // s is null terminated, q is not! if (strlen(s) != (unsigned int) len) return false; return strncmp(s, q, len) == 0; } // Search the flag table for a named flag -Flag* Flag::find_flag(char* name, size_t length, bool allow_locked) { +Flag* Flag::find_flag(const char* name, size_t length, bool allow_locked) { for (Flag* current = &flagTable[0]; current->name != NULL; current++) { if (str_equal(current->name, name, length)) { // Found a matching entry. Report locked flags only if allowed. @@ -301,6 +301,52 @@ Flag* Flag::find_flag(char* name, size_t length, bool allow_locked) { return NULL; } +// Compute string similarity based on Dice's coefficient +static float str_similar(const char* str1, const char* str2, size_t len2) { + int len1 = (int) strlen(str1); + int total = len1 + (int) len2; + + int hit = 0; + + for (int i = 0; i < len1 -1; ++i) { + for (int j = 0; j < (int) len2 -1; ++j) { + if ((str1[i] == str2[j]) && (str1[i+1] == str2[j+1])) { + ++hit; + break; + } + } + } + + return 2.0f * (float) hit / (float) total; +} + +Flag* Flag::fuzzy_match(const char* name, size_t length, bool allow_locked) { + float VMOptionsFuzzyMatchSimilarity = 0.7f; + Flag* match = NULL; + float score; + float max_score = -1; + + for (Flag* current = &flagTable[0]; current->name != NULL; current++) { + score = str_similar(current->name, name, length); + if (score > max_score) { + max_score = score; + match = current; + } + } + + if (!(match->is_unlocked() || match->is_unlocker())) { + if (!allow_locked) { + return NULL; + } + } + + if (max_score < VMOptionsFuzzyMatchSimilarity) { + return NULL; + } + + return match; +} + // Returns the address of the index'th element static Flag* address_of_flag(CommandLineFlagWithType flag) { assert((size_t)flag < Flag::numFlags, "bad command line flag index"); diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp index b1adcf7fce1..3a8a4493cc1 100644 --- a/hotspot/src/share/vm/runtime/globals.hpp +++ b/hotspot/src/share/vm/runtime/globals.hpp @@ -175,6 +175,7 @@ define_pd_global(intx, InitialCodeCacheSize, 160*K); define_pd_global(intx, ReservedCodeCacheSize, 32*M); define_pd_global(intx, CodeCacheExpansionSize, 32*K); define_pd_global(intx, CodeCacheMinBlockLength, 1); +define_pd_global(intx, CodeCacheMinimumUseSpace, 200*K); define_pd_global(uintx,MetaspaceSize, ScaleForWordSize(4*M)); define_pd_global(bool, NeverActAsServerClassMachine, true); define_pd_global(uint64_t,MaxRAM, 1ULL*G); @@ -220,7 +221,8 @@ struct Flag { // number of flags static size_t numFlags; - static Flag* find_flag(char* name, size_t length, bool allow_locked = false); + static Flag* find_flag(const char* name, size_t length, bool allow_locked = false); + static Flag* fuzzy_match(const char* name, size_t length, bool allow_locked = false); bool is_bool() const { return strcmp(type, "bool") == 0; } bool get_bool() const { return *((bool*) addr); } @@ -644,6 +646,9 @@ class CommandLineFlags { product(bool, UseAESIntrinsics, false, \ "use intrinsics for AES versions of crypto") \ \ + product(bool, UseCRC32Intrinsics, false, \ + "use intrinsics for java.util.zip.CRC32") \ + \ develop(bool, TraceCallFixup, false, \ "traces all call fixups") \ \ @@ -2584,9 +2589,6 @@ class CommandLineFlags { product(bool, AggressiveOpts, false, \ "Enable aggressive optimizations - see arguments.cpp") \ \ - product(bool, UseStringCache, false, \ - "Enable String cache capabilities on String.java") \ - \ /* statistics */ \ develop(bool, CountCompiledCalls, false, \ "counts method invocations") \ @@ -3160,6 +3162,9 @@ class CommandLineFlags { product_pd(uintx, InitialCodeCacheSize, \ "Initial code cache size (in bytes)") \ \ + develop_pd(uintx, CodeCacheMinimumUseSpace, \ + "Minimum code cache size (in bytes) required to start VM.") \ + \ product_pd(uintx, ReservedCodeCacheSize, \ "Reserved code cache size (in bytes) - maximum code cache size") \ \ @@ -3672,6 +3677,9 @@ class CommandLineFlags { develop(bool, VerifyGenericSignatures, false, \ "Abort VM on erroneous or inconsistent generic signatures") \ \ + product(bool, ParseGenericDefaults, false, \ + "Parse generic signatures for default method handling") \ + \ product(bool, UseVMInterruptibleIO, false, \ "(Unstable, Solaris-specific) Thread interrupt before or with " \ "EINTR for I/O operations results in OS_INTRPT. The default value"\ diff --git a/hotspot/src/share/vm/runtime/handles.hpp b/hotspot/src/share/vm/runtime/handles.hpp index 82506bd7049..4a2a90c74c0 100644 --- a/hotspot/src/share/vm/runtime/handles.hpp +++ b/hotspot/src/share/vm/runtime/handles.hpp @@ -227,7 +227,7 @@ class HandleArea: public Arena { HandleArea* _prev; // link to outer (older) area public: // Constructor - HandleArea(HandleArea* prev) { + HandleArea(HandleArea* prev) : Arena(Chunk::tiny_size) { debug_only(_handle_mark_nesting = 0); debug_only(_no_handle_mark_nesting = 0); _prev = prev; diff --git a/hotspot/src/share/vm/runtime/java.cpp b/hotspot/src/share/vm/runtime/java.cpp index 7795fb92a87..ebc4e087578 100644 --- a/hotspot/src/share/vm/runtime/java.cpp +++ b/hotspot/src/share/vm/runtime/java.cpp @@ -42,7 +42,6 @@ #include "oops/oop.inline.hpp" #include "oops/symbol.hpp" #include "prims/jvmtiExport.hpp" -#include "runtime/aprofiler.hpp" #include "runtime/arguments.hpp" #include "runtime/biasedLocking.hpp" #include "runtime/compilationPolicy.hpp" @@ -509,16 +508,6 @@ void before_exit(JavaThread * thread) { } } - - if (Arguments::has_alloc_profile()) { - HandleMark hm; - // Do one last collection to enumerate all the objects - // allocated since the last one. - Universe::heap()->collect(GCCause::_allocation_profiler); - AllocationProfiler::disengage(); - AllocationProfiler::print(0); - } - if (PrintBytecodeHistogram) { BytecodeHistogram::print(); } diff --git a/hotspot/src/share/vm/runtime/javaCalls.hpp b/hotspot/src/share/vm/runtime/javaCalls.hpp index 08881fcbb88..7c397d9f4a9 100644 --- a/hotspot/src/share/vm/runtime/javaCalls.hpp +++ b/hotspot/src/share/vm/runtime/javaCalls.hpp @@ -80,6 +80,8 @@ class JavaCallWrapper: StackObj { oop receiver() { return _receiver; } void oops_do(OopClosure* f); + bool is_first_frame() const { return _anchor.last_Java_sp() == NULL; } + }; diff --git a/hotspot/src/share/vm/runtime/mutex.cpp b/hotspot/src/share/vm/runtime/mutex.cpp index 10d91fa37c4..7adc19f7a7c 100644 --- a/hotspot/src/share/vm/runtime/mutex.cpp +++ b/hotspot/src/share/vm/runtime/mutex.cpp @@ -1370,6 +1370,10 @@ void Monitor::check_prelock_state(Thread *thread) { debug_only(if (rank() != Mutex::special) \ thread->check_for_valid_safepoint_state(false);) } + if (thread->is_Watcher_thread()) { + assert(!WatcherThread::watcher_thread()->has_crash_protection(), + "locking not allowed when crash protection is set"); + } } void Monitor::check_block_state(Thread *thread) { diff --git a/hotspot/src/share/vm/runtime/os.cpp b/hotspot/src/share/vm/runtime/os.cpp index 93a60cd06d6..a16c85785d3 100644 --- a/hotspot/src/share/vm/runtime/os.cpp +++ b/hotspot/src/share/vm/runtime/os.cpp @@ -595,6 +595,22 @@ void* os::malloc(size_t size, MEMFLAGS memflags, address caller) { NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1)); NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size)); +#ifdef ASSERT + // checking for the WatcherThread and crash_protection first + // since os::malloc can be called when the libjvm.{dll,so} is + // first loaded and we don't have a thread yet. + // try to find the thread after we see that the watcher thread + // exists and has crash protection. + WatcherThread *wt = WatcherThread::watcher_thread(); + if (wt != NULL && wt->has_crash_protection()) { + Thread* thread = ThreadLocalStorage::get_thread_slow(); + if (thread == wt) { + assert(!wt->has_crash_protection(), + "Can't malloc with crash protection from WatcherThread"); + } + } +#endif + if (size == 0) { // return a valid pointer if size is zero // if NULL is returned the calling functions assume out of memory. diff --git a/hotspot/src/share/vm/runtime/os.hpp b/hotspot/src/share/vm/runtime/os.hpp index e1866919df4..03497e1973b 100644 --- a/hotspot/src/share/vm/runtime/os.hpp +++ b/hotspot/src/share/vm/runtime/os.hpp @@ -32,15 +32,18 @@ #include "utilities/top.hpp" #ifdef TARGET_OS_FAMILY_linux # include "jvm_linux.h" +# include #endif #ifdef TARGET_OS_FAMILY_solaris # include "jvm_solaris.h" +# include #endif #ifdef TARGET_OS_FAMILY_windows # include "jvm_windows.h" #endif #ifdef TARGET_OS_FAMILY_bsd # include "jvm_bsd.h" +# include #endif // os defines the interface to operating system; this includes traditional @@ -507,16 +510,16 @@ class os: AllStatic { // Symbol lookup, find nearest function name; basically it implements // dladdr() for all platforms. Name of the nearest function is copied - // to buf. Distance from its base address is returned as offset. + // to buf. Distance from its base address is optionally returned as offset. // If function name is not found, buf[0] is set to '\0' and offset is - // set to -1. + // set to -1 (if offset is non-NULL). static bool dll_address_to_function_name(address addr, char* buf, int buflen, int* offset); // Locate DLL/DSO. On success, full path of the library is copied to - // buf, and offset is set to be the distance between addr and the - // library's base address. On failure, buf[0] is set to '\0' and - // offset is set to -1. + // buf, and offset is optionally set to be the distance between addr + // and the library's base address. On failure, buf[0] is set to '\0' + // and offset is set to -1 (if offset is non-NULL). static bool dll_address_to_library_name(address addr, char* buf, int buflen, int* offset); @@ -730,6 +733,10 @@ class os: AllStatic { #include "runtime/os_ext.hpp" public: + class CrashProtectionCallback : public StackObj { + public: + virtual void call() = 0; + }; // Platform dependent stuff #ifdef TARGET_OS_FAMILY_linux @@ -908,6 +915,7 @@ class os: AllStatic { char pathSep); static bool set_boot_path(char fileSep, char pathSep); static char** split_path(const char* path, int* n); + }; // Note that "PAUSE" is almost always used with synchronization @@ -915,8 +923,6 @@ class os: AllStatic { // of the global SpinPause() with C linkage. // It'd also be eligible for inlining on many platforms. -extern "C" int SpinPause () ; -extern "C" int SafeFetch32 (int * adr, int errValue) ; -extern "C" intptr_t SafeFetchN (intptr_t * adr, intptr_t errValue) ; +extern "C" int SpinPause(); #endif // SHARE_VM_RUNTIME_OS_HPP diff --git a/hotspot/src/share/vm/runtime/reflection.cpp b/hotspot/src/share/vm/runtime/reflection.cpp index 15869cc5c0e..f06a7f922aa 100644 --- a/hotspot/src/share/vm/runtime/reflection.cpp +++ b/hotspot/src/share/vm/runtime/reflection.cpp @@ -458,7 +458,7 @@ bool Reflection::verify_class_access(Klass* current_class, Klass* new_class, boo // doesn't have a classloader. if ((current_class == NULL) || (current_class == new_class) || - (InstanceKlass::cast(new_class)->is_public()) || + (new_class->is_public()) || is_same_class_package(current_class, new_class)) { return true; } diff --git a/hotspot/src/share/vm/runtime/stubRoutines.cpp b/hotspot/src/share/vm/runtime/stubRoutines.cpp index c559865b821..ff12ca65163 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.cpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1997, 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 @@ -125,6 +125,9 @@ address StubRoutines::_aescrypt_decryptBlock = NULL; address StubRoutines::_cipherBlockChaining_encryptAESCrypt = NULL; address StubRoutines::_cipherBlockChaining_decryptAESCrypt = NULL; +address StubRoutines::_updateBytesCRC32 = NULL; +address StubRoutines::_crc_table_adr = NULL; + double (* StubRoutines::_intrinsic_log )(double) = NULL; double (* StubRoutines::_intrinsic_log10 )(double) = NULL; double (* StubRoutines::_intrinsic_exp )(double) = NULL; @@ -133,6 +136,13 @@ double (* StubRoutines::_intrinsic_sin )(double) = NULL; double (* StubRoutines::_intrinsic_cos )(double) = NULL; double (* StubRoutines::_intrinsic_tan )(double) = NULL; +address StubRoutines::_safefetch32_entry = NULL; +address StubRoutines::_safefetch32_fault_pc = NULL; +address StubRoutines::_safefetch32_continuation_pc = NULL; +address StubRoutines::_safefetchN_entry = NULL; +address StubRoutines::_safefetchN_fault_pc = NULL; +address StubRoutines::_safefetchN_continuation_pc = NULL; + // Initialization // // Note: to break cycle with universe initialization, stubs are generated in two phases. diff --git a/hotspot/src/share/vm/runtime/stubRoutines.hpp b/hotspot/src/share/vm/runtime/stubRoutines.hpp index 7ad66371300..e43e3ab0e7b 100644 --- a/hotspot/src/share/vm/runtime/stubRoutines.hpp +++ b/hotspot/src/share/vm/runtime/stubRoutines.hpp @@ -204,6 +204,9 @@ class StubRoutines: AllStatic { static address _cipherBlockChaining_encryptAESCrypt; static address _cipherBlockChaining_decryptAESCrypt; + static address _updateBytesCRC32; + static address _crc_table_adr; + // These are versions of the java.lang.Math methods which perform // the same operations as the intrinsic version. They are used for // constant folding in the compiler to ensure equivalence. If the @@ -218,6 +221,14 @@ class StubRoutines: AllStatic { static double (*_intrinsic_cos)(double); static double (*_intrinsic_tan)(double); + // Safefetch stubs. + static address _safefetch32_entry; + static address _safefetch32_fault_pc; + static address _safefetch32_continuation_pc; + static address _safefetchN_entry; + static address _safefetchN_fault_pc; + static address _safefetchN_continuation_pc; + public: // Initialization/Testing static void initialize1(); // must happen before universe::genesis @@ -342,6 +353,9 @@ class StubRoutines: AllStatic { static address cipherBlockChaining_encryptAESCrypt() { return _cipherBlockChaining_encryptAESCrypt; } static address cipherBlockChaining_decryptAESCrypt() { return _cipherBlockChaining_decryptAESCrypt; } + static address updateBytesCRC32() { return _updateBytesCRC32; } + static address crc_table_addr() { return _crc_table_adr; } + static address select_fill_function(BasicType t, bool aligned, const char* &name); static address zero_aligned_words() { return _zero_aligned_words; } @@ -375,6 +389,34 @@ class StubRoutines: AllStatic { return _intrinsic_tan(d); } + // + // Safefetch stub support + // + + typedef int (*SafeFetch32Stub)(int* adr, int errValue); + typedef intptr_t (*SafeFetchNStub) (intptr_t* adr, intptr_t errValue); + + static SafeFetch32Stub SafeFetch32_stub() { return CAST_TO_FN_PTR(SafeFetch32Stub, _safefetch32_entry); } + static SafeFetchNStub SafeFetchN_stub() { return CAST_TO_FN_PTR(SafeFetchNStub, _safefetchN_entry); } + + static bool is_safefetch_fault(address pc) { + return pc != NULL && + (pc == _safefetch32_fault_pc || + pc == _safefetchN_fault_pc); + } + + static address continuation_for_safefetch_fault(address pc) { + assert(_safefetch32_continuation_pc != NULL && + _safefetchN_continuation_pc != NULL, + "not initialized"); + + if (pc == _safefetch32_fault_pc) return _safefetch32_continuation_pc; + if (pc == _safefetchN_fault_pc) return _safefetchN_continuation_pc; + + ShouldNotReachHere(); + return NULL; + } + // // Default versions of the above arraycopy functions for platforms which do // not have specialized versions @@ -394,4 +436,15 @@ class StubRoutines: AllStatic { static void arrayof_oop_copy_uninit(HeapWord* src, HeapWord* dest, size_t count); }; +// Safefetch allows to load a value from a location that's not known +// to be valid. If the load causes a fault, the error value is returned. +inline int SafeFetch32(int* adr, int errValue) { + assert(StubRoutines::SafeFetch32_stub(), "stub not yet generated"); + return StubRoutines::SafeFetch32_stub()(adr, errValue); +} +inline intptr_t SafeFetchN(intptr_t* adr, intptr_t errValue) { + assert(StubRoutines::SafeFetchN_stub(), "stub not yet generated"); + return StubRoutines::SafeFetchN_stub()(adr, errValue); +} + #endif // SHARE_VM_RUNTIME_STUBROUTINES_HPP diff --git a/hotspot/src/share/vm/runtime/thread.cpp b/hotspot/src/share/vm/runtime/thread.cpp index eb2e256b1a0..bbb9a47c221 100644 --- a/hotspot/src/share/vm/runtime/thread.cpp +++ b/hotspot/src/share/vm/runtime/thread.cpp @@ -45,7 +45,6 @@ #include "prims/jvmtiExport.hpp" #include "prims/jvmtiThreadState.hpp" #include "prims/privilegedStack.hpp" -#include "runtime/aprofiler.hpp" #include "runtime/arguments.hpp" #include "runtime/biasedLocking.hpp" #include "runtime/deoptimization.hpp" @@ -219,6 +218,7 @@ Thread::Thread() { // allocated data structures set_osthread(NULL); set_resource_area(new (mtThread)ResourceArea()); + DEBUG_ONLY(_current_resource_mark = NULL;) set_handle_area(new (mtThread) HandleArea(NULL)); set_metadata_handles(new (ResourceObj::C_HEAP, mtClass) GrowableArray(30, true)); set_active_handles(NULL); @@ -954,6 +954,14 @@ bool Thread::is_in_stack(address adr) const { } +bool Thread::is_in_usable_stack(address adr) const { + size_t stack_guard_size = os::uses_stack_guard_pages() ? (StackYellowPages + StackRedPages) * os::vm_page_size() : 0; + size_t usable_stack_size = _stack_size - stack_guard_size; + + return ((adr < stack_base()) && (adr >= stack_base() - usable_stack_size)); +} + + // We had to move these methods here, because vm threads get into ObjectSynchronizer::enter // However, there is a note in JavaThread::is_lock_owned() about the VM threads not being // used for compilation in the future. If that change is made, the need for these methods @@ -1218,7 +1226,7 @@ WatcherThread* WatcherThread::_watcher_thread = NULL; bool WatcherThread::_startable = false; volatile bool WatcherThread::_should_terminate = false; -WatcherThread::WatcherThread() : Thread() { +WatcherThread::WatcherThread() : Thread(), _crash_protection(NULL) { assert(watcher_thread() == NULL, "we can only allocate one WatcherThread"); if (os::create_thread(this, os::watcher_thread)) { _watcher_thread = this; @@ -3482,44 +3490,6 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { initialize_class(vmSymbols::java_lang_String(), CHECK_0); - if (AggressiveOpts) { - { - // Forcibly initialize java/util/HashMap and mutate the private - // static final "frontCacheEnabled" field before we start creating instances -#ifdef ASSERT - Klass* tmp_k = SystemDictionary::find(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0); - assert(tmp_k == NULL, "java/util/HashMap should not be loaded yet"); -#endif - Klass* k_o = SystemDictionary::resolve_or_null(vmSymbols::java_util_HashMap(), Handle(), Handle(), CHECK_0); - KlassHandle k = KlassHandle(THREAD, k_o); - guarantee(k.not_null(), "Must find java/util/HashMap"); - instanceKlassHandle ik = instanceKlassHandle(THREAD, k()); - ik->initialize(CHECK_0); - fieldDescriptor fd; - // Possible we might not find this field; if so, don't break - if (ik->find_local_field(vmSymbols::frontCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) { - k()->java_mirror()->bool_field_put(fd.offset(), true); - } - } - - if (UseStringCache) { - // Forcibly initialize java/lang/StringValue and mutate the private - // static final "stringCacheEnabled" field before we start creating instances - Klass* k_o = SystemDictionary::resolve_or_null(vmSymbols::java_lang_StringValue(), Handle(), Handle(), CHECK_0); - // Possible that StringValue isn't present: if so, silently don't break - if (k_o != NULL) { - KlassHandle k = KlassHandle(THREAD, k_o); - instanceKlassHandle ik = instanceKlassHandle(THREAD, k()); - ik->initialize(CHECK_0); - fieldDescriptor fd; - // Possible we might not find this field: if so, silently don't break - if (ik->find_local_field(vmSymbols::stringCacheEnabled_name(), vmSymbols::bool_signature(), &fd)) { - k()->java_mirror()->bool_field_put(fd.offset(), true); - } - } - } - } - // Initialize java_lang.System (needed before creating the thread) initialize_class(vmSymbols::java_lang_System(), CHECK_0); initialize_class(vmSymbols::java_lang_ThreadGroup(), CHECK_0); @@ -3637,6 +3607,7 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { // Start Attach Listener if +StartAttachListener or it can't be started lazily if (!DisableAttachMechanism) { + AttachListener::vm_start(); if (StartAttachListener || AttachListener::init_at_startup()) { AttachListener::init(); } @@ -3677,7 +3648,6 @@ jint Threads::create_vm(JavaVMInitArgs* args, bool* canTryAgain) { } if (Arguments::has_profile()) FlatProfiler::engage(main_thread, true); - if (Arguments::has_alloc_profile()) AllocationProfiler::engage(); if (MemProfiling) MemProfiler::engage(); StatSampler::engage(); if (CheckJNICalls) JniPeriodicChecker::engage(); diff --git a/hotspot/src/share/vm/runtime/thread.hpp b/hotspot/src/share/vm/runtime/thread.hpp index 8b8e6dd4e62..2c8c1875491 100644 --- a/hotspot/src/share/vm/runtime/thread.hpp +++ b/hotspot/src/share/vm/runtime/thread.hpp @@ -86,6 +86,8 @@ class GCTaskQueue; class ThreadClosure; class IdealGraphPrinter; +DEBUG_ONLY(class ResourceMark;) + class WorkerThread; // Class hierarchy @@ -519,6 +521,9 @@ public: // Check if address is in the stack of the thread (not just for locks). // Warning: the method can only be used on the running thread bool is_in_stack(address adr) const; + // Check if address is in the usable part of the stack (excludes protected + // guard pages) + bool is_in_usable_stack(address adr) const; // Sets this thread as starting thread. Returns failure if thread // creation fails due to lack of memory, too many threads etc. @@ -531,6 +536,8 @@ public: // Thread local resource area for temporary allocation within the VM ResourceArea* _resource_area; + DEBUG_ONLY(ResourceMark* _current_resource_mark;) + // Thread local handle area for allocation of handles within the VM HandleArea* _handle_area; GrowableArray* _metadata_handles; @@ -585,6 +592,8 @@ public: // Deadlock detection bool allow_allocation() { return _allow_allocation_count == 0; } + ResourceMark* current_resource_mark() { return _current_resource_mark; } + void set_current_resource_mark(ResourceMark* rm) { _current_resource_mark = rm; } #endif void check_for_valid_safepoint_state(bool potential_vm_operation) PRODUCT_RETURN; @@ -724,6 +733,8 @@ class WatcherThread: public Thread { static bool _startable; volatile static bool _should_terminate; // updated without holding lock + + os::WatcherThreadCrashProtection* _crash_protection; public: enum SomeConstants { delay_interval = 10 // interrupt delay in milliseconds @@ -751,6 +762,14 @@ class WatcherThread: public Thread { // Otherwise the first task to enroll will trigger the start static void make_startable(); + void set_crash_protection(os::WatcherThreadCrashProtection* crash_protection) { + assert(Thread::current()->is_Watcher_thread(), "Can only be set by WatcherThread"); + _crash_protection = crash_protection; + } + + bool has_crash_protection() const { return _crash_protection != NULL; } + os::WatcherThreadCrashProtection* crash_protection() const { return _crash_protection; } + private: int sleep() const; }; diff --git a/hotspot/src/share/vm/runtime/vmStructs.cpp b/hotspot/src/share/vm/runtime/vmStructs.cpp index caf785a2cfb..e7de9601c96 100644 --- a/hotspot/src/share/vm/runtime/vmStructs.cpp +++ b/hotspot/src/share/vm/runtime/vmStructs.cpp @@ -263,7 +263,7 @@ typedef BinaryTreeDictionary MetablockTreeDictionary; unchecked_c2_static_field) \ \ /******************************************************************/ \ - /* OopDesc and Klass hierarchies (NOTE: MethodData* incomplete) */ \ + /* OopDesc and Klass hierarchies (NOTE: MethodData* incomplete) */ \ /******************************************************************/ \ \ volatile_nonstatic_field(oopDesc, _mark, markOop) \ @@ -274,21 +274,20 @@ typedef BinaryTreeDictionary MetablockTreeDictionary; volatile_nonstatic_field(ArrayKlass, _higher_dimension, Klass*) \ volatile_nonstatic_field(ArrayKlass, _lower_dimension, Klass*) \ nonstatic_field(ArrayKlass, _vtable_len, int) \ - nonstatic_field(ArrayKlass, _alloc_size, juint) \ nonstatic_field(ArrayKlass, _component_mirror, oop) \ - nonstatic_field(CompiledICHolder, _holder_method, Method*) \ + nonstatic_field(CompiledICHolder, _holder_method, Method*) \ nonstatic_field(CompiledICHolder, _holder_klass, Klass*) \ nonstatic_field(ConstantPool, _tags, Array*) \ - nonstatic_field(ConstantPool, _cache, ConstantPoolCache*) \ + nonstatic_field(ConstantPool, _cache, ConstantPoolCache*) \ nonstatic_field(ConstantPool, _pool_holder, InstanceKlass*) \ nonstatic_field(ConstantPool, _operands, Array*) \ nonstatic_field(ConstantPool, _length, int) \ nonstatic_field(ConstantPool, _resolved_references, jobject) \ nonstatic_field(ConstantPool, _reference_map, Array*) \ nonstatic_field(ConstantPoolCache, _length, int) \ - nonstatic_field(ConstantPoolCache, _constant_pool, ConstantPool*) \ + nonstatic_field(ConstantPoolCache, _constant_pool, ConstantPool*) \ nonstatic_field(InstanceKlass, _array_klasses, Klass*) \ - nonstatic_field(InstanceKlass, _methods, Array*) \ + nonstatic_field(InstanceKlass, _methods, Array*) \ nonstatic_field(InstanceKlass, _local_interfaces, Array*) \ nonstatic_field(InstanceKlass, _transitive_interfaces, Array*) \ nonstatic_field(InstanceKlass, _fields, Array*) \ @@ -336,9 +335,8 @@ typedef BinaryTreeDictionary MetablockTreeDictionary; nonstatic_field(Klass, _access_flags, AccessFlags) \ nonstatic_field(Klass, _subklass, Klass*) \ nonstatic_field(Klass, _next_sibling, Klass*) \ - nonstatic_field(Klass, _alloc_count, juint) \ nonstatic_field(MethodData, _size, int) \ - nonstatic_field(MethodData, _method, Method*) \ + nonstatic_field(MethodData, _method, Method*) \ nonstatic_field(MethodData, _data_size, int) \ nonstatic_field(MethodData, _data[0], intptr_t) \ nonstatic_field(MethodData, _nof_decompiles, uint) \ @@ -437,10 +435,6 @@ typedef BinaryTreeDictionary MetablockTreeDictionary; static_field(Universe, _main_thread_group, oop) \ static_field(Universe, _system_thread_group, oop) \ static_field(Universe, _the_empty_class_klass_array, objArrayOop) \ - static_field(Universe, _out_of_memory_error_java_heap, oop) \ - static_field(Universe, _out_of_memory_error_perm_gen, oop) \ - static_field(Universe, _out_of_memory_error_array_size, oop) \ - static_field(Universe, _out_of_memory_error_gc_overhead_limit, oop) \ static_field(Universe, _null_ptr_exception_instance, oop) \ static_field(Universe, _arithmetic_exception_instance, oop) \ static_field(Universe, _vm_exception, oop) \ diff --git a/hotspot/src/share/vm/services/attachListener.hpp b/hotspot/src/share/vm/services/attachListener.hpp index 2e7cff39537..6995a0f23ab 100644 --- a/hotspot/src/share/vm/services/attachListener.hpp +++ b/hotspot/src/share/vm/services/attachListener.hpp @@ -50,6 +50,7 @@ struct AttachOperationFunctionInfo { class AttachListener: AllStatic { public: + static void vm_start() NOT_SERVICES_RETURN; static void init() NOT_SERVICES_RETURN; static void abort() NOT_SERVICES_RETURN; diff --git a/hotspot/src/share/vm/services/memBaseline.cpp b/hotspot/src/share/vm/services/memBaseline.cpp index 21eb8b5d422..62e51873c7b 100644 --- a/hotspot/src/share/vm/services/memBaseline.cpp +++ b/hotspot/src/share/vm/services/memBaseline.cpp @@ -486,7 +486,7 @@ int MemBaseline::malloc_sort_by_addr(const void* p1, const void* p2) { const MemPointerRecord* mp1 = (const MemPointerRecord*)p1; const MemPointerRecord* mp2 = (const MemPointerRecord*)p2; int delta = UNSIGNED_COMPARE(mp1->addr(), mp2->addr()); - assert(delta != 0, "dup pointer"); + assert(p1 == p2 || delta != 0, "dup pointer"); return delta; } diff --git a/hotspot/src/share/vm/services/memReporter.cpp b/hotspot/src/share/vm/services/memReporter.cpp index 573d9e03c14..9d0f45ada36 100644 --- a/hotspot/src/share/vm/services/memReporter.cpp +++ b/hotspot/src/share/vm/services/memReporter.cpp @@ -188,8 +188,8 @@ void BaselineReporter::diff_callsites(const MemBaseline& cur, const MemBaseline& (MallocCallsitePointer*)prev_malloc_itr.current(); while (cur_malloc_callsite != NULL || prev_malloc_callsite != NULL) { - if (prev_malloc_callsite == NULL || - cur_malloc_callsite->addr() < prev_malloc_callsite->addr()) { + if (prev_malloc_callsite == NULL) { + assert(cur_malloc_callsite != NULL, "sanity check"); // this is a new callsite _outputer.diff_malloc_callsite(cur_malloc_callsite->addr(), amount_in_current_scale(cur_malloc_callsite->amount()), @@ -197,22 +197,42 @@ void BaselineReporter::diff_callsites(const MemBaseline& cur, const MemBaseline& diff_in_current_scale(cur_malloc_callsite->amount(), 0), diff(cur_malloc_callsite->count(), 0)); cur_malloc_callsite = (MallocCallsitePointer*)cur_malloc_itr.next(); - } else if (cur_malloc_callsite == NULL || - cur_malloc_callsite->addr() > prev_malloc_callsite->addr()) { + } else if (cur_malloc_callsite == NULL) { + assert(prev_malloc_callsite != NULL, "Sanity check"); // this callsite is already gone _outputer.diff_malloc_callsite(prev_malloc_callsite->addr(), - amount_in_current_scale(0), 0, + 0, 0, diff_in_current_scale(0, prev_malloc_callsite->amount()), diff(0, prev_malloc_callsite->count())); prev_malloc_callsite = (MallocCallsitePointer*)prev_malloc_itr.next(); - } else { // the same callsite - _outputer.diff_malloc_callsite(cur_malloc_callsite->addr(), - amount_in_current_scale(cur_malloc_callsite->amount()), - cur_malloc_callsite->count(), - diff_in_current_scale(cur_malloc_callsite->amount(), prev_malloc_callsite->amount()), - diff(cur_malloc_callsite->count(), prev_malloc_callsite->count())); - cur_malloc_callsite = (MallocCallsitePointer*)cur_malloc_itr.next(); - prev_malloc_callsite = (MallocCallsitePointer*)prev_malloc_itr.next(); + } else { + assert(cur_malloc_callsite != NULL, "Sanity check"); + assert(prev_malloc_callsite != NULL, "Sanity check"); + if (cur_malloc_callsite->addr() < prev_malloc_callsite->addr()) { + // this is a new callsite + _outputer.diff_malloc_callsite(cur_malloc_callsite->addr(), + amount_in_current_scale(cur_malloc_callsite->amount()), + cur_malloc_callsite->count(), + diff_in_current_scale(cur_malloc_callsite->amount(), 0), + diff(cur_malloc_callsite->count(), 0)); + cur_malloc_callsite = (MallocCallsitePointer*)cur_malloc_itr.next(); + } else if (cur_malloc_callsite->addr() > prev_malloc_callsite->addr()) { + // this callsite is already gone + _outputer.diff_malloc_callsite(prev_malloc_callsite->addr(), + 0, 0, + diff_in_current_scale(0, prev_malloc_callsite->amount()), + diff(0, prev_malloc_callsite->count())); + prev_malloc_callsite = (MallocCallsitePointer*)prev_malloc_itr.next(); + } else { + // the same callsite + _outputer.diff_malloc_callsite(cur_malloc_callsite->addr(), + amount_in_current_scale(cur_malloc_callsite->amount()), + cur_malloc_callsite->count(), + diff_in_current_scale(cur_malloc_callsite->amount(), prev_malloc_callsite->amount()), + diff(cur_malloc_callsite->count(), prev_malloc_callsite->count())); + cur_malloc_callsite = (MallocCallsitePointer*)cur_malloc_itr.next(); + prev_malloc_callsite = (MallocCallsitePointer*)prev_malloc_itr.next(); + } } } diff --git a/hotspot/src/share/vm/services/memTracker.cpp b/hotspot/src/share/vm/services/memTracker.cpp index e0a1b29a8e9..a2961ee990a 100644 --- a/hotspot/src/share/vm/services/memTracker.cpp +++ b/hotspot/src/share/vm/services/memTracker.cpp @@ -81,13 +81,13 @@ void MemTracker::init_tracking_options(const char* option_line) { } else if (strcmp(option_line, "=detail") == 0) { // detail relies on a stack-walking ability that may not // be available depending on platform and/or compiler flags - if (PLATFORM_NMT_DETAIL_SUPPORTED) { +#if PLATFORM_NATIVE_STACK_WALKING_SUPPORTED _tracking_level = NMT_detail; - } else { +#else jio_fprintf(defaultStream::error_stream(), - "NMT detail is not supported on this platform. Using NMT summary instead."); + "NMT detail is not supported on this platform. Using NMT summary instead.\n"); _tracking_level = NMT_summary; - } +#endif } else if (strcmp(option_line, "=off") != 0) { vm_exit_during_initialization("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]", NULL); } @@ -385,6 +385,7 @@ void MemTracker::enqueue_pending_recorder(MemRecorder* rec) { #define SAFE_SEQUENCE_THRESHOLD 30 #define HIGH_GENERATION_THRESHOLD 60 #define MAX_RECORDER_THREAD_RATIO 30 +#define MAX_RECORDER_PER_THREAD 100 void MemTracker::sync() { assert(_tracking_level > NMT_off, "NMT is not enabled"); @@ -437,6 +438,11 @@ void MemTracker::sync() { // means that worker thread is lagging behind in processing them. if (!AutoShutdownNMT) { _slowdown_calling_thread = (MemRecorder::_instance_count > MAX_RECORDER_THREAD_RATIO * _thread_count); + } else { + // If auto shutdown is on, enforce MAX_RECORDER_PER_THREAD threshold to prevent OOM + if (MemRecorder::_instance_count >= _thread_count * MAX_RECORDER_PER_THREAD) { + shutdown(NMT_out_of_memory); + } } // check _worker_thread with lock to avoid racing condition diff --git a/hotspot/src/share/vm/services/memTracker.hpp b/hotspot/src/share/vm/services/memTracker.hpp index dc7b78859d3..364c6b4f235 100644 --- a/hotspot/src/share/vm/services/memTracker.hpp +++ b/hotspot/src/share/vm/services/memTracker.hpp @@ -470,7 +470,21 @@ class MemTracker : AllStatic { static void check_NMT_load(Thread* thr) { assert(thr != NULL, "Sanity check"); if (_slowdown_calling_thread && thr != _worker_thread) { +#ifdef _WINDOWS + // On Windows, os::NakedYield() does not work as well + // as os::yield_all() os::yield_all(); +#else + // On Solaris, os::yield_all() depends on os::sleep() + // which requires JavaTherad in _thread_in_vm state. + // Transits thread to _thread_in_vm state can be dangerous + // if caller holds lock, as it may deadlock with Threads_lock. + // So use NaKedYield instead. + // + // Linux and BSD, NakedYield() and yield_all() implementations + // are the same. + os::NakedYield(); +#endif } } diff --git a/hotspot/src/share/vm/trace/trace.xml b/hotspot/src/share/vm/trace/trace.xml index c530bbc3c16..6b1d9a8850f 100644 --- a/hotspot/src/share/vm/trace/trace.xml +++ b/hotspot/src/share/vm/trace/trace.xml @@ -158,7 +158,7 @@ Declares a structure type that can be used in other events. - + @@ -203,7 +203,7 @@ Declares a structure type that can be used in other events. - + @@ -211,7 +211,7 @@ Declares a structure type that can be used in other events. - + @@ -240,14 +240,14 @@ Declares a structure type that can be used in other events. - + - + - + diff --git a/hotspot/src/share/vm/trace/traceDataTypes.hpp b/hotspot/src/share/vm/trace/traceDataTypes.hpp index 437ac447e73..31004d934b5 100644 --- a/hotspot/src/share/vm/trace/traceDataTypes.hpp +++ b/hotspot/src/share/vm/trace/traceDataTypes.hpp @@ -63,5 +63,7 @@ typedef u8 stacktraceid; typedef u8 methodid; typedef u8 fieldid; +class TraceUnicodeString; + #endif // SHARE_VM_TRACE_TRACEDATATYPES_HPP diff --git a/hotspot/src/share/vm/trace/tracetypes.xml b/hotspot/src/share/vm/trace/tracetypes.xml index 7f0460e691a..22fd5059042 100644 --- a/hotspot/src/share/vm/trace/tracetypes.xml +++ b/hotspot/src/share/vm/trace/tracetypes.xml @@ -55,18 +55,6 @@ Before we can use it we need also define a primary field data type: type="u8" sizeop="sizeof(u1)"/> Now we can use the content + data type in declaring event fields. -Remember however, that for us to be able to resolve the value later we must also add -creating the constant pool data in VM_JFRCheckpoint::write_checkpoint - - ... - //CGMODE - w->be_uint(CONTENT_TYPE_GCMODE); - w->be_uint(MM_GC_MODE_UNINITIALIZED); - for (i = 0; i < MM_GC_MODE_UNINITIALIZED; i++) { - w->uchar(i); - w->write_utf8(gcModeGetName(i)); - } - --> @@ -81,10 +69,6 @@ creating the constant pool data in VM_JFRCheckpoint::write_checkpoint - @@ -285,6 +269,10 @@ creating the constant pool data in VM_JFRCheckpoint::write_checkpoint + + + - - * @throws XMLEncryptionException */ - - public EncryptedData createEncryptedData(int type, String value) throws - XMLEncryptionException { + public EncryptedData createEncryptedData(int type, String value) throws XMLEncryptionException { EncryptedData result = null; CipherData data = null; switch (type) { - case CipherData.REFERENCE_TYPE: - CipherReference cipherReference = _factory.newCipherReference( - value); - data = _factory.newCipherData(type); - data.setCipherReference(cipherReference); - result = _factory.newEncryptedData(data); - break; - case CipherData.VALUE_TYPE: - CipherValue cipherValue = _factory.newCipherValue(value); - data = _factory.newCipherData(type); - data.setCipherValue(cipherValue); - result = _factory.newEncryptedData(data); + case CipherData.REFERENCE_TYPE: + CipherReference cipherReference = factory.newCipherReference(value); + data = factory.newCipherData(type); + data.setCipherReference(cipherReference); + result = factory.newEncryptedData(data); + break; + case CipherData.VALUE_TYPE: + CipherValue cipherValue = factory.newCipherValue(value); + data = factory.newCipherData(type); + data.setCipherValue(cipherValue); + result = factory.newEncryptedData(data); } - return (result); + return result; } /** * Creates an EncryptedKey Element. * - * The newEncryptedData and newEncryptedKey methods create fairly complete - * elements that are immediately useable. All the other create* methods - * return bare elements that still need to be built upon. - *

- * An EncryptionMethod will still need to be added however - * - * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of - * CipherData this EncryptedData will contain. + * The newEncryptedData and newEncryptedKey methods create fairly complete + * elements that are immediately useable. All the other create* methods + * return bare elements that still need to be built upon. + *

+ * An EncryptionMethod will still need to be added however + * + * @param type Either REFERENCE_TYPE or VALUE_TYPE - defines what kind of + * CipherData this EncryptedData will contain. * @param value the Base 64 encoded, encrypted text to wrap in the * EncryptedKey or the URI to set in the CipherReference - * (usage will depend on the type + * (usage will depend on the type * @return the EncryptedKey Element. * * * @throws XMLEncryptionException */ - - public EncryptedKey createEncryptedKey(int type, String value) throws - XMLEncryptionException { + public EncryptedKey createEncryptedKey(int type, String value) throws XMLEncryptionException { EncryptedKey result = null; CipherData data = null; switch (type) { - case CipherData.REFERENCE_TYPE: - CipherReference cipherReference = _factory.newCipherReference( - value); - data = _factory.newCipherData(type); - data.setCipherReference(cipherReference); - result = _factory.newEncryptedKey(data); - break; - case CipherData.VALUE_TYPE: - CipherValue cipherValue = _factory.newCipherValue(value); - data = _factory.newCipherData(type); - data.setCipherValue(cipherValue); - result = _factory.newEncryptedKey(data); + case CipherData.REFERENCE_TYPE: + CipherReference cipherReference = factory.newCipherReference(value); + data = factory.newCipherData(type); + data.setCipherReference(cipherReference); + result = factory.newEncryptedKey(data); + break; + case CipherData.VALUE_TYPE: + CipherValue cipherValue = factory.newCipherValue(value); + data = factory.newCipherData(type); + data.setCipherValue(cipherValue); + result = factory.newEncryptedKey(data); } - return (result); + return result; } - /** - * Create an AgreementMethod object - * - * @param algorithm Algorithm of the agreement method - * @return - */ - - public AgreementMethod createAgreementMethod(String algorithm) { - return (_factory.newAgreementMethod(algorithm)); - } - - /** - * Create a CipherData object - * - * @param type Type of this CipherData (either VALUE_TUPE or - * REFERENCE_TYPE) - * @return - */ - - public CipherData createCipherData(int type) { - return (_factory.newCipherData(type)); - } - - /** - * Create a CipherReference object - * - * @return - * @param uri The URI that the reference will refer - */ - - public CipherReference createCipherReference(String uri) { - return (_factory.newCipherReference(uri)); - } - - /** - * Create a CipherValue element - * - * @param value The value to set the ciphertext to - * @return - */ - - public CipherValue createCipherValue(String value) { - return (_factory.newCipherValue(value)); - } - - /** - * Create an EncryptedMethod object - * - * @param algorithm Algorithm for the encryption - * @return - */ - public EncryptionMethod createEncryptionMethod(String algorithm) { - return (_factory.newEncryptionMethod(algorithm)); - } - - /** - * Create an EncryptedProperties element - * @return - */ - public EncryptionProperties createEncryptionProperties() { - return (_factory.newEncryptionProperties()); - } - - /** - * Create a new EncryptionProperty element - * @return - */ - public EncryptionProperty createEncryptionProperty() { - return (_factory.newEncryptionProperty()); - } - - /** - * Create a new ReferenceList object - * @return - * @param type - */ - public ReferenceList createReferenceList(int type) { - return (_factory.newReferenceList(type)); - } - - /** - * Create a new Transforms object - *

- * Note: A context document must have been set - * elsewhere (possibly via a call to doFinal). If not, use the - * createTransforms(Document) method. - * @return - */ - - public Transforms createTransforms() { - return (_factory.newTransforms()); - } - - /** - * Create a new Transforms object - * - * Because the handling of Transforms is currently done in the signature - * code, the creation of a Transforms object requires a - * context document. - * - * @param doc Document that will own the created Transforms node - * @return - */ - public Transforms createTransforms(Document doc) { - return (_factory.newTransforms(doc)); - } - /** - * Converts Strings into Nodes and visa versa. - *

- * NOTE: For internal use only. + * Create an AgreementMethod object * - * @author Axl Mattheus + * @param algorithm Algorithm of the agreement method + * @return a new AgreementMethod */ - - private class Serializer { - /** - * Initialize the XMLSerializer with the specified context - * Document. - *

- * Setup OutputFormat in a way that the serialization does not - * modifiy the contents, that is it shall not do any pretty printing - * and so on. This would destroy the original content before - * encryption. If that content was signed before encryption and the - * serialization modifies the content the signature verification will - * fail. - */ - Serializer() { - } - - /** - * Returns a String representation of the specified - * Document. - *

- * Refer also to comments about setup of format. - * - * @param document the Document to serialize. - * @return the String representation of the serilaized - * Document. - * @throws Exception - */ - String serialize(Document document) throws Exception { - return canonSerialize(document); - } - - /** - * Returns a String representation of the specified - * Element. - *

- * Refer also to comments about setup of format. - * - * @param element the Element to serialize. - * @return the String representation of the serilaized - * Element. - * @throws Exception - */ - String serialize(Element element) throws Exception { - return canonSerialize(element); - } - - /** - * Returns a String representation of the specified - * NodeList. - *

- * This is a special case because the NodeList may represent a - * DocumentFragment. A document fragement may be a - * non-valid XML document (refer to appropriate description of - * W3C) because it my start with a non-element node, e.g. a text - * node. - *

- * The methods first converts the node list into a document fragment. - * Special care is taken to not destroy the current document, thus - * the method clones the nodes (deep cloning) before it appends - * them to the document fragment. - *

- * Refer also to comments about setup of format. - * - * @param content the NodeList to serialize. - * @return the String representation of the serilaized - * NodeList. - * @throws Exception - */ - String serialize(NodeList content) throws Exception { //XMLEncryptionException { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - _canon.setWriter(baos); - _canon.notReset(); - for (int i = 0; i < content.getLength(); i++) { - _canon.canonicalizeSubtree(content.item(i)); - } - baos.close(); - return baos.toString("UTF-8"); - } - - /** - * Use the Canoncializer to serialize the node - * @param node - * @return - * @throws Exception - */ - String canonSerialize(Node node) throws Exception { - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - _canon.setWriter(baos); - _canon.notReset(); - _canon.canonicalizeSubtree(node); - baos.close(); - return baos.toString("UTF-8"); - } - /** - * @param source - * @param ctx - * @return - * @throws XMLEncryptionException - * - */ - DocumentFragment deserialize(String source, Node ctx) throws XMLEncryptionException { - DocumentFragment result; - final String tagname = "fragment"; - - // Create the context to parse the document against - StringBuffer sb; - - sb = new StringBuffer(); - sb.append("<"+tagname); - - // Run through each node up to the document node and find any - // xmlns: nodes - - Node wk = ctx; - - while (wk != null) { - - NamedNodeMap atts = wk.getAttributes(); - int length; - if (atts != null) - length = atts.getLength(); - else - length = 0; - - for (int i = 0 ; i < length ; ++i) { - Node att = atts.item(i); - if (att.getNodeName().startsWith("xmlns:") || - att.getNodeName().equals("xmlns")) { - - // Check to see if this node has already been found - Node p = ctx; - boolean found = false; - while (p != wk) { - NamedNodeMap tstAtts = p.getAttributes(); - if (tstAtts != null && - tstAtts.getNamedItem(att.getNodeName()) != null) { - found = true; - break; - } - p = p.getParentNode(); - } - if (found == false) { - - // This is an attribute node - sb.append(" " + att.getNodeName() + "=\"" + - att.getNodeValue() + "\""); - } - } - } - wk = wk.getParentNode(); - } - sb.append(">" + source + ""); - String fragment = sb.toString(); - - try { - DocumentBuilderFactory dbf = - DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - dbf.setAttribute("http://xml.org/sax/features/namespaces", Boolean.TRUE); - DocumentBuilder db = dbf.newDocumentBuilder(); - Document d = db.parse( - new InputSource(new StringReader(fragment))); - - Element fragElt = (Element) _contextDocument.importNode( - d.getDocumentElement(), true); - result = _contextDocument.createDocumentFragment(); - Node child = fragElt.getFirstChild(); - while (child != null) { - fragElt.removeChild(child); - result.appendChild(child); - child = fragElt.getFirstChild(); - } - // String outp = serialize(d); - - } catch (SAXException se) { - throw new XMLEncryptionException("empty", se); - } catch (ParserConfigurationException pce) { - throw new XMLEncryptionException("empty", pce); - } catch (IOException ioe) { - throw new XMLEncryptionException("empty", ioe); - } - - return (result); - } + public AgreementMethod createAgreementMethod(String algorithm) { + return factory.newAgreementMethod(algorithm); } + /** + * Create a CipherData object + * + * @param type Type of this CipherData (either VALUE_TUPE or + * REFERENCE_TYPE) + * @return a new CipherData + */ + public CipherData createCipherData(int type) { + return factory.newCipherData(type); + } + + /** + * Create a CipherReference object + * + * @param uri The URI that the reference will refer + * @return a new CipherReference + */ + public CipherReference createCipherReference(String uri) { + return factory.newCipherReference(uri); + } + + /** + * Create a CipherValue element + * + * @param value The value to set the ciphertext to + * @return a new CipherValue + */ + public CipherValue createCipherValue(String value) { + return factory.newCipherValue(value); + } + + /** + * Create an EncryptionMethod object + * + * @param algorithm Algorithm for the encryption + * @return a new EncryptionMethod + */ + public EncryptionMethod createEncryptionMethod(String algorithm) { + return factory.newEncryptionMethod(algorithm); + } + + /** + * Create an EncryptionProperties element + * @return a new EncryptionProperties + */ + public EncryptionProperties createEncryptionProperties() { + return factory.newEncryptionProperties(); + } + + /** + * Create a new EncryptionProperty element + * @return a new EncryptionProperty + */ + public EncryptionProperty createEncryptionProperty() { + return factory.newEncryptionProperty(); + } + + /** + * Create a new ReferenceList object + * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE + * @return a new ReferenceList + */ + public ReferenceList createReferenceList(int type) { + return factory.newReferenceList(type); + } + + /** + * Create a new Transforms object + *

+ * Note: A context document must have been set + * elsewhere (possibly via a call to doFinal). If not, use the + * createTransforms(Document) method. + * @return a new Transforms + */ + public Transforms createTransforms() { + return factory.newTransforms(); + } + + /** + * Create a new Transforms object + * + * Because the handling of Transforms is currently done in the signature + * code, the creation of a Transforms object requires a + * context document. + * + * @param doc Document that will own the created Transforms node + * @return a new Transforms + */ + public Transforms createTransforms(Document doc) { + return factory.newTransforms(doc); + } /** * @@ -2020,201 +1994,110 @@ public class XMLCipher { private class Factory { /** * @param algorithm - * @return - * + * @return a new AgreementMethod */ AgreementMethod newAgreementMethod(String algorithm) { - return (new AgreementMethodImpl(algorithm)); + return new AgreementMethodImpl(algorithm); } /** * @param type - * @return + * @return a new CipherData * */ CipherData newCipherData(int type) { - return (new CipherDataImpl(type)); + return new CipherDataImpl(type); } /** * @param uri - * @return - * + * @return a new CipherReference */ CipherReference newCipherReference(String uri) { - return (new CipherReferenceImpl(uri)); + return new CipherReferenceImpl(uri); } /** * @param value - * @return - * + * @return a new CipherValue */ CipherValue newCipherValue(String value) { - return (new CipherValueImpl(value)); + return new CipherValueImpl(value); } - /** - * - + /* CipherValue newCipherValue(byte[] value) { - return (new CipherValueImpl(value)); + return new CipherValueImpl(value); } - */ + */ + /** * @param data - * @return - * + * @return a new EncryptedData */ EncryptedData newEncryptedData(CipherData data) { - return (new EncryptedDataImpl(data)); + return new EncryptedDataImpl(data); } /** * @param data - * @return - * + * @return a new EncryptedKey */ EncryptedKey newEncryptedKey(CipherData data) { - return (new EncryptedKeyImpl(data)); + return new EncryptedKeyImpl(data); } /** * @param algorithm - * @return - * + * @return a new EncryptionMethod */ EncryptionMethod newEncryptionMethod(String algorithm) { - return (new EncryptionMethodImpl(algorithm)); + return new EncryptionMethodImpl(algorithm); } /** - * @return - * + * @return a new EncryptionProperties */ EncryptionProperties newEncryptionProperties() { - return (new EncryptionPropertiesImpl()); + return new EncryptionPropertiesImpl(); } /** - * @return - * + * @return a new EncryptionProperty */ EncryptionProperty newEncryptionProperty() { - return (new EncryptionPropertyImpl()); + return new EncryptionPropertyImpl(); } /** - * @param type - * @return - * + * @param type ReferenceList.DATA_REFERENCE or ReferenceList.KEY_REFERENCE + * @return a new ReferenceList */ ReferenceList newReferenceList(int type) { - return (new ReferenceListImpl(type)); + return new ReferenceListImpl(type); } /** - * @return - * + * @return a new Transforms */ Transforms newTransforms() { - return (new TransformsImpl()); + return new TransformsImpl(); } /** * @param doc - * @return - * + * @return a new Transforms */ Transforms newTransforms(Document doc) { - return (new TransformsImpl(doc)); + return new TransformsImpl(doc); } /** * @param element - * @return + * @return a new CipherData * @throws XMLEncryptionException - * */ - // - // - // - // - // - // - // - // - // - // - // - AgreementMethod newAgreementMethod(Element element) throws - XMLEncryptionException { - if (null == element) { - throw new NullPointerException("element is null"); - } - - String algorithm = element.getAttributeNS(null, - EncryptionConstants._ATT_ALGORITHM); - AgreementMethod result = newAgreementMethod(algorithm); - - Element kaNonceElement = (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KA_NONCE).item(0); - if (null != kaNonceElement) { - result.setKANonce(kaNonceElement.getNodeValue().getBytes()); - } - // TODO: /////////////////////////////////////////////////////////// - // Figure out how to make this pesky line work.. - // - - // TODO: Work out how to handle relative URI - - Element originatorKeyInfoElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ORIGINATORKEYINFO).item(0); - if (null != originatorKeyInfoElement) { - try { - result.setOriginatorKeyInfo( - new KeyInfo(originatorKeyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } - } - - // TODO: Work out how to handle relative URI - - Element recipientKeyInfoElement = - (Element) element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_RECIPIENTKEYINFO).item(0); - if (null != recipientKeyInfoElement) { - try { - result.setRecipientKeyInfo( - new KeyInfo(recipientKeyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } - } - - return (result); - } - - /** - * @param element - * @return - * @throws XMLEncryptionException - * - */ - // - // - // - // - // - // - // - CipherData newCipherData(Element element) throws - XMLEncryptionException { + CipherData newCipherData(Element element) throws XMLEncryptionException { if (null == element) { throw new NullPointerException("element is null"); } @@ -2223,7 +2106,8 @@ public class XMLCipher { Element e = null; if (element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0) { + EncryptionConstants._TAG_CIPHERVALUE).getLength() > 0 + ) { type = CipherData.VALUE_TYPE; e = (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, @@ -2244,100 +2128,67 @@ public class XMLCipher { result.setCipherReference(newCipherReference(e)); } - return (result); + return result; } /** * @param element - * @return + * @return a new CipherReference * @throws XMLEncryptionException * */ - // - // - // - // - // - // - // - CipherReference newCipherReference(Element element) throws - XMLEncryptionException { + CipherReference newCipherReference(Element element) throws XMLEncryptionException { - Attr URIAttr = - element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); - CipherReference result = new CipherReferenceImpl(URIAttr); + Attr uriAttr = + element.getAttributeNodeNS(null, EncryptionConstants._ATT_URI); + CipherReference result = new CipherReferenceImpl(uriAttr); - // Find any Transforms + // Find any Transforms + NodeList transformsElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_TRANSFORMS); + Element transformsElement = (Element) transformsElements.item(0); - NodeList transformsElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_TRANSFORMS); - Element transformsElement = - (Element) transformsElements.item(0); + if (transformsElement != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element"); + } + try { + result.setTransforms(new TransformsImpl(transformsElement)); + } catch (XMLSignatureException xse) { + throw new XMLEncryptionException("empty", xse); + } catch (InvalidTransformException ite) { + throw new XMLEncryptionException("empty", ite); + } catch (XMLSecurityException xse) { + throw new XMLEncryptionException("empty", xse); + } + } - if (transformsElement != null) { - logger.log(java.util.logging.Level.FINE, "Creating a DSIG based Transforms element"); - try { - result.setTransforms(new TransformsImpl(transformsElement)); - } - catch (XMLSignatureException xse) { - throw new XMLEncryptionException("empty", xse); - } catch (InvalidTransformException ite) { - throw new XMLEncryptionException("empty", ite); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("empty", xse); - } - - } - - return result; + return result; } /** * @param element - * @return - * + * @return a new CipherValue */ CipherValue newCipherValue(Element element) { String value = XMLUtils.getFullTextChildrenFromElement(element); - CipherValue result = newCipherValue(value); - - return (result); + return newCipherValue(value); } /** * @param element - * @return + * @return a new EncryptedData * @throws XMLEncryptionException * */ - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - EncryptedData newEncryptedData(Element element) throws - XMLEncryptionException { + EncryptedData newEncryptedData(Element element) throws XMLEncryptionException { EncryptedData result = null; - NodeList dataElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + NodeList dataElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA); // Need to get the last CipherData found, as earlier ones will // be for elements in the KeyInfo lists @@ -2349,22 +2200,17 @@ public class XMLCipher { result = newEncryptedData(data); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); - result.setType( - element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); - result.setMimeType(element.getAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE)); - result.setEncoding( - element.getAttributeNS(null, Constants._ATT_ENCODING)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); + result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); + result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE)); + result.setEncoding( element.getAttributeNS(null, Constants._ATT_ENCODING)); Element encryptionMethodElement = (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0); if (null != encryptionMethodElement) { - result.setEncryptionMethod(newEncryptionMethod( - encryptionMethodElement)); + result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement)); } // BFL 16/7/03 - simple implementation @@ -2374,12 +2220,8 @@ public class XMLCipher { (Element) element.getElementsByTagNameNS( Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); if (null != keyInfoElement) { - try { - result.setKeyInfo(new KeyInfo(keyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException("Error loading Key Info", - xse); - } + KeyInfo ki = newKeyInfo(keyInfoElement); + result.setKeyInfo(ki); } // TODO: Implement @@ -2389,85 +2231,49 @@ public class XMLCipher { EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); if (null != encryptionPropertiesElement) { result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement)); + newEncryptionProperties(encryptionPropertiesElement) + ); } - return (result); + return result; } /** * @param element - * @return + * @return a new EncryptedKey * @throws XMLEncryptionException - * */ - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - EncryptedKey newEncryptedKey(Element element) throws - XMLEncryptionException { + EncryptedKey newEncryptedKey(Element element) throws XMLEncryptionException { EncryptedKey result = null; - NodeList dataElements = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + NodeList dataElements = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CIPHERDATA); Element dataElement = (Element) dataElements.item(dataElements.getLength() - 1); CipherData data = newCipherData(dataElement); result = newEncryptedKey(data); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); - result.setType( - element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); - result.setMimeType(element.getAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE)); - result.setEncoding( - element.getAttributeNS(null, Constants._ATT_ENCODING)); - result.setRecipient(element.getAttributeNS( - null, EncryptionConstants._ATT_RECIPIENT)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); + result.setType(element.getAttributeNS(null, EncryptionConstants._ATT_TYPE)); + result.setMimeType(element.getAttributeNS(null, EncryptionConstants._ATT_MIMETYPE)); + result.setEncoding(element.getAttributeNS(null, Constants._ATT_ENCODING)); + result.setRecipient(element.getAttributeNS(null, EncryptionConstants._ATT_RECIPIENT)); Element encryptionMethodElement = (Element) element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONMETHOD).item(0); if (null != encryptionMethodElement) { - result.setEncryptionMethod(newEncryptionMethod( - encryptionMethodElement)); + result.setEncryptionMethod(newEncryptionMethod(encryptionMethodElement)); } Element keyInfoElement = (Element) element.getElementsByTagNameNS( Constants.SignatureSpecNS, Constants._TAG_KEYINFO).item(0); if (null != keyInfoElement) { - try { - result.setKeyInfo(new KeyInfo(keyInfoElement, null)); - } catch (XMLSecurityException xse) { - throw new XMLEncryptionException - ("Error loading Key Info", xse); - } + KeyInfo ki = newKeyInfo(keyInfoElement); + result.setKeyInfo(ki); } // TODO: Implement @@ -2477,7 +2283,8 @@ public class XMLCipher { EncryptionConstants._TAG_ENCRYPTIONPROPERTIES).item(0); if (null != encryptionPropertiesElement) { result.setEncryptionProperties( - newEncryptionProperties(encryptionPropertiesElement)); + newEncryptionProperties(encryptionPropertiesElement) + ); } Element referenceListElement = @@ -2493,30 +2300,40 @@ public class XMLCipher { EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_CARRIEDKEYNAME).item(0); if (null != carriedNameElement) { - result.setCarriedName - (carriedNameElement.getFirstChild().getNodeValue()); + result.setCarriedName(carriedNameElement.getFirstChild().getNodeValue()); } - return (result); + return result; } /** * @param element - * @return - * + * @return a new KeyInfo + * @throws XMLEncryptionException + */ + KeyInfo newKeyInfo(Element element) throws XMLEncryptionException { + try { + KeyInfo ki = new KeyInfo(element, null); + ki.setSecureValidation(secureValidation); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + ki.registerInternalKeyResolver(internalKeyResolvers.get(i)); + } + } + return ki; + } catch (XMLSecurityException xse) { + throw new XMLEncryptionException("Error loading Key Info", xse); + } + } + + /** + * @param element + * @return a new EncryptionMethod */ - // - // - // - // - // - // - // - // EncryptionMethod newEncryptionMethod(Element element) { - String algorithm = element.getAttributeNS( - null, EncryptionConstants._ATT_ALGORITHM); - EncryptionMethod result = newEncryptionMethod(algorithm); + String encAlgorithm = element.getAttributeNS(null, EncryptionConstants._ATT_ALGORITHM); + EncryptionMethod result = newEncryptionMethod(encAlgorithm); Element keySizeElement = (Element) element.getElementsByTagNameNS( @@ -2533,92 +2350,83 @@ public class XMLCipher { EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_OAEPPARAMS).item(0); if (null != oaepParamsElement) { - result.setOAEPparams( - oaepParamsElement.getNodeValue().getBytes()); + try { + String oaepParams = oaepParamsElement.getFirstChild().getNodeValue(); + result.setOAEPparams(Base64.decode(oaepParams.getBytes("UTF-8"))); + } catch(UnsupportedEncodingException e) { + throw new RuntimeException("UTF-8 not supported", e); + } catch (Base64DecodingException e) { + throw new RuntimeException("BASE-64 decoding error", e); + } + } + + Element digestElement = + (Element) element.getElementsByTagNameNS( + Constants.SignatureSpecNS, Constants._TAG_DIGESTMETHOD).item(0); + if (digestElement != null) { + String digestAlgorithm = digestElement.getAttributeNS(null, "Algorithm"); + result.setDigestAlgorithm(digestAlgorithm); + } + + Element mgfElement = + (Element) element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpec11NS, EncryptionConstants._TAG_MGF).item(0); + if (mgfElement != null && !XMLCipher.RSA_OAEP.equals(algorithm)) { + String mgfAlgorithm = mgfElement.getAttributeNS(null, "Algorithm"); + result.setMGFAlgorithm(mgfAlgorithm); } // TODO: Make this mess work // - return (result); + return result; } /** * @param element - * @return - * + * @return a new EncryptionProperties */ - // - // - // - // - // - // - // EncryptionProperties newEncryptionProperties(Element element) { EncryptionProperties result = newEncryptionProperties(); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); NodeList encryptionPropertyList = element.getElementsByTagNameNS( EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_ENCRYPTIONPROPERTY); - for(int i = 0; i < encryptionPropertyList.getLength(); i++) { + for (int i = 0; i < encryptionPropertyList.getLength(); i++) { Node n = encryptionPropertyList.item(i); if (null != n) { - result.addEncryptionProperty( - newEncryptionProperty((Element) n)); + result.addEncryptionProperty(newEncryptionProperty((Element) n)); } } - return (result); + return result; } /** * @param element - * @return - * + * @return a new EncryptionProperty */ - // - // - // - // - // - // - // - // - // EncryptionProperty newEncryptionProperty(Element element) { EncryptionProperty result = newEncryptionProperty(); - result.setTarget( - element.getAttributeNS(null, EncryptionConstants._ATT_TARGET)); - result.setId(element.getAttributeNS( - null, EncryptionConstants._ATT_ID)); + result.setTarget(element.getAttributeNS(null, EncryptionConstants._ATT_TARGET)); + result.setId(element.getAttributeNS(null, EncryptionConstants._ATT_ID)); // TODO: Make this lot work... // // TODO: Make this work... // - return (result); + return result; } /** * @param element - * @return - * + * @return a new ReferenceList */ - // - // - // - // - // - // - // - // ReferenceList newReferenceList(Element element) { int type = 0; if (null != element.getElementsByTagNameNS( @@ -2629,84 +2437,38 @@ public class XMLCipher { EncryptionConstants.EncryptionSpecNS, EncryptionConstants._TAG_KEYREFERENCE).item(0)) { type = ReferenceList.KEY_REFERENCE; - } else { - // complain } ReferenceList result = new ReferenceListImpl(type); NodeList list = null; switch (type) { case ReferenceList.DATA_REFERENCE: - list = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_DATAREFERENCE); + list = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_DATAREFERENCE); for (int i = 0; i < list.getLength() ; i++) { String uri = ((Element) list.item(i)).getAttribute("URI"); result.add(result.newDataReference(uri)); } break; case ReferenceList.KEY_REFERENCE: - list = element.getElementsByTagNameNS( - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KEYREFERENCE); + list = + element.getElementsByTagNameNS( + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_KEYREFERENCE); for (int i = 0; i < list.getLength() ; i++) { String uri = ((Element) list.item(i)).getAttribute("URI"); result.add(result.newKeyReference(uri)); } } - return (result); - } - - /** - * @param element - * @return - * - */ - Transforms newTransforms(Element element) { - return (null); - } - - /** - * @param agreementMethod - * @return - * - */ - Element toElement(AgreementMethod agreementMethod) { - return ((AgreementMethodImpl) agreementMethod).toElement(); - } - - /** - * @param cipherData - * @return - * - */ - Element toElement(CipherData cipherData) { - return ((CipherDataImpl) cipherData).toElement(); - } - - /** - * @param cipherReference - * @return - * - */ - Element toElement(CipherReference cipherReference) { - return ((CipherReferenceImpl) cipherReference).toElement(); - } - - /** - * @param cipherValue - * @return - * - */ - Element toElement(CipherValue cipherValue) { - return ((CipherValueImpl) cipherValue).toElement(); + return result; } /** * @param encryptedData - * @return - * + * @return the XML Element form of that EncryptedData */ Element toElement(EncryptedData encryptedData) { return ((EncryptedDataImpl) encryptedData).toElement(); @@ -2714,64 +2476,20 @@ public class XMLCipher { /** * @param encryptedKey - * @return - * + * @return the XML Element form of that EncryptedKey */ Element toElement(EncryptedKey encryptedKey) { return ((EncryptedKeyImpl) encryptedKey).toElement(); } /** - * @param encryptionMethod - * @return - * + * @param referenceList + * @return the XML Element form of that ReferenceList */ - Element toElement(EncryptionMethod encryptionMethod) { - return ((EncryptionMethodImpl) encryptionMethod).toElement(); - } - - /** - * @param encryptionProperties - * @return - * - */ - Element toElement(EncryptionProperties encryptionProperties) { - return ((EncryptionPropertiesImpl) encryptionProperties).toElement(); - } - - /** - * @param encryptionProperty - * @return - * - */ - Element toElement(EncryptionProperty encryptionProperty) { - return ((EncryptionPropertyImpl) encryptionProperty).toElement(); - } - Element toElement(ReferenceList referenceList) { return ((ReferenceListImpl) referenceList).toElement(); } - /** - * @param transforms - * @return - * - */ - Element toElement(Transforms transforms) { - return ((TransformsImpl) transforms).toElement(); - } - - // - // - // - // - // - // - // - // - // - // - // private class AgreementMethodImpl implements AgreementMethod { private byte[] kaNonce = null; private List agreementMethodInformation = null; @@ -2787,15 +2505,16 @@ public class XMLCipher { URI tmpAlgorithm = null; try { tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException fmue) { - //complain? + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } algorithmURI = tmpAlgorithm.toString(); } /** @inheritDoc */ public byte[] getKANonce() { - return (kaNonce); + return kaNonce; } /** @inheritDoc */ @@ -2805,7 +2524,7 @@ public class XMLCipher { /** @inheritDoc */ public Iterator getAgreementMethodInformation() { - return (agreementMethodInformation.iterator()); + return agreementMethodInformation.iterator(); } /** @inheritDoc */ @@ -2820,7 +2539,7 @@ public class XMLCipher { /** @inheritDoc */ public KeyInfo getOriginatorKeyInfo() { - return (originatorKeyInfo); + return originatorKeyInfo; } /** @inheritDoc */ @@ -2830,7 +2549,7 @@ public class XMLCipher { /** @inheritDoc */ public KeyInfo getRecipientKeyInfo() { - return (recipientKeyInfo); + return recipientKeyInfo; } /** @inheritDoc */ @@ -2840,70 +2559,10 @@ public class XMLCipher { /** @inheritDoc */ public String getAlgorithm() { - return (algorithmURI); - } - - /** @param algorithm*/ - public void setAlgorithm(String algorithm) { - URI tmpAlgorithm = null; - try { - tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException mfue) { - //complain - } - algorithmURI = tmpAlgorithm.toString(); - } - - // - // - // - // - // - // - // - // - // - // - // - Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_AGREEMENTMETHOD); - result.setAttributeNS( - null, EncryptionConstants._ATT_ALGORITHM, algorithmURI); - if (null != kaNonce) { - result.appendChild( - ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KA_NONCE)).appendChild( - _contextDocument.createTextNode(new String(kaNonce))); - } - if (!agreementMethodInformation.isEmpty()) { - Iterator itr = agreementMethodInformation.iterator(); - while (itr.hasNext()) { - result.appendChild(itr.next()); - } - } - if (null != originatorKeyInfo) { - result.appendChild(originatorKeyInfo.getElement()); - } - if (null != recipientKeyInfo) { - result.appendChild(recipientKeyInfo.getElement()); - } - - return (result); + return algorithmURI; } } - // - // - // - // - // - // - // private class CipherDataImpl implements CipherData { private static final String valueMessage = "Data type is reference type."; @@ -2922,16 +2581,16 @@ public class XMLCipher { /** @inheritDoc */ public CipherValue getCipherValue() { - return (cipherValue); + return cipherValue; } /** @inheritDoc */ - public void setCipherValue(CipherValue value) throws - XMLEncryptionException { + public void setCipherValue(CipherValue value) throws XMLEncryptionException { if (cipherType == REFERENCE_TYPE) { - throw new XMLEncryptionException("empty", - new UnsupportedOperationException(valueMessage)); + throw new XMLEncryptionException( + "empty", new UnsupportedOperationException(valueMessage) + ); } cipherValue = value; @@ -2939,15 +2598,16 @@ public class XMLCipher { /** @inheritDoc */ public CipherReference getCipherReference() { - return (cipherReference); + return cipherReference; } /** @inheritDoc */ public void setCipherReference(CipherReference reference) throws - XMLEncryptionException { + XMLEncryptionException { if (cipherType == VALUE_TYPE) { - throw new XMLEncryptionException("empty", - new UnsupportedOperationException(referenceMessage)); + throw new XMLEncryptionException( + "empty", new UnsupportedOperationException(referenceMessage) + ); } cipherReference = reference; @@ -2955,77 +2615,59 @@ public class XMLCipher { /** @inheritDoc */ public int getDataType() { - return (cipherType); + return cipherType; } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERDATA); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERDATA + ); if (cipherType == VALUE_TYPE) { - result.appendChild( - ((CipherValueImpl) cipherValue).toElement()); + result.appendChild(((CipherValueImpl) cipherValue).toElement()); } else if (cipherType == REFERENCE_TYPE) { - result.appendChild( - ((CipherReferenceImpl) cipherReference).toElement()); - } else { - // complain + result.appendChild(((CipherReferenceImpl) cipherReference).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // private class CipherReferenceImpl implements CipherReference { private String referenceURI = null; private Transforms referenceTransforms = null; - private Attr referenceNode = null; + private Attr referenceNode = null; /** * @param uri */ public CipherReferenceImpl(String uri) { - /* Don't check validity of URI as may be "" */ + /* Don't check validity of URI as may be "" */ referenceURI = uri; - referenceNode = null; + referenceNode = null; } - /** - * @param uri - */ - public CipherReferenceImpl(Attr uri) { - referenceURI = uri.getNodeValue(); - referenceNode = uri; - } + /** + * @param uri + */ + public CipherReferenceImpl(Attr uri) { + referenceURI = uri.getNodeValue(); + referenceNode = uri; + } /** @inheritDoc */ public String getURI() { - return (referenceURI); + return referenceURI; } /** @inheritDoc */ - public Attr getURIAsAttr() { - return (referenceNode); - } + public Attr getURIAsAttr() { + return referenceNode; + } /** @inheritDoc */ public Transforms getTransforms() { - return (referenceTransforms); + return referenceTransforms; } /** @inheritDoc */ @@ -3033,91 +2675,53 @@ public class XMLCipher { referenceTransforms = transforms; } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERREFERENCE); - result.setAttributeNS( - null, EncryptionConstants._ATT_URI, referenceURI); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERREFERENCE + ); + result.setAttributeNS(null, EncryptionConstants._ATT_URI, referenceURI); if (null != referenceTransforms) { - result.appendChild( - ((TransformsImpl) referenceTransforms).toElement()); + result.appendChild(((TransformsImpl) referenceTransforms).toElement()); } - return (result); + return result; } } private class CipherValueImpl implements CipherValue { - private String cipherValue = null; - - // public CipherValueImpl(byte[] value) { - // cipherValue = value; - // } + private String cipherValue = null; /** * @param value */ public CipherValueImpl(String value) { - // cipherValue = value.getBytes(); - cipherValue = value; + cipherValue = value; } /** @inheritDoc */ - public String getValue() { - return (cipherValue); + public String getValue() { + return cipherValue; } - // public void setValue(byte[] value) { - // public void setValue(String value) { - // cipherValue = value; - // } - /** @inheritDoc */ + /** @inheritDoc */ public void setValue(String value) { - // cipherValue = value.getBytes(); - cipherValue = value; + cipherValue = value; } Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CIPHERVALUE); - result.appendChild(_contextDocument.createTextNode( - cipherValue)); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_CIPHERVALUE + ); + result.appendChild(contextDocument.createTextNode(cipherValue)); - return (result); + return result; } } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - private class EncryptedDataImpl extends EncryptedTypeImpl implements - EncryptedData { + private class EncryptedDataImpl extends EncryptedTypeImpl implements EncryptedData { + /** * @param data */ @@ -3125,94 +2729,49 @@ public class XMLCipher { super(data); } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDDATA); + Element result = + ElementProxy.createElementForFamily( + contextDocument, EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_ENCRYPTEDDATA + ); if (null != super.getId()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_ID, super.getId()); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId()); } if (null != super.getType()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_TYPE, super.getType()); + result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType()); } if (null != super.getMimeType()) { result.setAttributeNS( - null, EncryptionConstants._ATT_MIMETYPE, - super.getMimeType()); + null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType() + ); } if (null != super.getEncoding()) { result.setAttributeNS( - null, EncryptionConstants._ATT_ENCODING, - super.getEncoding()); + null, EncryptionConstants._ATT_ENCODING, super.getEncoding() + ); } if (null != super.getEncryptionMethod()) { - result.appendChild(((EncryptionMethodImpl) - super.getEncryptionMethod()).toElement()); + result.appendChild( + ((EncryptionMethodImpl)super.getEncryptionMethod()).toElement() + ); } if (null != super.getKeyInfo()) { - result.appendChild(super.getKeyInfo().getElement()); + result.appendChild(super.getKeyInfo().getElement().cloneNode(true)); } - result.appendChild( - ((CipherDataImpl) super.getCipherData()).toElement()); + result.appendChild(((CipherDataImpl) super.getCipherData()).toElement()); if (null != super.getEncryptionProperties()) { result.appendChild(((EncryptionPropertiesImpl) super.getEncryptionProperties()).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - private class EncryptedKeyImpl extends EncryptedTypeImpl implements - EncryptedKey { + private class EncryptedKeyImpl extends EncryptedTypeImpl implements EncryptedKey { private String keyRecipient = null; private ReferenceList referenceList = null; private String carriedName = null; @@ -3226,7 +2785,7 @@ public class XMLCipher { /** @inheritDoc */ public String getRecipient() { - return (keyRecipient); + return keyRecipient; } /** @inheritDoc */ @@ -3236,7 +2795,7 @@ public class XMLCipher { /** @inheritDoc */ public ReferenceList getReferenceList() { - return (referenceList); + return referenceList; } /** @inheritDoc */ @@ -3246,7 +2805,7 @@ public class XMLCipher { /** @inheritDoc */ public String getCarriedName() { - return (carriedName); + return carriedName; } /** @inheritDoc */ @@ -3254,84 +2813,60 @@ public class XMLCipher { carriedName = name; } - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTEDKEY); + Element result = + ElementProxy.createElementForFamily( + contextDocument, EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_ENCRYPTEDKEY + ); if (null != super.getId()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_ID, super.getId()); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, super.getId()); } if (null != super.getType()) { - result.setAttributeNS( - null, EncryptionConstants._ATT_TYPE, super.getType()); + result.setAttributeNS(null, EncryptionConstants._ATT_TYPE, super.getType()); } if (null != super.getMimeType()) { - result.setAttributeNS(null, - EncryptionConstants._ATT_MIMETYPE, super.getMimeType()); + result.setAttributeNS( + null, EncryptionConstants._ATT_MIMETYPE, super.getMimeType() + ); } if (null != super.getEncoding()) { - result.setAttributeNS(null, Constants._ATT_ENCODING, - super.getEncoding()); + result.setAttributeNS(null, Constants._ATT_ENCODING, super.getEncoding()); } if (null != getRecipient()) { - result.setAttributeNS(null, - EncryptionConstants._ATT_RECIPIENT, getRecipient()); + result.setAttributeNS( + null, EncryptionConstants._ATT_RECIPIENT, getRecipient() + ); } if (null != super.getEncryptionMethod()) { result.appendChild(((EncryptionMethodImpl) super.getEncryptionMethod()).toElement()); } if (null != super.getKeyInfo()) { - result.appendChild(super.getKeyInfo().getElement()); + result.appendChild(super.getKeyInfo().getElement().cloneNode(true)); } - result.appendChild( - ((CipherDataImpl) super.getCipherData()).toElement()); + result.appendChild(((CipherDataImpl) super.getCipherData()).toElement()); if (null != super.getEncryptionProperties()) { result.appendChild(((EncryptionPropertiesImpl) super.getEncryptionProperties()).toElement()); } if (referenceList != null && !referenceList.isEmpty()) { - result.appendChild(((ReferenceListImpl) - getReferenceList()).toElement()); + result.appendChild(((ReferenceListImpl)getReferenceList()).toElement()); } if (null != carriedName) { - Element element = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_CARRIEDKEYNAME); - Node node = _contextDocument.createTextNode(carriedName); + Element element = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_CARRIEDKEYNAME + ); + Node node = contextDocument.createTextNode(carriedName); element.appendChild(node); result.appendChild(element); } - return (result); + return result; } } @@ -3345,16 +2880,22 @@ public class XMLCipher { private CipherData cipherData = null; private EncryptionProperties encryptionProperties = null; + /** + * Constructor. + * @param data + */ protected EncryptedTypeImpl(CipherData data) { cipherData = data; } + /** * - * @return + * @return the Id */ public String getId() { - return (id); + return id; } + /** * * @param id @@ -3362,13 +2903,15 @@ public class XMLCipher { public void setId(String id) { this.id = id; } + /** * - * @return + * @return the type */ public String getType() { - return (type); + return type; } + /** * * @param type @@ -3380,18 +2923,20 @@ public class XMLCipher { URI tmpType = null; try { tmpType = new URI(type); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.type = tmpType.toString(); } } + /** * - * @return + * @return the MimeType */ public String getMimeType() { - return (mimeType); + return mimeType; } /** * @@ -3400,13 +2945,15 @@ public class XMLCipher { public void setMimeType(String type) { mimeType = type; } + /** * - * @return + * @return the encoding */ public String getEncoding() { - return (encoding); + return encoding; } + /** * * @param encoding @@ -3418,19 +2965,22 @@ public class XMLCipher { URI tmpEncoding = null; try { tmpEncoding = new URI(encoding); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.encoding = tmpEncoding.toString(); } } + /** * - * @return + * @return the EncryptionMethod */ public EncryptionMethod getEncryptionMethod() { - return (encryptionMethod); + return encryptionMethod; } + /** * * @param method @@ -3438,13 +2988,15 @@ public class XMLCipher { public void setEncryptionMethod(EncryptionMethod method) { encryptionMethod = method; } + /** * - * @return + * @return the KeyInfo */ public KeyInfo getKeyInfo() { - return (keyInfo); + return keyInfo; } + /** * * @param info @@ -3452,217 +3004,235 @@ public class XMLCipher { public void setKeyInfo(KeyInfo info) { keyInfo = info; } + /** * - * @return + * @return the CipherData */ public CipherData getCipherData() { - return (cipherData); + return cipherData; } + /** * - * @return + * @return the EncryptionProperties */ public EncryptionProperties getEncryptionProperties() { - return (encryptionProperties); + return encryptionProperties; } + /** * * @param properties */ - public void setEncryptionProperties( - EncryptionProperties properties) { + public void setEncryptionProperties(EncryptionProperties properties) { encryptionProperties = properties; } } - // - // - // - // - // - // - // - // private class EncryptionMethodImpl implements EncryptionMethod { private String algorithm = null; private int keySize = Integer.MIN_VALUE; private byte[] oaepParams = null; private List encryptionMethodInformation = null; + private String digestAlgorithm = null; + private String mgfAlgorithm = null; + /** - * + * Constructor. * @param algorithm */ public EncryptionMethodImpl(String algorithm) { URI tmpAlgorithm = null; try { tmpAlgorithm = new URI(algorithm); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.algorithm = tmpAlgorithm.toString(); encryptionMethodInformation = new LinkedList(); } + /** @inheritDoc */ public String getAlgorithm() { - return (algorithm); + return algorithm; } + /** @inheritDoc */ public int getKeySize() { - return (keySize); + return keySize; } + /** @inheritDoc */ public void setKeySize(int size) { keySize = size; } + /** @inheritDoc */ public byte[] getOAEPparams() { - return (oaepParams); + return oaepParams; } + /** @inheritDoc */ public void setOAEPparams(byte[] params) { oaepParams = params; } + + /** @inheritDoc */ + public void setDigestAlgorithm(String digestAlgorithm) { + this.digestAlgorithm = digestAlgorithm; + } + + /** @inheritDoc */ + public String getDigestAlgorithm() { + return digestAlgorithm; + } + + /** @inheritDoc */ + public void setMGFAlgorithm(String mgfAlgorithm) { + this.mgfAlgorithm = mgfAlgorithm; + } + + /** @inheritDoc */ + public String getMGFAlgorithm() { + return mgfAlgorithm; + } + /** @inheritDoc */ public Iterator getEncryptionMethodInformation() { - return (encryptionMethodInformation.iterator()); + return encryptionMethodInformation.iterator(); } + /** @inheritDoc */ public void addEncryptionMethodInformation(Element info) { encryptionMethodInformation.add(info); } + /** @inheritDoc */ public void removeEncryptionMethodInformation(Element info) { encryptionMethodInformation.remove(info); } - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONMETHOD); - result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, - algorithm); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONMETHOD + ); + result.setAttributeNS(null, EncryptionConstants._ATT_ALGORITHM, algorithm); if (keySize > 0) { result.appendChild( - ElementProxy.createElementForFamily(_contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_KEYSIZE).appendChild( - _contextDocument.createTextNode( - String.valueOf(keySize)))); + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_KEYSIZE + ).appendChild(contextDocument.createTextNode(String.valueOf(keySize)))); } if (null != oaepParams) { - result.appendChild( - ElementProxy.createElementForFamily(_contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_OAEPPARAMS).appendChild( - _contextDocument.createTextNode( - new String(oaepParams)))); + Element oaepElement = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_OAEPPARAMS + ); + oaepElement.appendChild(contextDocument.createTextNode(Base64.encode(oaepParams))); + result.appendChild(oaepElement); } - if (!encryptionMethodInformation.isEmpty()) { - Iterator itr = encryptionMethodInformation.iterator(); + if (digestAlgorithm != null) { + Element digestElement = + XMLUtils.createElementInSignatureSpace(contextDocument, Constants._TAG_DIGESTMETHOD); + digestElement.setAttributeNS(null, "Algorithm", digestAlgorithm); + result.appendChild(digestElement); + } + if (mgfAlgorithm != null) { + Element mgfElement = + XMLUtils.createElementInEncryption11Space( + contextDocument, EncryptionConstants._TAG_MGF + ); + mgfElement.setAttributeNS(null, "Algorithm", mgfAlgorithm); + mgfElement.setAttributeNS( + Constants.NamespaceSpecNS, + "xmlns:" + ElementProxy.getDefaultPrefix(EncryptionConstants.EncryptionSpec11NS), + EncryptionConstants.EncryptionSpec11NS + ); + result.appendChild(mgfElement); + } + Iterator itr = encryptionMethodInformation.iterator(); + while (itr.hasNext()) { result.appendChild(itr.next()); } - return (result); + return result; } } - // - // - // - // - // - // - // private class EncryptionPropertiesImpl implements EncryptionProperties { private String id = null; private List encryptionProperties = null; + /** - * - * + * Constructor. */ public EncryptionPropertiesImpl() { encryptionProperties = new LinkedList(); } + /** @inheritDoc */ public String getId() { - return (id); + return id; } + /** @inheritDoc */ public void setId(String id) { this.id = id; } + /** @inheritDoc */ public Iterator getEncryptionProperties() { - return (encryptionProperties.iterator()); + return encryptionProperties.iterator(); } + /** @inheritDoc */ public void addEncryptionProperty(EncryptionProperty property) { encryptionProperties.add(property); } + /** @inheritDoc */ public void removeEncryptionProperty(EncryptionProperty property) { encryptionProperties.remove(property); } - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONPROPERTIES); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTIES + ); if (null != id) { result.setAttributeNS(null, EncryptionConstants._ATT_ID, id); } Iterator itr = getEncryptionProperties(); while (itr.hasNext()) { - result.appendChild(((EncryptionPropertyImpl) - itr.next()).toElement()); + result.appendChild(((EncryptionPropertyImpl)itr.next()).toElement()); } - return (result); + return result; } } - // - // - // - // - // - // - // - // - // private class EncryptionPropertyImpl implements EncryptionProperty { private String target = null; private String id = null; - private HashMap attributeMap = new HashMap(); + private Map attributeMap = new HashMap(); private List encryptionInformation = null; /** - * - * + * Constructor. */ public EncryptionPropertyImpl() { encryptionInformation = new LinkedList(); } + /** @inheritDoc */ public String getTarget() { - return (target); + return target; } + /** @inheritDoc */ public void setTarget(String target) { if (target == null || target.length() == 0) { @@ -3670,163 +3240,144 @@ public class XMLCipher { } else if (target.startsWith("#")) { /* * This is a same document URI reference. Do not parse, - * because com.sun.org.apache.xml.internal.utils.URI considers this an - * illegal URI because it has no scheme. + * because it has no scheme. */ this.target = target; } else { URI tmpTarget = null; try { tmpTarget = new URI(target); - } catch (URI.MalformedURIException mfue) { - // complain + } catch (URISyntaxException ex) { + throw (IllegalArgumentException) + new IllegalArgumentException().initCause(ex); } this.target = tmpTarget.toString(); } } + /** @inheritDoc */ public String getId() { - return (id); + return id; } + /** @inheritDoc */ public void setId(String id) { this.id = id; } + /** @inheritDoc */ public String getAttribute(String attribute) { return attributeMap.get(attribute); } + /** @inheritDoc */ public void setAttribute(String attribute, String value) { attributeMap.put(attribute, value); } + /** @inheritDoc */ public Iterator getEncryptionInformation() { - return (encryptionInformation.iterator()); + return encryptionInformation.iterator(); } + /** @inheritDoc */ public void addEncryptionInformation(Element info) { encryptionInformation.add(info); } + /** @inheritDoc */ public void removeEncryptionInformation(Element info) { encryptionInformation.remove(info); } - // - // - // - // - // - // - // - // - // Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_ENCRYPTIONPROPERTY); + Element result = + XMLUtils.createElementInEncryptionSpace( + contextDocument, EncryptionConstants._TAG_ENCRYPTIONPROPERTY + ); if (null != target) { - result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, - target); + result.setAttributeNS(null, EncryptionConstants._ATT_TARGET, target); } if (null != id) { - result.setAttributeNS(null, EncryptionConstants._ATT_ID, - id); + result.setAttributeNS(null, EncryptionConstants._ATT_ID, id); } // TODO: figure out the anyAttribyte stuff... // TODO: figure out the any stuff... - return (result); + return result; } } - // - // - // - // - // - private class TransformsImpl extends - com.sun.org.apache.xml.internal.security.transforms.Transforms - implements Transforms { + private class TransformsImpl extends com.sun.org.apache.xml.internal.security.transforms.Transforms + implements Transforms { - /** - * Construct Transforms - */ - - public TransformsImpl() { - super(_contextDocument); - } - /** - * - * @param doc - */ - public TransformsImpl(Document doc) { - if (doc == null) { - throw new RuntimeException("Document is null"); - } - - this._doc = doc; - this._constructionElement = createElementForFamilyLocal(this._doc, - this.getBaseNamespace(), this.getBaseLocalName()); - } - /** - * - * @param element - * @throws XMLSignatureException - * @throws InvalidTransformException - * @throws XMLSecurityException - * @throws TransformationException - */ - public TransformsImpl(Element element) - throws XMLSignatureException, - InvalidTransformException, - XMLSecurityException, - TransformationException { - - super(element, ""); - - } + /** + * Construct Transforms + */ + public TransformsImpl() { + super(contextDocument); + } /** * - * @return + * @param doc */ - public Element toElement() { + public TransformsImpl(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - if (_doc == null) - _doc = _contextDocument; + this.doc = doc; + this.constructionElement = + createElementForFamilyLocal( + this.doc, this.getBaseNamespace(), this.getBaseLocalName() + ); + } - return getElement(); - } + /** + * + * @param element + * @throws XMLSignatureException + * @throws InvalidTransformException + * @throws XMLSecurityException + * @throws TransformationException + */ + public TransformsImpl(Element element) + throws XMLSignatureException, InvalidTransformException, + XMLSecurityException, TransformationException { + super(element, ""); + } + + /** + * + * @return the XML Element form of that Transforms + */ + public Element toElement() { + if (doc == null) { + doc = contextDocument; + } + + return getElement(); + } /** @inheritDoc */ - public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() { - return (this); - } + public com.sun.org.apache.xml.internal.security.transforms.Transforms getDSTransforms() { + return this; + } - - // Over-ride the namespace + // Over-ride the namespace /** @inheritDoc */ - public String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } - + public String getBaseNamespace() { + return EncryptionConstants.EncryptionSpecNS; + } } - // - // - // - // - // - // - // - // private class ReferenceListImpl implements ReferenceList { private Class sentry; private List references; + /** - * + * Constructor. * @param type */ public ReferenceListImpl(int type) { @@ -3839,13 +3390,15 @@ public class XMLCipher { } references = new LinkedList(); } + /** @inheritDoc */ public void add(Reference reference) { if (!reference.getClass().equals(sentry)) { throw new IllegalArgumentException(); } - references.add(reference); + references.add(reference); } + /** @inheritDoc */ public void remove(Reference reference) { if (!reference.getClass().equals(sentry)) { @@ -3853,39 +3406,45 @@ public class XMLCipher { } references.remove(reference); } + /** @inheritDoc */ public int size() { - return (references.size()); + return references.size(); } + /** @inheritDoc */ public boolean isEmpty() { - return (references.isEmpty()); + return references.isEmpty(); } + /** @inheritDoc */ public Iterator getReferences() { - return (references.iterator()); + return references.iterator(); } Element toElement() { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - EncryptionConstants._TAG_REFERENCELIST); + Element result = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + EncryptionConstants._TAG_REFERENCELIST + ); Iterator eachReference = references.iterator(); while (eachReference.hasNext()) { Reference reference = eachReference.next(); - result.appendChild( - ((ReferenceImpl) reference).toElement()); + result.appendChild(((ReferenceImpl) reference).toElement()); } - return (result); + return result; } + /** @inheritDoc */ public Reference newDataReference(String uri) { - return (new DataReference(uri)); + return new DataReference(uri); } + /** @inheritDoc */ public Reference newKeyReference(String uri) { - return (new KeyReference(uri)); + return new KeyReference(uri); } /** @@ -3898,68 +3457,81 @@ public class XMLCipher { private String uri; private List referenceInformation; - ReferenceImpl(String _uri) { - this.uri = _uri; + ReferenceImpl(String uri) { + this.uri = uri; referenceInformation = new LinkedList(); } + + /** @inheritDoc */ + public abstract String getType(); + /** @inheritDoc */ public String getURI() { - return (uri); + return uri; } + /** @inheritDoc */ public Iterator getElementRetrievalInformation() { - return (referenceInformation.iterator()); + return referenceInformation.iterator(); } + /** @inheritDoc */ - public void setURI(String _uri) { - this.uri = _uri; + public void setURI(String uri) { + this.uri = uri; } + /** @inheritDoc */ public void removeElementRetrievalInformation(Element node) { referenceInformation.remove(node); } + /** @inheritDoc */ public void addElementRetrievalInformation(Element node) { referenceInformation.add(node); } - /** - * - * @return - */ - public abstract Element toElement(); - Element toElement(String tagName) { - Element result = ElementProxy.createElementForFamily( - _contextDocument, - EncryptionConstants.EncryptionSpecNS, - tagName); + /** + * @return the XML Element form of that Reference + */ + public Element toElement() { + String tagName = getType(); + Element result = + ElementProxy.createElementForFamily( + contextDocument, + EncryptionConstants.EncryptionSpecNS, + tagName + ); result.setAttribute(EncryptionConstants._ATT_URI, uri); // TODO: Need to martial referenceInformation // Figure out how to make this work.. // - return (result); + return result; } } private class DataReference extends ReferenceImpl { + DataReference(String uri) { super(uri); } + /** @inheritDoc */ - public Element toElement() { - return super.toElement(EncryptionConstants._TAG_DATAREFERENCE); + public String getType() { + return EncryptionConstants._TAG_DATAREFERENCE; } } private class KeyReference extends ReferenceImpl { + KeyReference(String uri) { - super (uri); + super(uri); } + /** @inheritDoc */ - public Element toElement() { - return super.toElement(EncryptionConstants._TAG_KEYREFERENCE); + public String getType() { + return EncryptionConstants._TAG_KEYREFERENCE; } } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java index 65b9a604b66..583042680d1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherInput.java @@ -2,23 +2,24 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package com.sun.org.apache.xml.internal.security.encryption; import java.io.IOException; @@ -32,7 +33,6 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformationExcepti import org.w3c.dom.Attr; import com.sun.org.apache.xml.internal.security.utils.Base64; - /** * XMLCipherInput is used to wrap input passed into the * XMLCipher encryption operations. @@ -50,77 +50,79 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; public class XMLCipherInput { private static java.util.logging.Logger logger = - java.util.logging.Logger.getLogger(XMLCipher.class.getName()); + java.util.logging.Logger.getLogger(XMLCipherInput.class.getName()); - /** The data we are working with */ - private CipherData _cipherData; + /** The data we are working with */ + private CipherData cipherData; - /** MODES */ - private int _mode; + /** MODES */ + private int mode; - /** - * Constructor for processing encrypted octets - * - * @param data The CipherData object to read the bytes from - * @throws XMLEncryptionException {@link XMLEncryptionException} - */ - - public XMLCipherInput(CipherData data) throws XMLEncryptionException { - - _cipherData = data; - _mode = XMLCipher.DECRYPT_MODE; - if (_cipherData == null) { - throw new XMLEncryptionException("CipherData is null"); - } + private boolean secureValidation; + /** + * Constructor for processing encrypted octets + * + * @param data The CipherData object to read the bytes from + * @throws XMLEncryptionException {@link XMLEncryptionException} + */ + public XMLCipherInput(CipherData data) throws XMLEncryptionException { + cipherData = data; + mode = XMLCipher.DECRYPT_MODE; + if (cipherData == null) { + throw new XMLEncryptionException("CipherData is null"); } + } - /** - * Constructor for processing encrypted octets - * - * @param input The EncryptedType object to read - * the bytes from. - * @throws XMLEncryptionException {@link XMLEncryptionException} - */ - - public XMLCipherInput(EncryptedType input) throws XMLEncryptionException { - - _cipherData = ((input == null) ? null : input.getCipherData()); - _mode = XMLCipher.DECRYPT_MODE; - if (_cipherData == null) { - throw new XMLEncryptionException("CipherData is null"); - } - + /** + * Constructor for processing encrypted octets + * + * @param input The EncryptedType object to read + * the bytes from. + * @throws XMLEncryptionException {@link XMLEncryptionException} + */ + public XMLCipherInput(EncryptedType input) throws XMLEncryptionException { + cipherData = ((input == null) ? null : input.getCipherData()); + mode = XMLCipher.DECRYPT_MODE; + if (cipherData == null) { + throw new XMLEncryptionException("CipherData is null"); } + } - /** - * Dereferences the input and returns it as a single byte array. - * - * @throws XMLEncryptionException + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + + /** + * Dereferences the input and returns it as a single byte array. + * + * @throws XMLEncryptionException * @return The decripted bytes. - */ - - public byte[] getBytes() throws XMLEncryptionException { - - if (_mode == XMLCipher.DECRYPT_MODE) { - return getDecryptBytes(); - } - return null; + */ + public byte[] getBytes() throws XMLEncryptionException { + if (mode == XMLCipher.DECRYPT_MODE) { + return getDecryptBytes(); } + return null; + } /** * Internal method to get bytes in decryption mode - * @return the decripted bytes + * @return the decrypted bytes * @throws XMLEncryptionException */ private byte[] getDecryptBytes() throws XMLEncryptionException { - String base64EncodedEncryptedOctets = null; - if (_cipherData.getDataType() == CipherData.REFERENCE_TYPE) { + if (cipherData.getDataType() == CipherData.REFERENCE_TYPE) { // Fun time! - logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); - CipherReference cr = _cipherData.getCipherReference(); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Found a reference type CipherData"); + } + CipherReference cr = cipherData.getCipherReference(); // Need to wrap the uri in an Attribute node so that we can // Pass to the resource resolvers @@ -130,25 +132,32 @@ public class XMLCipherInput { try { ResourceResolver resolver = - ResourceResolver.getInstance(uriAttr, null); - input = resolver.resolve(uriAttr, null); + ResourceResolver.getInstance(uriAttr, null, secureValidation); + input = resolver.resolve(uriAttr, null, secureValidation); } catch (ResourceResolverException ex) { throw new XMLEncryptionException("empty", ex); } if (input != null) { - logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Managed to resolve URI \"" + cr.getURI() + "\""); + } } else { - logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Failed to resolve URI \"" + cr.getURI() + "\""); + } } // Lets see if there are any transforms Transforms transforms = cr.getTransforms(); if (transforms != null) { - logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Have transforms in cipher reference"); + } try { com.sun.org.apache.xml.internal.security.transforms.Transforms dsTransforms = transforms.getDSTransforms(); + dsTransforms.setSecureValidation(secureValidation); input = dsTransforms.performTransforms(input); } catch (TransformationException ex) { throw new XMLEncryptionException("empty", ex); @@ -163,23 +172,21 @@ public class XMLCipherInput { throw new XMLEncryptionException("empty", ex); } - // retrieve the cipher text - } else if (_cipherData.getDataType() == CipherData.VALUE_TYPE) { - base64EncodedEncryptedOctets = - _cipherData.getCipherValue().getValue(); + // retrieve the cipher text + } else if (cipherData.getDataType() == CipherData.VALUE_TYPE) { + base64EncodedEncryptedOctets = cipherData.getCipherValue().getValue(); } else { throw new XMLEncryptionException("CipherData.getDataType() returned unexpected value"); } - logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + if (logger.isLoggable(java.util.logging.Level.FINE)) { + logger.log(java.util.logging.Level.FINE, "Encrypted octets:\n" + base64EncodedEncryptedOctets); + } - byte[] encryptedBytes = null; try { - encryptedBytes = Base64.decode(base64EncodedEncryptedOctets); + return Base64.decode(base64EncodedEncryptedOctets); } catch (Base64DecodingException bde) { throw new XMLEncryptionException("empty", bde); } - - return (encryptedBytes); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java index e25e1fa2a61..1c74f02060d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLCipherParameters.java @@ -2,104 +2,85 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ - package com.sun.org.apache.xml.internal.security.encryption; - /** * Constants */ public interface XMLCipherParameters { - /** */ - public static final String AES_128 = + String AES_128 = "http://www.w3.org/2001/04/xmlenc#aes128-cbc"; - /** */ - public static final String AES_256 = + String AES_256 = "http://www.w3.org/2001/04/xmlenc#aes256-cbc"; - /** */ - public static final String AES_192 = + String AES_192 = "http://www.w3.org/2001/04/xmlenc#aes192-cbc"; - /** */ - public static final String RSA_1_5 = + String RSA_1_5 = "http://www.w3.org/2001/04/xmlenc#rsa-1_5"; - /** */ - public static final String RSA_OAEP = + String RSA_OAEP = "http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"; - /** */ - public static final String DIFFIE_HELLMAN = + String DIFFIE_HELLMAN = "http://www.w3.org/2001/04/xmlenc#dh"; - /** */ - public static final String TRIPLEDES_KEYWRAP = + String TRIPLEDES_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-tripledes"; - /** */ - public static final String AES_128_KEYWRAP = + String AES_128_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes128"; - /** */ - public static final String AES_256_KEYWRAP = + String AES_256_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes256"; - /** */ - public static final String AES_192_KEYWRAP = + String AES_192_KEYWRAP = "http://www.w3.org/2001/04/xmlenc#kw-aes192"; - /** */ - public static final String SHA1 = + String SHA1 = "http://www.w3.org/2000/09/xmldsig#sha1"; - /** */ - public static final String SHA256 = + String SHA256 = "http://www.w3.org/2001/04/xmlenc#sha256"; - /** */ - public static final String SHA512 = + String SHA512 = "http://www.w3.org/2001/04/xmlenc#sha512"; - /** */ - public static final String RIPEMD_160 = + String RIPEMD_160 = "http://www.w3.org/2001/04/xmlenc#ripemd160"; - /** */ - public static final String XML_DSIG = + String XML_DSIG = "http://www.w3.org/2000/09/xmldsig#"; - /** */ - public static final String N14C_XML = + String N14C_XML = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; - /** */ - public static final String N14C_XML_CMMNTS = + String N14C_XML_CMMNTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; - /** */ - public static final String EXCL_XML_N14C = + String EXCL_XML_N14C = "http://www.w3.org/2001/10/xml-exc-c14n#"; - /** */ - public static final String EXCL_XML_N14C_CMMNTS = + String EXCL_XML_N14C_CMMNTS = "http://www.w3.org/2001/10/xml-exc-c14n#WithComments"; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java index 0c913145058..8d027a2d893 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/encryption/XMLEncryptionException.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2003-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.encryption; @@ -26,49 +28,53 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; * */ public class XMLEncryptionException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** + /** * - * - */ - public XMLEncryptionException() { - super(); - } - /** - * - * @param _msgID - */ - public XMLEncryptionException(String _msgID) { - super(_msgID); - } - /** - * - * @param _msgID - * @param exArgs - */ - public XMLEncryptionException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } - /** - * - * @param _msgID - * @param _originalException - */ - public XMLEncryptionException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } - /** - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLEncryptionException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + */ + private static final long serialVersionUID = 1L; + + /** + * + * + */ + public XMLEncryptionException() { + super(); + } + + /** + * + * @param msgID + */ + public XMLEncryptionException(String msgID) { + super(msgID); + } + + /** + * + * @param msgID + * @param exArgs + */ + public XMLEncryptionException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } + + /** + * + * @param msgID + * @param originalException + */ + public XMLEncryptionException(String msgID, Exception originalException) { + super(msgID, originalException); + + } + + /** + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLEncryptionException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java index bbdbaefa27d..1dcb10b9ec6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/AlgorithmAlreadyRegisteredException.java @@ -2,88 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.exceptions; - - -/** - * - * - * - * - * @author Christian Geuer-Pollmann - * - */ public class AlgorithmAlreadyRegisteredException extends XMLSecurityException { + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor AlgorithmAlreadyRegisteredException + * + */ + public AlgorithmAlreadyRegisteredException() { + super(); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - */ - public AlgorithmAlreadyRegisteredException() { - super(); - } + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + */ + public AlgorithmAlreadyRegisteredException(String msgID) { + super(msgID); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - */ - public AlgorithmAlreadyRegisteredException(String _msgID) { - super(_msgID); - } + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param exArgs + */ + public AlgorithmAlreadyRegisteredException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - */ - public AlgorithmAlreadyRegisteredException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param originalException + */ + public AlgorithmAlreadyRegisteredException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param _originalException - */ - public AlgorithmAlreadyRegisteredException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor AlgorithmAlreadyRegisteredException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public AlgorithmAlreadyRegisteredException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } - /** - * Constructor AlgorithmAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public AlgorithmAlreadyRegisteredException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java index bf039a2602e..0b982c0b241 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/Base64DecodingException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.exceptions; - - /** * This Exception is thrown if decoding of Base64 data fails. * @@ -29,58 +29,54 @@ package com.sun.org.apache.xml.internal.security.exceptions; */ public class Base64DecodingException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; - /** - * Constructor Base64DecodingException - * - */ - public Base64DecodingException() { - super(); - } + /** + * Constructor Base64DecodingException + * + */ + public Base64DecodingException() { + super(); + } - /** - * Constructor Base64DecodingException - * - * @param _msgID - */ - public Base64DecodingException(String _msgID) { - super(_msgID); - } + /** + * Constructor Base64DecodingException + * + * @param msgID + */ + public Base64DecodingException(String msgID) { + super(msgID); + } - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param exArgs - */ - public Base64DecodingException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param exArgs + */ + public Base64DecodingException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param _originalException - */ - public Base64DecodingException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param originalException + */ + public Base64DecodingException(String msgID, Exception originalException) { + super(msgID, originalException); + } + + /** + * Constructor Base64DecodingException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public Base64DecodingException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } - /** - * Constructor Base64DecodingException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public Base64DecodingException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java index 4a4be909ab2..63cb4572e49 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.exceptions; - - import java.io.PrintStream; import java.io.PrintWriter; import java.text.MessageFormat; @@ -29,7 +29,6 @@ import java.text.MessageFormat; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; - /** * The mother of all Exceptions in this bundle. It allows exceptions to have * their messages translated to the different locales. @@ -64,186 +63,154 @@ import com.sun.org.apache.xml.internal.security.utils.I18n; */ public class XMLSecurityException extends Exception { + /** + * + */ + private static final long serialVersionUID = 1L; + /** Field msgID */ + protected String msgID; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor XMLSecurityException + * + */ + public XMLSecurityException() { + super("Missing message string"); - /** Field originalException */ - protected Exception originalException = null; + this.msgID = null; + } - /** Field msgID */ - protected String msgID; + /** + * Constructor XMLSecurityException + * + * @param msgID + */ + public XMLSecurityException(String msgID) { + super(I18n.getExceptionMessage(msgID)); - /** - * Constructor XMLSecurityException - * - */ - public XMLSecurityException() { + this.msgID = msgID; + } - super("Missing message string"); + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param exArgs + */ + public XMLSecurityException(String msgID, Object exArgs[]) { - this.msgID = null; - this.originalException = null; - } + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - /** - * Constructor XMLSecurityException - * - * @param _msgID - */ - public XMLSecurityException(String _msgID) { + this.msgID = msgID; + } - super(I18n.getExceptionMessage(_msgID)); + /** + * Constructor XMLSecurityException + * + * @param originalException + */ + public XMLSecurityException(Exception originalException) { - this.msgID = _msgID; - this.originalException = null; - } + super("Missing message ID to locate message string in resource bundle \"" + + Constants.exceptionMessagesResourceBundleBase + + "\". Original Exception was a " + + originalException.getClass().getName() + " and message " + + originalException.getMessage(), originalException); + } - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param exArgs - */ - public XMLSecurityException(String _msgID, Object exArgs[]) { + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param originalException + */ + public XMLSecurityException(String msgID, Exception originalException) { + super(I18n.getExceptionMessage(msgID, originalException), originalException); - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * Constructor XMLSecurityException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSecurityException(String msgID, Object exArgs[], Exception originalException) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs), originalException); - /** - * Constructor XMLSecurityException - * - * @param _originalException - */ - public XMLSecurityException(Exception _originalException) { + this.msgID = msgID; + } - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + _originalException.getClass().getName() + " and message " - + _originalException.getMessage()); + /** + * Method getMsgID + * + * @return the messageId + */ + public String getMsgID() { + if (msgID == null) { + return "Missing message ID"; + } + return msgID; + } - this.originalException = _originalException; - } + /** @inheritDoc */ + public String toString() { + String s = this.getClass().getName(); + String message = super.getLocalizedMessage(); - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param _originalException - */ - public XMLSecurityException(String _msgID, Exception _originalException) { + if (message != null) { + message = s + ": " + message; + } else { + message = s; + } - super(I18n.getExceptionMessage(_msgID, _originalException)); + if (super.getCause() != null) { + message = message + "\nOriginal Exception was " + super.getCause().toString(); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + return message; + } - /** - * Constructor XMLSecurityException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSecurityException(String _msgID, Object exArgs[], - Exception _originalException) { + /** + * Method printStackTrace + * + */ + public void printStackTrace() { + synchronized (System.err) { + super.printStackTrace(System.err); + } + } - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + /** + * Method printStackTrace + * + * @param printwriter + */ + public void printStackTrace(PrintWriter printwriter) { + super.printStackTrace(printwriter); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + /** + * Method printStackTrace + * + * @param printstream + */ + public void printStackTrace(PrintStream printstream) { + super.printStackTrace(printstream); + } - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { - - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** @inheritDoc */ - public String toString() { - - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (originalException != null) { - message = message + "\nOriginal Exception was " - + originalException.toString(); - } - - return message; - } - - /** - * Method printStackTrace - * - */ - public void printStackTrace() { - - synchronized (System.err) { - super.printStackTrace(System.err); - - if (this.originalException != null) { - this.originalException.printStackTrace(System.err); - } - } - } - - /** - * Method printStackTrace - * - * @param printwriter - */ - public void printStackTrace(PrintWriter printwriter) { - - super.printStackTrace(printwriter); - - if (this.originalException != null) { - this.originalException.printStackTrace(printwriter); - } - } - - /** - * Method printStackTrace - * - * @param printstream - */ - public void printStackTrace(PrintStream printstream) { - - super.printStackTrace(printstream); - - if (this.originalException != null) { - this.originalException.printStackTrace(printstream); - } - } - - /** - * Method getOriginalException - * - * @return the original exception - */ - public Exception getOriginalException() { - return originalException; - } + /** + * Method getOriginalException + * + * @return the original exception + */ + public Exception getOriginalException() { + if (this.getCause() instanceof Exception) { + return (Exception)this.getCause(); + } + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java index 69a803b04c9..06cb920dabe 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/exceptions/XMLSecurityRuntimeException.java @@ -1,3 +1,25 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package com.sun.org.apache.xml.internal.security.exceptions; import java.io.PrintStream; @@ -39,186 +61,152 @@ import com.sun.org.apache.xml.internal.security.utils.I18n; * * @author Christian Geuer-Pollmann */ -public class XMLSecurityRuntimeException - extends RuntimeException { - /** - * - */ +public class XMLSecurityRuntimeException extends RuntimeException { + private static final long serialVersionUID = 1L; - /** Field originalException */ - protected Exception originalException = null; + /** Field msgID */ + protected String msgID; - /** Field msgID */ - protected String msgID; + /** + * Constructor XMLSecurityRuntimeException + * + */ + public XMLSecurityRuntimeException() { + super("Missing message string"); - /** - * Constructor XMLSecurityRuntimeException - * - */ - public XMLSecurityRuntimeException() { + this.msgID = null; + } - super("Missing message string"); + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + */ + public XMLSecurityRuntimeException(String msgID) { + super(I18n.getExceptionMessage(msgID)); - this.msgID = null; - this.originalException = null; - } + this.msgID = msgID; + } - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - */ - public XMLSecurityRuntimeException(String _msgID) { + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param exArgs + */ + public XMLSecurityRuntimeException(String msgID, Object exArgs[]) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - super(I18n.getExceptionMessage(_msgID)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * Constructor XMLSecurityRuntimeException + * + * @param originalException + */ + public XMLSecurityRuntimeException(Exception originalException) { + super("Missing message ID to locate message string in resource bundle \"" + + Constants.exceptionMessagesResourceBundleBase + + "\". Original Exception was a " + + originalException.getClass().getName() + " and message " + + originalException.getMessage(), originalException); + } - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param exArgs - */ - public XMLSecurityRuntimeException(String _msgID, Object exArgs[]) { + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param originalException + */ + public XMLSecurityRuntimeException(String msgID, Exception originalException) { + super(I18n.getExceptionMessage(msgID, originalException), originalException); - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + this.msgID = msgID; + } - this.msgID = _msgID; - this.originalException = null; - } + /** + * Constructor XMLSecurityRuntimeException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSecurityRuntimeException(String msgID, Object exArgs[], Exception originalException) { + super(MessageFormat.format(I18n.getExceptionMessage(msgID), exArgs)); - /** - * Constructor XMLSecurityRuntimeException - * - * @param _originalException - */ - public XMLSecurityRuntimeException(Exception _originalException) { + this.msgID = msgID; + } - super("Missing message ID to locate message string in resource bundle \"" - + Constants.exceptionMessagesResourceBundleBase - + "\". Original Exception was a " - + _originalException.getClass().getName() + " and message " - + _originalException.getMessage()); + /** + * Method getMsgID + * + * @return the messageId + */ + public String getMsgID() { + if (msgID == null) { + return "Missing message ID"; + } + return msgID; + } - this.originalException = _originalException; - } + /** @inheritDoc */ + public String toString() { + String s = this.getClass().getName(); + String message = super.getLocalizedMessage(); - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param _originalException - */ - public XMLSecurityRuntimeException(String _msgID, Exception _originalException) { + if (message != null) { + message = s + ": " + message; + } else { + message = s; + } - super(I18n.getExceptionMessage(_msgID, _originalException)); + if (this.getCause() != null) { + message = message + "\nOriginal Exception was " + this.getCause().toString(); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + return message; + } - /** - * Constructor XMLSecurityRuntimeException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSecurityRuntimeException(String _msgID, Object exArgs[], - Exception _originalException) { + /** + * Method printStackTrace + * + */ + public void printStackTrace() { + synchronized (System.err) { + super.printStackTrace(System.err); + } + } - super(MessageFormat.format(I18n.getExceptionMessage(_msgID), exArgs)); + /** + * Method printStackTrace + * + * @param printwriter + */ + public void printStackTrace(PrintWriter printwriter) { + super.printStackTrace(printwriter); + } - this.msgID = _msgID; - this.originalException = _originalException; - } + /** + * Method printStackTrace + * + * @param printstream + */ + public void printStackTrace(PrintStream printstream) { + super.printStackTrace(printstream); + } - /** - * Method getMsgID - * - * @return the messageId - */ - public String getMsgID() { + /** + * Method getOriginalException + * + * @return the original exception + */ + public Exception getOriginalException() { + if (this.getCause() instanceof Exception) { + return (Exception)this.getCause(); + } + return null; + } - if (msgID == null) { - return "Missing message ID"; - } - return msgID; - } - - /** @inheritDoc */ - public String toString() { - - String s = this.getClass().getName(); - String message = super.getLocalizedMessage(); - - if (message != null) { - message = s + ": " + message; - } else { - message = s; - } - - if (originalException != null) { - message = message + "\nOriginal Exception was " - + originalException.toString(); - } - - return message; - } - - /** - * Method printStackTrace - * - */ - public void printStackTrace() { - - synchronized (System.err) { - super.printStackTrace(System.err); - - if (this.originalException != null) { - this.originalException.printStackTrace(System.err); - } - } - } - - /** - * Method printStackTrace - * - * @param printwriter - */ - public void printStackTrace(PrintWriter printwriter) { - - super.printStackTrace(printwriter); - - if (this.originalException != null) { - this.originalException.printStackTrace(printwriter); - } - } - - /** - * Method printStackTrace - * - * @param printstream - */ - public void printStackTrace(PrintStream printstream) { - - super.printStackTrace(printstream); - - if (this.originalException != null) { - this.originalException.printStackTrace(printstream); - } - } - - /** - * Method getOriginalException - * - * @return the original exception - */ - public Exception getOriginalException() { - return originalException; - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java index 6477d9bba2c..ad807c2d862 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/ContentHandlerAlreadyRegisteredException.java @@ -2,89 +2,83 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +public class ContentHandlerAlreadyRegisteredException extends XMLSecurityException { -/** - * - * @author $Author: mullan $ - */ -public class ContentHandlerAlreadyRegisteredException - extends XMLSecurityException { + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + */ + public ContentHandlerAlreadyRegisteredException() { + super(); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - */ - public ContentHandlerAlreadyRegisteredException() { - super(); - } + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + */ + public ContentHandlerAlreadyRegisteredException(String msgID) { + super(msgID); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - */ - public ContentHandlerAlreadyRegisteredException(String _msgID) { - super(_msgID); - } + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + * @param exArgs + */ + public ContentHandlerAlreadyRegisteredException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - */ - public ContentHandlerAlreadyRegisteredException(String _msgID, - Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + * @param originalException + */ + public ContentHandlerAlreadyRegisteredException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - * @param _originalException - */ - public ContentHandlerAlreadyRegisteredException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor ContentHandlerAlreadyRegisteredException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public ContentHandlerAlreadyRegisteredException( + String msgID, Object exArgs[], Exception originalException + ) { + super(msgID, exArgs, originalException); + } - /** - * Constructor ContentHandlerAlreadyRegisteredException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public ContentHandlerAlreadyRegisteredException(String _msgID, - Object exArgs[], Exception _originalException) { - super(_msgID, exArgs, _originalException); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java index 3c273dea7ac..6716d80d899 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyInfo.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys; - - +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.ArrayList; -import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -35,6 +35,8 @@ import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey; import com.sun.org.apache.xml.internal.security.encryption.XMLCipher; import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue; +import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference; import com.sun.org.apache.xml.internal.security.keys.content.KeyName; import com.sun.org.apache.xml.internal.security.keys.content.KeyValue; import com.sun.org.apache.xml.internal.security.keys.content.MgmtData; @@ -49,9 +51,8 @@ import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverExce import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import com.sun.org.apache.xml.internal.security.transforms.Transforms; -import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; +import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Attr; @@ -60,7 +61,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * This class stand for KeyInfo Element that may contain keys, names, * certificates and other public key management information, @@ -91,639 +91,769 @@ import org.w3c.dom.NodeList; * The containsXXX() methods return whether the KeyInfo * contains the corresponding type. * - * @author $Author: mullan $ */ public class KeyInfo extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(KeyInfo.class.getName()); - List x509Datas=null; - List encryptedKeys=null; - static final List nullList; + // We need at least one StorageResolver otherwise + // the KeyResolvers would not be called. + // The default StorageResolver is null. + + private List x509Datas = null; + private List encryptedKeys = null; + + private static final List nullList; static { List list = new ArrayList(1); list.add(null); - nullList = Collections.unmodifiableList(list); + nullList = java.util.Collections.unmodifiableList(list); } - /** - * Constructor KeyInfo - * @param doc - */ - public KeyInfo(Document doc) { - - super(doc); - - XMLUtils.addReturnToElement(this._constructionElement); - - } - - /** - * Constructor KeyInfo - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public KeyInfo(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - - Attr attr = element.getAttributeNodeNS(null, "Id"); - if (attr != null) { - element.setIdAttributeNode(attr, true); - } - } - - /** - * Sets the Id attribute - * - * @param Id ID - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Method addKeyName - * - * @param keynameString - */ - public void addKeyName(String keynameString) { - this.add(new KeyName(this._doc, keynameString)); - } - - /** - * Method add - * - * @param keyname - */ - public void add(KeyName keyname) { - - this._constructionElement.appendChild(keyname.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addKeyValue - * - * @param pk - */ - public void addKeyValue(PublicKey pk) { - this.add(new KeyValue(this._doc, pk)); - } - - /** - * Method addKeyValue - * - * @param unknownKeyValueElement - */ - public void addKeyValue(Element unknownKeyValueElement) { - this.add(new KeyValue(this._doc, unknownKeyValueElement)); - } - - /** - * Method add - * - * @param dsakeyvalue - */ - public void add(DSAKeyValue dsakeyvalue) { - this.add(new KeyValue(this._doc, dsakeyvalue)); - } - - /** - * Method add - * - * @param rsakeyvalue - */ - public void add(RSAKeyValue rsakeyvalue) { - this.add(new KeyValue(this._doc, rsakeyvalue)); - } - - /** - * Method add - * - * @param pk - */ - public void add(PublicKey pk) { - this.add(new KeyValue(this._doc, pk)); - } - - /** - * Method add - * - * @param keyvalue - */ - public void add(KeyValue keyvalue) { - this._constructionElement.appendChild(keyvalue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addMgmtData - * - * @param mgmtdata - */ - public void addMgmtData(String mgmtdata) { - this.add(new MgmtData(this._doc, mgmtdata)); - } - - /** - * Method add - * - * @param mgmtdata - */ - public void add(MgmtData mgmtdata) { - this._constructionElement.appendChild(mgmtdata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addPGPData - * - * @param pgpdata - */ - public void add(PGPData pgpdata) { - this._constructionElement.appendChild(pgpdata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addRetrievalMethod - * - * @param URI - * @param transforms - * @param Type - */ - public void addRetrievalMethod(String URI, Transforms transforms, - String Type) { - this.add(new RetrievalMethod(this._doc, URI, transforms, Type)); - } - - /** - * Method add - * - * @param retrievalmethod - */ - public void add(RetrievalMethod retrievalmethod) { - this._constructionElement.appendChild(retrievalmethod.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method add - * - * @param spkidata - */ - public void add(SPKIData spkidata) { - this._constructionElement.appendChild(spkidata.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addX509Data - * - * @param x509data - */ - public void add(X509Data x509data) { - if (x509Datas==null) - x509Datas=new ArrayList(); - x509Datas.add(x509data); - this._constructionElement.appendChild(x509data.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method addEncryptedKey - * - * @param encryptedKey - * @throws XMLEncryptionException - */ - - public void add(EncryptedKey encryptedKey) - throws XMLEncryptionException { - if (encryptedKeys==null) - encryptedKeys=new ArrayList(); - encryptedKeys.add(encryptedKey); - XMLCipher cipher = XMLCipher.getInstance(); - this._constructionElement.appendChild(cipher.martial(encryptedKey)); - } - - /** - * Method addUnknownElement - * - * @param element - */ - public void addUnknownElement(Element element) { - this._constructionElement.appendChild(element); - XMLUtils.addReturnToElement(this._constructionElement); - } - - /** - * Method lengthKeyName - * - * @return the number of the KeyName tags - */ - public int lengthKeyName() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME); - } - - /** - * Method lengthKeyValue - * - *@return the number of the KeyValue tags - */ - public int lengthKeyValue() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE); - } - - /** - * Method lengthMgmtData - * - *@return the number of the MgmtData tags - */ - public int lengthMgmtData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA); - } - - /** - * Method lengthPGPData - * - *@return the number of the PGPDat. tags - */ - public int lengthPGPData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA); - } - - /** - * Method lengthRetrievalMethod - * - *@return the number of the RetrievalMethod tags - */ - public int lengthRetrievalMethod() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_RETRIEVALMETHOD); - } - - /** - * Method lengthSPKIData - * - *@return the number of the SPKIData tags - */ - public int lengthSPKIData() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA); - } - - /** - * Method lengthX509Data - * - *@return the number of the X509Data tags - */ - public int lengthX509Data() { - if (x509Datas!=null) { - return x509Datas.size(); - } - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA); - } - - /** - * Method lengthUnknownElement - * NOTE posibly buggy. - *@return the number of the UnknownElement tags - */ - public int lengthUnknownElement() { - - int res = 0; - NodeList nl = this._constructionElement.getChildNodes(); - - for (int i = 0; i < nl.getLength(); i++) { - Node current = nl.item(i); - - /** - * $todo$ using this method, we don't see unknown Elements - * from Signature NS; revisit - */ - if ((current.getNodeType() == Node.ELEMENT_NODE) - && current.getNamespaceURI() - .equals(Constants.SignatureSpecNS)) { - res++; - } - } - - return res; - } - - /** - * Method itemKeyName - * - * @param i - * @return the asked KeyName element, null if the index is too big - * @throws XMLSecurityException - */ - public KeyName itemKeyName(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_KEYNAME,i); - - if (e != null) { - return new KeyName(e, this._baseURI); - } - return null; - } - - /** - * Method itemKeyValue - * - * @param i - * @return the asked KeyValue element, null if the index is too big - * @throws XMLSecurityException - */ - public KeyValue itemKeyValue(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_KEYVALUE,i); - - if (e != null) { - return new KeyValue(e, this._baseURI); - } - return null; - } - - /** - * Method itemMgmtData - * - * @param i - *@return the asked MgmtData element, null if the index is too big - * @throws XMLSecurityException - */ - public MgmtData itemMgmtData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_MGMTDATA,i); - - if (e != null) { - return new MgmtData(e, this._baseURI); - } - return null; - } - - /** - * Method itemPGPData - * - * @param i - *@return the asked PGPData element, null if the index is too big - * @throws XMLSecurityException - */ - public PGPData itemPGPData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_PGPDATA,i); - - if (e != null) { - return new PGPData(e, this._baseURI); - } - return null; - } - - /** - * Method itemRetrievalMethod - * - * @param i - *@return the asked RetrievalMethod element, null if the index is too big - * @throws XMLSecurityException - */ - public RetrievalMethod itemRetrievalMethod(int i) - throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_RETRIEVALMETHOD,i); - - if (e != null) { - return new RetrievalMethod(e, this._baseURI); - } - return null; - } - - /** - * Method itemSPKIData - * - * @param i - *@return the asked SPKIData element, null if the index is too big - * @throws XMLSecurityException - */ - public SPKIData itemSPKIData(int i) throws XMLSecurityException { - - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_SPKIDATA,i); - - if (e != null) { - return new SPKIData(e, this._baseURI); - } - return null; - } - - /** - * Method itemX509Data - *@return the asked X509Data element, null if the index is too big - * @param i - * - * @throws XMLSecurityException - */ - public X509Data itemX509Data(int i) throws XMLSecurityException { - if (x509Datas!=null) { - return x509Datas.get(i); - } - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509DATA,i); - - if (e != null) { - return new X509Data(e, this._baseURI); - } - return null; - } - - /** - * Method itemEncryptedKey - * - * @param i - * @return the asked EncryptedKey element, null if the index is too big - * @throws XMLSecurityException - */ - - public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException { - if (encryptedKeys!=null) { - return encryptedKeys.get(i); - } - Element e = - XMLUtils.selectXencNode(this._constructionElement.getFirstChild(), - EncryptionConstants._TAG_ENCRYPTEDKEY,i); - - if (e != null) { - XMLCipher cipher = XMLCipher.getInstance(); - cipher.init(XMLCipher.UNWRAP_MODE, null); - return cipher.loadEncryptedKey(e); - } - return null; - } - - /** - * Method itemUnknownElement - * - * @param i index - * @return the element number of the unknown elemens - */ - public Element itemUnknownElement(int i) { - - NodeList nl = this._constructionElement.getChildNodes(); - int res = 0; - - for (int j = 0; j < nl.getLength(); j++) { - Node current = nl.item(j); - - /** - * $todo$ using this method, we don't see unknown Elements - * from Signature NS; revisit - */ - if ((current.getNodeType() == Node.ELEMENT_NODE) - && current.getNamespaceURI() - .equals(Constants.SignatureSpecNS)) { - res++; - - if (res == i) { - return (Element) current; - } - } - } - - return null; - } - - /** - * Method isEmpty - * - * @return true if the element has no descedants. - */ - public boolean isEmpty() { - return this._constructionElement.getFirstChild()==null; - } - - /** - * Method containsKeyName - * - * @return If the KeyInfo contains a KeyName node - */ - public boolean containsKeyName() { - return this.lengthKeyName() > 0; - } - - /** - * Method containsKeyValue - * - * @return If the KeyInfo contains a KeyValue node - */ - public boolean containsKeyValue() { - return this.lengthKeyValue() > 0; - } - - /** - * Method containsMgmtData - * - * @return If the KeyInfo contains a MgmtData node - */ - public boolean containsMgmtData() { - return this.lengthMgmtData() > 0; - } - - /** - * Method containsPGPData - * - * @return If the KeyInfo contains a PGPData node - */ - public boolean containsPGPData() { - return this.lengthPGPData() > 0; - } - - /** - * Method containsRetrievalMethod - * - * @return If the KeyInfo contains a RetrievalMethod node - */ - public boolean containsRetrievalMethod() { - return this.lengthRetrievalMethod() > 0; - } - - /** - * Method containsSPKIData - * - * @return If the KeyInfo contains a SPKIData node - */ - public boolean containsSPKIData() { - return this.lengthSPKIData() > 0; - } - - /** - * Method containsUnknownElement - * - * @return If the KeyInfo contains a UnknownElement node - */ - public boolean containsUnknownElement() { - return this.lengthUnknownElement() > 0; - } - - /** - * Method containsX509Data - * - * @return If the KeyInfo contains a X509Data node - */ - public boolean containsX509Data() { - return this.lengthX509Data() > 0; - } - - /** - * This method returns the public key. - * - * @return If the KeyInfo contains a PublicKey node - * @throws KeyResolverException - */ - - public PublicKey getPublicKey() throws KeyResolverException { - - PublicKey pk = this.getPublicKeyFromInternalResolvers(); - - if (pk != null) { - log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers"); - - return pk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers"); - - pk = this.getPublicKeyFromStaticResolvers(); - - if (pk != null) { - log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers"); - - return pk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers"); - - return null; - } + /** Field storageResolvers */ + private List storageResolvers = nullList; /** - * Searches the library wide keyresolvers for public keys + * Stores the individual (per-KeyInfo) {@link KeyResolverSpi}s + */ + private List internalKeyResolvers = new ArrayList(); + + private boolean secureValidation; + + /** + * Constructor KeyInfo + * @param doc + */ + public KeyInfo(Document doc) { + super(doc); + + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Constructor KeyInfo + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public KeyInfo(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + + Attr attr = element.getAttributeNodeNS(null, "Id"); + if (attr != null) { + element.setIdAttributeNode(attr, true); + } + } + + /** + * Set whether secure processing is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** + * Method addKeyName + * + * @param keynameString + */ + public void addKeyName(String keynameString) { + this.add(new KeyName(this.doc, keynameString)); + } + + /** + * Method add + * + * @param keyname + */ + public void add(KeyName keyname) { + this.constructionElement.appendChild(keyname.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addKeyValue + * + * @param pk + */ + public void addKeyValue(PublicKey pk) { + this.add(new KeyValue(this.doc, pk)); + } + + /** + * Method addKeyValue + * + * @param unknownKeyValueElement + */ + public void addKeyValue(Element unknownKeyValueElement) { + this.add(new KeyValue(this.doc, unknownKeyValueElement)); + } + + /** + * Method add + * + * @param dsakeyvalue + */ + public void add(DSAKeyValue dsakeyvalue) { + this.add(new KeyValue(this.doc, dsakeyvalue)); + } + + /** + * Method add + * + * @param rsakeyvalue + */ + public void add(RSAKeyValue rsakeyvalue) { + this.add(new KeyValue(this.doc, rsakeyvalue)); + } + + /** + * Method add + * + * @param pk + */ + public void add(PublicKey pk) { + this.add(new KeyValue(this.doc, pk)); + } + + /** + * Method add + * + * @param keyvalue + */ + public void add(KeyValue keyvalue) { + this.constructionElement.appendChild(keyvalue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addMgmtData + * + * @param mgmtdata + */ + public void addMgmtData(String mgmtdata) { + this.add(new MgmtData(this.doc, mgmtdata)); + } + + /** + * Method add + * + * @param mgmtdata + */ + public void add(MgmtData mgmtdata) { + this.constructionElement.appendChild(mgmtdata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addPGPData + * + * @param pgpdata + */ + public void add(PGPData pgpdata) { + this.constructionElement.appendChild(pgpdata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addRetrievalMethod + * + * @param uri + * @param transforms + * @param Type + */ + public void addRetrievalMethod(String uri, Transforms transforms, String Type) { + this.add(new RetrievalMethod(this.doc, uri, transforms, Type)); + } + + /** + * Method add + * + * @param retrievalmethod + */ + public void add(RetrievalMethod retrievalmethod) { + this.constructionElement.appendChild(retrievalmethod.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method add + * + * @param spkidata + */ + public void add(SPKIData spkidata) { + this.constructionElement.appendChild(spkidata.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addX509Data + * + * @param x509data + */ + public void add(X509Data x509data) { + if (x509Datas == null) { + x509Datas = new ArrayList(); + } + x509Datas.add(x509data); + this.constructionElement.appendChild(x509data.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addEncryptedKey + * + * @param encryptedKey + * @throws XMLEncryptionException + */ + + public void add(EncryptedKey encryptedKey) throws XMLEncryptionException { + if (encryptedKeys == null) { + encryptedKeys = new ArrayList(); + } + encryptedKeys.add(encryptedKey); + XMLCipher cipher = XMLCipher.getInstance(); + this.constructionElement.appendChild(cipher.martial(encryptedKey)); + } + + /** + * Method addDEREncodedKeyValue + * + * @param pk + * @throws XMLSecurityException + */ + public void addDEREncodedKeyValue(PublicKey pk) throws XMLSecurityException { + this.add(new DEREncodedKeyValue(this.doc, pk)); + } + + /** + * Method add + * + * @param derEncodedKeyValue + */ + public void add(DEREncodedKeyValue derEncodedKeyValue) { + this.constructionElement.appendChild(derEncodedKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addKeyInfoReference + * + * @param URI + * @throws XMLSecurityException + */ + public void addKeyInfoReference(String URI) throws XMLSecurityException { + this.add(new KeyInfoReference(this.doc, URI)); + } + + /** + * Method add + * + * @param keyInfoReference + */ + public void add(KeyInfoReference keyInfoReference) { + this.constructionElement.appendChild(keyInfoReference.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method addUnknownElement + * + * @param element + */ + public void addUnknownElement(Element element) { + this.constructionElement.appendChild(element); + XMLUtils.addReturnToElement(this.constructionElement); + } + + /** + * Method lengthKeyName + * + * @return the number of the KeyName tags + */ + public int lengthKeyName() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYNAME); + } + + /** + * Method lengthKeyValue + * + *@return the number of the KeyValue tags + */ + public int lengthKeyValue() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_KEYVALUE); + } + + /** + * Method lengthMgmtData + * + *@return the number of the MgmtData tags + */ + public int lengthMgmtData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_MGMTDATA); + } + + /** + * Method lengthPGPData + * + *@return the number of the PGPDat. tags + */ + public int lengthPGPData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_PGPDATA); + } + + /** + * Method lengthRetrievalMethod + * + *@return the number of the RetrievalMethod tags + */ + public int lengthRetrievalMethod() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_RETRIEVALMETHOD); + } + + /** + * Method lengthSPKIData + * + *@return the number of the SPKIData tags + */ + public int lengthSPKIData() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_SPKIDATA); + } + + /** + * Method lengthX509Data + * + *@return the number of the X509Data tags + */ + public int lengthX509Data() { + if (x509Datas != null) { + return x509Datas.size(); + } + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509DATA); + } + + /** + * Method lengthDEREncodedKeyValue + * + *@return the number of the DEREncodedKeyValue tags + */ + public int lengthDEREncodedKeyValue() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_DERENCODEDKEYVALUE); + } + + /** + * Method lengthKeyInfoReference + * + *@return the number of the KeyInfoReference tags + */ + public int lengthKeyInfoReference() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_KEYINFOREFERENCE); + } + + /** + * Method lengthUnknownElement + * NOTE possibly buggy. + * @return the number of the UnknownElement tags + */ + public int lengthUnknownElement() { + int res = 0; + NodeList nl = this.constructionElement.getChildNodes(); + + for (int i = 0; i < nl.getLength(); i++) { + Node current = nl.item(i); + + /** + * $todo$ using this method, we don't see unknown Elements + * from Signature NS; revisit + */ + if ((current.getNodeType() == Node.ELEMENT_NODE) + && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + res++; + } + } + + return res; + } + + /** + * Method itemKeyName + * + * @param i + * @return the asked KeyName element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyName itemKeyName(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_KEYNAME, i); + + if (e != null) { + return new KeyName(e, this.baseURI); + } + return null; + } + + /** + * Method itemKeyValue + * + * @param i + * @return the asked KeyValue element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyValue itemKeyValue(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_KEYVALUE, i); + + if (e != null) { + return new KeyValue(e, this.baseURI); + } + return null; + } + + /** + * Method itemMgmtData + * + * @param i + * @return the asked MgmtData element, null if the index is too big + * @throws XMLSecurityException + */ + public MgmtData itemMgmtData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_MGMTDATA, i); + + if (e != null) { + return new MgmtData(e, this.baseURI); + } + return null; + } + + /** + * Method itemPGPData + * + * @param i + * @return the asked PGPData element, null if the index is too big + * @throws XMLSecurityException + */ + public PGPData itemPGPData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_PGPDATA, i); + + if (e != null) { + return new PGPData(e, this.baseURI); + } + return null; + } + + /** + * Method itemRetrievalMethod + * + * @param i + *@return the asked RetrievalMethod element, null if the index is too big + * @throws XMLSecurityException + */ + public RetrievalMethod itemRetrievalMethod(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_RETRIEVALMETHOD, i); + + if (e != null) { + return new RetrievalMethod(e, this.baseURI); + } + return null; + } + + /** + * Method itemSPKIData + * + * @param i + * @return the asked SPKIData element, null if the index is too big + * @throws XMLSecurityException + */ + public SPKIData itemSPKIData(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_SPKIDATA, i); + + if (e != null) { + return new SPKIData(e, this.baseURI); + } + return null; + } + + /** + * Method itemX509Data + * + * @param i + * @return the asked X509Data element, null if the index is too big + * @throws XMLSecurityException + */ + public X509Data itemX509Data(int i) throws XMLSecurityException { + if (x509Datas != null) { + return x509Datas.get(i); + } + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509DATA, i); + + if (e != null) { + return new X509Data(e, this.baseURI); + } + return null; + } + + /** + * Method itemEncryptedKey + * + * @param i + * @return the asked EncryptedKey element, null if the index is too big + * @throws XMLSecurityException + */ + public EncryptedKey itemEncryptedKey(int i) throws XMLSecurityException { + if (encryptedKeys != null) { + return encryptedKeys.get(i); + } + Element e = + XMLUtils.selectXencNode( + this.constructionElement.getFirstChild(), EncryptionConstants._TAG_ENCRYPTEDKEY, i); + + if (e != null) { + XMLCipher cipher = XMLCipher.getInstance(); + cipher.init(XMLCipher.UNWRAP_MODE, null); + return cipher.loadEncryptedKey(e); + } + return null; + } + + /** + * Method itemDEREncodedKeyValue + * + * @param i + * @return the asked DEREncodedKeyValue element, null if the index is too big + * @throws XMLSecurityException + */ + public DEREncodedKeyValue itemDEREncodedKeyValue(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_DERENCODEDKEYVALUE, i); + + if (e != null) { + return new DEREncodedKeyValue(e, this.baseURI); + } + return null; + } + + /** + * Method itemKeyInfoReference + * + * @param i + * @return the asked KeyInfoReference element, null if the index is too big + * @throws XMLSecurityException + */ + public KeyInfoReference itemKeyInfoReference(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_KEYINFOREFERENCE, i); + + if (e != null) { + return new KeyInfoReference(e, this.baseURI); + } + return null; + } + + /** + * Method itemUnknownElement + * + * @param i index + * @return the element number of the unknown elements + */ + public Element itemUnknownElement(int i) { + NodeList nl = this.constructionElement.getChildNodes(); + int res = 0; + + for (int j = 0; j < nl.getLength(); j++) { + Node current = nl.item(j); + + /** + * $todo$ using this method, we don't see unknown Elements + * from Signature NS; revisit + */ + if ((current.getNodeType() == Node.ELEMENT_NODE) + && current.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + res++; + + if (res == i) { + return (Element) current; + } + } + } + + return null; + } + + /** + * Method isEmpty + * + * @return true if the element has no descendants. + */ + public boolean isEmpty() { + return this.constructionElement.getFirstChild() == null; + } + + /** + * Method containsKeyName + * + * @return If the KeyInfo contains a KeyName node + */ + public boolean containsKeyName() { + return this.lengthKeyName() > 0; + } + + /** + * Method containsKeyValue + * + * @return If the KeyInfo contains a KeyValue node + */ + public boolean containsKeyValue() { + return this.lengthKeyValue() > 0; + } + + /** + * Method containsMgmtData + * + * @return If the KeyInfo contains a MgmtData node + */ + public boolean containsMgmtData() { + return this.lengthMgmtData() > 0; + } + + /** + * Method containsPGPData + * + * @return If the KeyInfo contains a PGPData node + */ + public boolean containsPGPData() { + return this.lengthPGPData() > 0; + } + + /** + * Method containsRetrievalMethod + * + * @return If the KeyInfo contains a RetrievalMethod node + */ + public boolean containsRetrievalMethod() { + return this.lengthRetrievalMethod() > 0; + } + + /** + * Method containsSPKIData + * + * @return If the KeyInfo contains a SPKIData node + */ + public boolean containsSPKIData() { + return this.lengthSPKIData() > 0; + } + + /** + * Method containsUnknownElement + * + * @return If the KeyInfo contains a UnknownElement node + */ + public boolean containsUnknownElement() { + return this.lengthUnknownElement() > 0; + } + + /** + * Method containsX509Data + * + * @return If the KeyInfo contains a X509Data node + */ + public boolean containsX509Data() { + return this.lengthX509Data() > 0; + } + + /** + * Method containsDEREncodedKeyValue + * + * @return If the KeyInfo contains a DEREncodedKeyValue node + */ + public boolean containsDEREncodedKeyValue() { + return this.lengthDEREncodedKeyValue() > 0; + } + + /** + * Method containsKeyInfoReference + * + * @return If the KeyInfo contains a KeyInfoReference node + */ + public boolean containsKeyInfoReference() { + return this.lengthKeyInfoReference() > 0; + } + + /** + * This method returns the public key. + * + * @return If the KeyInfo contains a PublicKey node + * @throws KeyResolverException + */ + public PublicKey getPublicKey() throws KeyResolverException { + PublicKey pk = this.getPublicKeyFromInternalResolvers(); + + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a key using the per-KeyInfo key resolvers"); + } + + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a key using the per-KeyInfo key resolvers"); + } + + pk = this.getPublicKeyFromStaticResolvers(); + + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a key using the system-wide key resolvers"); + } + + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a key using the system-wide key resolvers"); + } + + return null; + } + + /** + * Searches the library wide KeyResolvers for public keys * * @return The public key contained in this Node. * @throws KeyResolverException @@ -732,11 +862,12 @@ public class KeyInfo extends SignatureElementProxy { Iterator it = KeyResolver.iterator(); while (it.hasNext()) { KeyResolverSpi keyResolver = it.next(); - Node currentChild = this._constructionElement.getFirstChild(); + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); String uri = this.getBaseURI(); while (currentChild != null) { if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (StorageResolver storage : _storageResolvers) { + for (StorageResolver storage : storageResolvers) { PublicKey pk = keyResolver.engineLookupAndResolvePublicKey( (Element) currentChild, uri, storage @@ -753,78 +884,77 @@ public class KeyInfo extends SignatureElementProxy { return null; } - /** - * Searches the per-KeyInfo keyresolvers for public keys - * - * @return The publick contained in this Node. - * @throws KeyResolverException - */ - PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException { - int length=lengthInternalKeyResolver(); - int storageLength=this._storageResolvers.size(); - for (int i = 0; i < length; i++) { - KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i); - if (log.isLoggable(java.util.logging.Level.FINE)) + /** + * Searches the per-KeyInfo KeyResolvers for public keys + * + * @return The public key contained in this Node. + * @throws KeyResolverException + */ + PublicKey getPublicKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); - - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); - PublicKey pk = keyResolver - .engineLookupAndResolvePublicKey((Element) currentChild, uri, storage); - - if (pk != null) { - return pk; - } - } } - currentChild=currentChild.getNextSibling(); - } - } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + PublicKey pk = + keyResolver.engineLookupAndResolvePublicKey( + (Element) currentChild, uri, storage + ); - return null; - } + if (pk != null) { + return pk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** - * Method getX509Certificate - * - * @return The certificate contined in this KeyInfo - * @throws KeyResolverException - */ - public X509Certificate getX509Certificate() throws KeyResolverException { + return null; + } - // First search using the individual resolvers from the user - X509Certificate cert = this.getX509CertificateFromInternalResolvers(); + /** + * Method getX509Certificate + * + * @return The certificate contained in this KeyInfo + * @throws KeyResolverException + */ + public X509Certificate getX509Certificate() throws KeyResolverException { + // First search using the individual resolvers from the user + X509Certificate cert = this.getX509CertificateFromInternalResolvers(); - if (cert != null) { - log.log(java.util.logging.Level.FINE, - "I could find a X509Certificate using the per-KeyInfo key resolvers"); + if (cert != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the per-KeyInfo key resolvers"); + } - return cert; - } - log.log(java.util.logging.Level.FINE, - "I couldn't find a X509Certificate using the per-KeyInfo key resolvers"); + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the per-KeyInfo key resolvers"); + } + // Then use the system-wide Resolvers + cert = this.getX509CertificateFromStaticResolvers(); - // Then use the system-wide Resolvers - cert = this.getX509CertificateFromStaticResolvers(); + if (cert != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a X509Certificate using the system-wide key resolvers"); + } - if (cert != null) { - log.log(java.util.logging.Level.FINE, - "I could find a X509Certificate using the system-wide key resolvers"); + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a X509Certificate using the system-wide key resolvers"); + } - return cert; - } - log.log(java.util.logging.Level.FINE, - "I couldn't find a X509Certificate using the system-wide key resolvers"); - - - return null; - } + return null; + } /** * This method uses each System-wide {@link KeyResolver} to search the @@ -846,6 +976,7 @@ public class KeyInfo extends SignatureElementProxy { Iterator it = KeyResolver.iterator(); while (it.hasNext()) { KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); X509Certificate cert = applyCurrentResolver(uri, keyResolver); if (cert != null) { return cert; @@ -857,10 +988,10 @@ public class KeyInfo extends SignatureElementProxy { private X509Certificate applyCurrentResolver( String uri, KeyResolverSpi keyResolver ) throws KeyResolverException { - Node currentChild = this._constructionElement.getFirstChild(); + Node currentChild = this.constructionElement.getFirstChild(); while (currentChild != null) { if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (StorageResolver storage : _storageResolvers) { + for (StorageResolver storage : storageResolvers) { X509Certificate cert = keyResolver.engineLookupResolveX509Certificate( (Element) currentChild, uri, storage @@ -879,7 +1010,7 @@ public class KeyInfo extends SignatureElementProxy { /** * Method getX509CertificateFromInternalResolvers * - * @return The certificate contined in this KeyInfo + * @return The certificate contained in this KeyInfo * @throws KeyResolverException */ X509Certificate getX509CertificateFromInternalResolvers() @@ -891,10 +1022,11 @@ public class KeyInfo extends SignatureElementProxy { ); } String uri = this.getBaseURI(); - for (KeyResolverSpi keyResolver : _internalKeyResolvers) { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); } + keyResolver.setSecureValidation(secureValidation); X509Certificate cert = applyCurrentResolver(uri, keyResolver); if (cert != null) { return cert; @@ -904,189 +1036,252 @@ public class KeyInfo extends SignatureElementProxy { return null; } - /** - * This method returns a secret (symmetric) key. This is for XML Encryption. - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ - public SecretKey getSecretKey() throws KeyResolverException { - SecretKey sk = this.getSecretKeyFromInternalResolvers(); + /** + * This method returns a secret (symmetric) key. This is for XML Encryption. + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ + public SecretKey getSecretKey() throws KeyResolverException { + SecretKey sk = this.getSecretKeyFromInternalResolvers(); - if (sk != null) { - log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers"); - - return sk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); - - - sk = this.getSecretKeyFromStaticResolvers(); - - if (sk != null) { - log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers"); - - return sk; - } - log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers"); - - - return null; - } - - /** - * Searches the library wide keyresolvers for Secret keys - * - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ - - SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException { - final int length=KeyResolver.length(); - int storageLength=this._storageResolvers.size(); - Iterator it = KeyResolver.iterator(); - for (int i = 0; i < length; i++) { - KeyResolverSpi keyResolver = it.next(); - - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); - - SecretKey sk = - keyResolver.engineLookupAndResolveSecretKey((Element) currentChild, - uri, - storage); - - if (sk != null) { - return sk; - } - } + if (sk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a secret key using the per-KeyInfo key resolvers"); } - currentChild=currentChild.getNextSibling(); - } - } - return null; - } - /** - * Searches the per-KeyInfo keyresolvers for secret keys - * - * @return the secret key contained in this KeyInfo - * @throws KeyResolverException - */ + return sk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); + } - SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException { - int storageLength=this._storageResolvers.size(); - for (int i = 0; i < this.lengthInternalKeyResolver(); i++) { - KeyResolverSpi keyResolver = this.itemInternalKeyResolver(i); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + sk = this.getSecretKeyFromStaticResolvers(); - Node currentChild=this._constructionElement.getFirstChild(); - String uri=this.getBaseURI(); - while (currentChild!=null) { - if (currentChild.getNodeType() == Node.ELEMENT_NODE) { - for (int k = 0; k < storageLength; k++) { - StorageResolver storage = - this._storageResolvers.get(k); + if (sk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a secret key using the system-wide key resolvers"); + } - SecretKey sk = keyResolver - .engineLookupAndResolveSecretKey((Element) currentChild, uri, storage); + return sk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the system-wide key resolvers"); + } - if (sk != null) { - return sk; - } + return null; + } + + /** + * Searches the library wide KeyResolvers for Secret keys + * + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ + SecretKey getSecretKeyFromStaticResolvers() throws KeyResolverException { + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); + + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + SecretKey sk = + keyResolver.engineLookupAndResolveSecretKey( + (Element) currentChild, uri, storage + ); + + if (sk != null) { + return sk; + } + } } - } - currentChild=currentChild.getNextSibling(); - } - } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } - return null; - } + /** + * Searches the per-KeyInfo KeyResolvers for secret keys + * + * @return the secret key contained in this KeyInfo + * @throws KeyResolverException + */ - /** - * Stores the individual (per-KeyInfo) {@link KeyResolver}s - */ - List _internalKeyResolvers = new ArrayList(); + SecretKey getSecretKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + for (StorageResolver storage : storageResolvers) { + SecretKey sk = + keyResolver.engineLookupAndResolveSecretKey( + (Element) currentChild, uri, storage + ); - /** - * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo - * object. - * - * @param realKeyResolver - */ - public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { - if (_internalKeyResolvers==null) { - _internalKeyResolvers=new ArrayList(); - } - this._internalKeyResolvers.add(realKeyResolver); - } + if (sk != null) { + return sk; + } + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** - * Method lengthInternalKeyResolver - * @return the length of the key - */ - int lengthInternalKeyResolver() { - if (_internalKeyResolvers==null) - return 0; - return this._internalKeyResolvers.size(); - } + return null; + } - /** - * Method itemInternalKeyResolver - * - * @param i the index - * @return the KeyResolverSpi for the index. - */ - KeyResolverSpi itemInternalKeyResolver(int i) { - return this._internalKeyResolvers.get(i); - } + /** + * This method returns a private key. This is for Key Transport in XML Encryption. + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + public PrivateKey getPrivateKey() throws KeyResolverException { + PrivateKey pk = this.getPrivateKeyFromInternalResolvers(); - /** Field _storageResolvers */ - private List _storageResolvers = nullList; + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a private key using the per-KeyInfo key resolvers"); + } + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a secret key using the per-KeyInfo key resolvers"); + } - /** - * Method addStorageResolver - * - * @param storageResolver - */ - public void addStorageResolver(StorageResolver storageResolver) { - if (_storageResolvers == nullList ){ - _storageResolvers=new ArrayList(); - } - this._storageResolvers.add(storageResolver); + pk = this.getPrivateKeyFromStaticResolvers(); + if (pk != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I could find a private key using the system-wide key resolvers"); + } + return pk; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I couldn't find a private key using the system-wide key resolvers"); + } - } + return null; + } - //J- - static boolean _alreadyInitialized = false; - /** init the keyinfo (Still needed?)*/ - public static void init() { + /** + * Searches the library wide KeyResolvers for Private keys + * + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + PrivateKey getPrivateKeyFromStaticResolvers() throws KeyResolverException { + Iterator it = KeyResolver.iterator(); + while (it.hasNext()) { + KeyResolverSpi keyResolver = it.next(); + keyResolver.setSecureValidation(secureValidation); - if (!KeyInfo._alreadyInitialized) { - if (KeyInfo.log == null) { + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + // not using StorageResolvers at the moment + // since they cannot return private keys + PrivateKey pk = + keyResolver.engineLookupAndResolvePrivateKey( + (Element) currentChild, uri, null + ); - /** - * $todo$ why the hell does the static initialization from the - * start not work ? - */ - KeyInfo.log = - java.util.logging.Logger.getLogger(KeyInfo.class.getName()); + if (pk != null) { + return pk; + } + } + currentChild = currentChild.getNextSibling(); + } + } + return null; + } - log.log(java.util.logging.Level.SEVERE, "Had to assign log in the init() function"); - } + /** + * Searches the per-KeyInfo KeyResolvers for private keys + * + * @return the private key contained in this KeyInfo + * @throws KeyResolverException + */ + PrivateKey getPrivateKeyFromInternalResolvers() throws KeyResolverException { + for (KeyResolverSpi keyResolver : internalKeyResolvers) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Try " + keyResolver.getClass().getName()); + } + keyResolver.setSecureValidation(secureValidation); + Node currentChild = this.constructionElement.getFirstChild(); + String uri = this.getBaseURI(); + while (currentChild != null) { + if (currentChild.getNodeType() == Node.ELEMENT_NODE) { + // not using StorageResolvers at the moment + // since they cannot return private keys + PrivateKey pk = + keyResolver.engineLookupAndResolvePrivateKey( + (Element) currentChild, uri, null + ); - // KeyInfo._contentHandlerHash = new HashMap(10); - KeyInfo._alreadyInitialized = true; - } - } + if (pk != null) { + return pk; + } + } + currentChild = currentChild.getNextSibling(); + } + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_KEYINFO; - } + return null; + } + + /** + * This method is used to add a custom {@link KeyResolverSpi} to a KeyInfo + * object. + * + * @param realKeyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { + this.internalKeyResolvers.add(realKeyResolver); + } + + /** + * Method lengthInternalKeyResolver + * @return the length of the key + */ + int lengthInternalKeyResolver() { + return this.internalKeyResolvers.size(); + } + + /** + * Method itemInternalKeyResolver + * + * @param i the index + * @return the KeyResolverSpi for the index. + */ + KeyResolverSpi itemInternalKeyResolver(int i) { + return this.internalKeyResolvers.get(i); + } + + /** + * Method addStorageResolver + * + * @param storageResolver + */ + public void addStorageResolver(StorageResolver storageResolver) { + if (storageResolvers == nullList) { + // Replace the default null StorageResolver + storageResolvers = new ArrayList(); + } + this.storageResolvers.add(storageResolver); + } + + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYINFO; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java index 67ce204efba..8613c8197b7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/KeyUtils.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys; - - import java.io.PrintStream; import java.security.PublicKey; @@ -31,57 +31,53 @@ import com.sun.org.apache.xml.internal.security.keys.content.KeyValue; import com.sun.org.apache.xml.internal.security.keys.content.MgmtData; import com.sun.org.apache.xml.internal.security.keys.content.X509Data; - /** * Utility class for for com.sun.org.apache.xml.internal.security.keys package. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class KeyUtils { - private KeyUtils() { - // no instantiation - } + private KeyUtils() { + // no instantiation + } - /** - * Method prinoutKeyInfo - * - * @param ki - * @param os - * @throws XMLSecurityException - */ - public static void prinoutKeyInfo(KeyInfo ki, PrintStream os) - throws XMLSecurityException { + /** + * Method prinoutKeyInfo + * + * @param ki + * @param os + * @throws XMLSecurityException + */ + public static void prinoutKeyInfo(KeyInfo ki, PrintStream os) + throws XMLSecurityException { - for (int i = 0; i < ki.lengthKeyName(); i++) { - KeyName x = ki.itemKeyName(i); + for (int i = 0; i < ki.lengthKeyName(); i++) { + KeyName x = ki.itemKeyName(i); - os.println("KeyName(" + i + ")=\"" + x.getKeyName() + "\""); - } + os.println("KeyName(" + i + ")=\"" + x.getKeyName() + "\""); + } - for (int i = 0; i < ki.lengthKeyValue(); i++) { - KeyValue x = ki.itemKeyValue(i); - PublicKey pk = x.getPublicKey(); + for (int i = 0; i < ki.lengthKeyValue(); i++) { + KeyValue x = ki.itemKeyValue(i); + PublicKey pk = x.getPublicKey(); - os.println("KeyValue Nr. " + i); - os.println(pk); - } + os.println("KeyValue Nr. " + i); + os.println(pk); + } - for (int i = 0; i < ki.lengthMgmtData(); i++) { - MgmtData x = ki.itemMgmtData(i); + for (int i = 0; i < ki.lengthMgmtData(); i++) { + MgmtData x = ki.itemMgmtData(i); - os.println("MgmtData(" + i + ")=\"" + x.getMgmtData() + "\""); - } + os.println("MgmtData(" + i + ")=\"" + x.getMgmtData() + "\""); + } - for (int i = 0; i < ki.lengthX509Data(); i++) { - X509Data x = ki.itemX509Data(i); + for (int i = 0; i < ki.lengthX509Data(); i++) { + X509Data x = ki.itemX509Data(i); - os.println("X509Data(" + i + ")=\"" + (x.containsCertificate() - ? "Certificate " - : "") + (x - .containsIssuerSerial() - ? "IssuerSerial " - : "") + "\""); - } - } + os.println("X509Data(" + i + ")=\"" + (x.containsCertificate() + ? "Certificate " : "") + (x.containsIssuerSerial() + ? "IssuerSerial " : "") + "\""); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java new file mode 100644 index 00000000000..0144025216a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/DEREncodedKeyValue.java @@ -0,0 +1,158 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.keys.content; + +import java.security.KeyFactory; +import java.security.NoSuchAlgorithmException; +import java.security.PublicKey; +import java.security.spec.InvalidKeySpecException; +import java.security.spec.X509EncodedKeySpec; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:DEREncodedKeyvalue element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class DEREncodedKeyValue extends Signature11ElementProxy implements KeyInfoContent { + + /** JCA algorithm key types supported by this implementation. */ + public static final String supportedKeyTypes[] = { "RSA", "DSA", "EC"}; + + /** + * Constructor DEREncodedKeyValue + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public DEREncodedKeyValue(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor DEREncodedKeyValue + * + * @param doc + * @param publicKey + * @throws XMLSecurityException + */ + public DEREncodedKeyValue(Document doc, PublicKey publicKey) throws XMLSecurityException { + super(doc); + + this.addBase64Text(getEncodedDER(publicKey)); + } + + /** + * Constructor DEREncodedKeyValue + * + * @param doc + * @param base64EncodedKey + */ + public DEREncodedKeyValue(Document doc, byte[] encodedKey) { + super(doc); + + this.addBase64Text(encodedKey); + } + + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } else { + this.constructionElement.removeAttributeNS(null, Constants._ATT_ID); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DERENCODEDKEYVALUE; + } + + /** + * Method getPublicKey + * + * @return the public key + * @throws XMLSecurityException + */ + public PublicKey getPublicKey() throws XMLSecurityException { + byte[] encodedKey = getBytesFromTextChild(); + + // Iterate over the supported key types until one produces a public key. + for (String keyType : supportedKeyTypes) { + try { + KeyFactory keyFactory = KeyFactory.getInstance(keyType); + X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encodedKey); + PublicKey publicKey = keyFactory.generatePublic(keySpec); + if (publicKey != null) { + return publicKey; + } + } catch (NoSuchAlgorithmException e) { + // Do nothing, try the next type + } catch (InvalidKeySpecException e) { + // Do nothing, try the next type + } + } + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedEncodedKey"); + } + + /** + * Method getEncodedDER + * + * @return the public key + * @throws XMLSecurityException + */ + protected byte[] getEncodedDER(PublicKey publicKey) throws XMLSecurityException { + try { + KeyFactory keyFactory = KeyFactory.getInstance(publicKey.getAlgorithm()); + X509EncodedKeySpec keySpec = keyFactory.getKeySpec(publicKey, X509EncodedKeySpec.class); + return keySpec.getEncoded(); + } catch (NoSuchAlgorithmException e) { + Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() }; + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e); + } catch (InvalidKeySpecException e) { + Object exArgs[] = { publicKey.getAlgorithm(), publicKey.getFormat(), publicKey.getClass().getName() }; + throw new XMLSecurityException("DEREncodedKeyValue.UnsupportedPublicKey", exArgs, e); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java index 4d5a7a6b975..e753f1bb4ce 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoContent.java @@ -2,32 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; - - - - /** - * Empty interface just to identify Elements that can be cildren of ds:KeyInfo. + * Empty interface just to identify Elements that can be children of ds:KeyInfo. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public interface KeyInfoContent { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java new file mode 100644 index 00000000000..f52f4a98e54 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyInfoReference.java @@ -0,0 +1,107 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.keys.content; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:KeyInfoReference element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class KeyInfoReference extends Signature11ElementProxy implements KeyInfoContent { + + /** + * Constructor RetrievalMethod + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public KeyInfoReference(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } + + /** + * Constructor RetrievalMethod + * + * @param doc + * @param URI + */ + public KeyInfoReference(Document doc, String URI) { + super(doc); + + this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); + } + + /** + * Method getURIAttr + * + * @return the URI attribute + */ + public Attr getURIAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); + } + + /** + * Method getURI + * + * @return URI string + */ + public String getURI() { + return this.getURIAttr().getNodeValue(); + } + + /** + * Sets the Id attribute + * + * @param Id ID + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } else { + this.constructionElement.removeAttributeNS(null, Constants._ATT_ID); + } + } + + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYINFOREFERENCE; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java index 6794ea67586..fbe2e0c1faf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyName.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -27,46 +29,44 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class KeyName extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor KeyName - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public KeyName(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor KeyName + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public KeyName(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor KeyName - * - * @param doc - * @param keyName - */ - public KeyName(Document doc, String keyName) { + /** + * Constructor KeyName + * + * @param doc + * @param keyName + */ + public KeyName(Document doc, String keyName) { + super(doc); - super(doc); + this.addText(keyName); + } - this.addText(keyName); - } + /** + * Method getKeyName + * + * @return key name + */ + public String getKeyName() { + return this.getTextFromTextChild(); + } - /** - * Method getKeyName - * - * @return key name - */ - public String getKeyName() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_KEYNAME; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_KEYNAME; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java index 0d3ee810d23..db7a6836d56 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/KeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -39,7 +41,7 @@ import org.w3c.dom.Element; * keys values represented as PCDATA or element types from an external * namespace. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { @@ -50,12 +52,11 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param dsaKeyValue */ public KeyValue(Document doc, DSAKeyValue dsaKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(dsaKeyValue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(dsaKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -65,12 +66,11 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param rsaKeyValue */ public KeyValue(Document doc, RSAKeyValue rsaKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(rsaKeyValue.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(rsaKeyValue.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -80,12 +80,11 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param unknownKeyValue */ public KeyValue(Document doc, Element unknownKeyValue) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(unknownKeyValue); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(unknownKeyValue); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -95,21 +94,20 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param pk */ public KeyValue(Document doc, PublicKey pk) { - super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); if (pk instanceof java.security.interfaces.DSAPublicKey) { - DSAKeyValue dsa = new DSAKeyValue(this._doc, pk); + DSAKeyValue dsa = new DSAKeyValue(this.doc, pk); - this._constructionElement.appendChild(dsa.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(dsa.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } else if (pk instanceof java.security.interfaces.RSAPublicKey) { - RSAKeyValue rsa = new RSAKeyValue(this._doc, pk); + RSAKeyValue rsa = new RSAKeyValue(this.doc, pk); - this._constructionElement.appendChild(rsa.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(rsa.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); } } @@ -120,8 +118,7 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @param BaseURI * @throws XMLSecurityException */ - public KeyValue(Element element, String BaseURI) - throws XMLSecurityException { + public KeyValue(Element element, String BaseURI) throws XMLSecurityException { super(element, BaseURI); } @@ -132,22 +129,21 @@ public class KeyValue extends SignatureElementProxy implements KeyInfoContent { * @throws XMLSecurityException */ public PublicKey getPublicKey() throws XMLSecurityException { - - Element rsa = XMLUtils.selectDsNode - (this._constructionElement.getFirstChild(), - Constants._TAG_RSAKEYVALUE,0); + Element rsa = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0); if (rsa != null) { - RSAKeyValue kv = new RSAKeyValue(rsa, this._baseURI); + RSAKeyValue kv = new RSAKeyValue(rsa, this.baseURI); return kv.getPublicKey(); } - Element dsa = XMLUtils.selectDsNode - (this._constructionElement.getFirstChild(), - Constants._TAG_DSAKEYVALUE,0); + Element dsa = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0); if (dsa != null) { - DSAKeyValue kv = new DSAKeyValue(dsa, this._baseURI); + DSAKeyValue kv = new DSAKeyValue(dsa, this.baseURI); return kv.getPublicKey(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java index 185e3557170..c037ee77f7d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/MgmtData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -27,47 +29,45 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class MgmtData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor MgmtData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public MgmtData(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor MgmtData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public MgmtData(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor MgmtData - * - * @param doc - * @param mgmtData - */ - public MgmtData(Document doc, String mgmtData) { + /** + * Constructor MgmtData + * + * @param doc + * @param mgmtData + */ + public MgmtData(Document doc, String mgmtData) { + super(doc); - super(doc); + this.addText(mgmtData); + } - this.addText(mgmtData); - } + /** + * Method getMgmtData + * + * @return the managment data + */ + public String getMgmtData() { + return this.getTextFromTextChild(); + } - /** - * Method getMgmtData - * - * @return the managment data - */ - public String getMgmtData() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_MGMTDATA; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_MGMTDATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java index 010c907a8d9..e4dbbf4b091 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/PGPData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -26,25 +28,24 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ * $todo$ Implement */ public class PGPData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor PGPData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public PGPData(Element element, String BaseURI) throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor PGPData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public PGPData(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_PGPDATA; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_PGPDATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java index 3c4956b7787..5ee9041f7b1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/RetrievalMethod.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -30,118 +32,104 @@ import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class RetrievalMethod extends SignatureElementProxy - implements KeyInfoContent { +public class RetrievalMethod extends SignatureElementProxy implements KeyInfoContent { - //J- /** DSA retrieval */ - public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue"; - /** RSA retrieval */ - public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue"; - /** PGP retrieval */ - public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData"; - /** SPKI retrieval */ - public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData"; - /** MGMT retrieval */ - public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData"; - /** X509 retrieval */ - public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data"; - /** RAWX509 retrieval */ - public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate"; - //J+ + public static final String TYPE_DSA = Constants.SignatureSpecNS + "DSAKeyValue"; + /** RSA retrieval */ + public static final String TYPE_RSA = Constants.SignatureSpecNS + "RSAKeyValue"; + /** PGP retrieval */ + public static final String TYPE_PGP = Constants.SignatureSpecNS + "PGPData"; + /** SPKI retrieval */ + public static final String TYPE_SPKI = Constants.SignatureSpecNS + "SPKIData"; + /** MGMT retrieval */ + public static final String TYPE_MGMT = Constants.SignatureSpecNS + "MgmtData"; + /** X509 retrieval */ + public static final String TYPE_X509 = Constants.SignatureSpecNS + "X509Data"; + /** RAWX509 retrieval */ + public static final String TYPE_RAWX509 = Constants.SignatureSpecNS + "rawX509Certificate"; - /** - * Constructor RetrievalMethod - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public RetrievalMethod(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor RetrievalMethod + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public RetrievalMethod(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor RetrievalMethod - * - * @param doc - * @param URI - * @param transforms - * @param Type - */ - public RetrievalMethod(Document doc, String URI, Transforms transforms, - String Type) { + /** + * Constructor RetrievalMethod + * + * @param doc + * @param URI + * @param transforms + * @param Type + */ + public RetrievalMethod(Document doc, String URI, Transforms transforms, String Type) { + super(doc); - super(doc); + this.constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); - this._constructionElement.setAttributeNS(null, Constants._ATT_URI, URI); + if (Type != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type); + } - if (Type != null) { - this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE, Type); - } + if (transforms != null) { + this.constructionElement.appendChild(transforms.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + } - if (transforms != null) { - this._constructionElement.appendChild(transforms.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } - } + /** + * Method getURIAttr + * + * @return the URI attribute + */ + public Attr getURIAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); + } - /** - * Method getURIAttr - * - * @return the URI attribute - */ - public Attr getURIAttr() { - return this._constructionElement.getAttributeNodeNS(null, Constants._ATT_URI); - } + /** + * Method getURI + * + * @return URI string + */ + public String getURI() { + return this.getURIAttr().getNodeValue(); + } - /** - * Method getURI - * - * - * @return URI string - */ - public String getURI() { - return this.getURIAttr().getNodeValue(); - } + /** @return the type*/ + public String getType() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE); + } - /** @return the type*/ - public String getType() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_TYPE); - } + /** + * Method getTransforms + * + * @throws XMLSecurityException + * @return the transformations + */ + public Transforms getTransforms() throws XMLSecurityException { + try { + Element transformsElem = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_TRANSFORMS, 0); - /** - * Method getTransforms - * - * - * @throws XMLSecurityException - * @return the transforamitons - */ - public Transforms getTransforms() throws XMLSecurityException { + if (transformsElem != null) { + return new Transforms(transformsElem, this.baseURI); + } - try { - Element transformsElem = - XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants - ._TAG_TRANSFORMS, 0); + return null; + } catch (XMLSignatureException ex) { + throw new XMLSecurityException("empty", ex); + } + } - if (transformsElem != null) { - return new Transforms(transformsElem, this._baseURI); - } - - return null; - } catch (XMLSignatureException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_RETRIEVALMETHOD; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_RETRIEVALMETHOD; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java index 95cef8d5491..0177f9bcc12 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/SPKIData.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; @@ -26,26 +28,25 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ * $todo$ implement */ public class SPKIData extends SignatureElementProxy implements KeyInfoContent { - /** - * Constructor SPKIData - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public SPKIData(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor SPKIData + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public SPKIData(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_SPKIDATA; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_SPKIDATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java index 199b1dcb020..55a2a0edd40 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/X509Data.java @@ -2,32 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content; - - import java.math.BigInteger; import java.security.cert.X509Certificate; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509CRL; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName; @@ -38,447 +39,501 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - -/** - * - * @author $Author: mullan $ - */ public class X509Data extends SignatureElementProxy implements KeyInfoContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509Data.class.getName()); - /** - * Constructor X509Data - * - * @param doc - */ - public X509Data(Document doc) { + /** + * Constructor X509Data + * + * @param doc + */ + public X509Data(Document doc) { + super(doc); - super(doc); + XMLUtils.addReturnToElement(this.constructionElement); + } - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Constructor X509Data + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public X509Data(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); - /** - * Constructor X509Data - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public X509Data(Element element, String BaseURI) - throws XMLSecurityException { + Node sibling = this.constructionElement.getFirstChild(); + while (sibling != null) { + if (sibling.getNodeType() != Node.ELEMENT_NODE) { + sibling = sibling.getNextSibling(); + continue; + } + return; + } + /* No Elements found */ + Object exArgs[] = { "Elements", Constants._TAG_X509DATA }; + throw new XMLSecurityException("xml.WrongContent", exArgs); + } - super(element, BaseURI); - Node sibling=this._constructionElement.getFirstChild(); - while (sibling!=null) { - if (sibling.getNodeType()!=Node.ELEMENT_NODE) { - sibling=sibling.getNextSibling(); - continue; - } - return; - } - /* No Elements found */ - Object exArgs[] = { "Elements", Constants._TAG_X509DATA }; - throw new XMLSecurityException("xml.WrongContent", exArgs); - } + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, BigInteger X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, - BigInteger X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, String X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } + /** + * Method addIssuerSerial + * + * @param X509IssuerName + * @param X509SerialNumber + */ + public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) { + this.add(new XMLX509IssuerSerial(this.doc, X509IssuerName, X509SerialNumber)); + } - /** - * Method addIssuerSerial - * - * @param X509IssuerName - * @param X509SerialNumber - */ - public void addIssuerSerial(String X509IssuerName, int X509SerialNumber) { - this.add(new XMLX509IssuerSerial(this._doc, X509IssuerName, - X509SerialNumber)); - } + /** + * Method add + * + * @param xmlX509IssuerSerial + */ + public void add(XMLX509IssuerSerial xmlX509IssuerSerial) { - /** - * Method add - * - * @param xmlX509IssuerSerial - */ - public void add(XMLX509IssuerSerial xmlX509IssuerSerial) { + this.constructionElement.appendChild(xmlX509IssuerSerial.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - this._constructionElement - .appendChild(xmlX509IssuerSerial.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addSKI + * + * @param skiBytes + */ + public void addSKI(byte[] skiBytes) { + this.add(new XMLX509SKI(this.doc, skiBytes)); + } - /** - * Method addSKI - * - * @param skiBytes - */ - public void addSKI(byte[] skiBytes) { - this.add(new XMLX509SKI(this._doc, skiBytes)); - } + /** + * Method addSKI + * + * @param x509certificate + * @throws XMLSecurityException + */ + public void addSKI(X509Certificate x509certificate) + throws XMLSecurityException { + this.add(new XMLX509SKI(this.doc, x509certificate)); + } - /** - * Method addSKI - * - * @param x509certificate - * @throws XMLSecurityException - */ - public void addSKI(X509Certificate x509certificate) - throws XMLSecurityException { - this.add(new XMLX509SKI(this._doc, x509certificate)); - } + /** + * Method add + * + * @param xmlX509SKI + */ + public void add(XMLX509SKI xmlX509SKI) { + this.constructionElement.appendChild(xmlX509SKI.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509SKI - */ - public void add(XMLX509SKI xmlX509SKI) { - this._constructionElement.appendChild(xmlX509SKI.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addSubjectName + * + * @param subjectName + */ + public void addSubjectName(String subjectName) { + this.add(new XMLX509SubjectName(this.doc, subjectName)); + } - /** - * Method addSubjectName - * - * @param subjectName - */ - public void addSubjectName(String subjectName) { - this.add(new XMLX509SubjectName(this._doc, subjectName)); - } + /** + * Method addSubjectName + * + * @param x509certificate + */ + public void addSubjectName(X509Certificate x509certificate) { + this.add(new XMLX509SubjectName(this.doc, x509certificate)); + } - /** - * Method addSubjectName - * - * @param x509certificate - */ - public void addSubjectName(X509Certificate x509certificate) { - this.add(new XMLX509SubjectName(this._doc, x509certificate)); - } + /** + * Method add + * + * @param xmlX509SubjectName + */ + public void add(XMLX509SubjectName xmlX509SubjectName) { + this.constructionElement.appendChild(xmlX509SubjectName.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509SubjectName - */ - public void add(XMLX509SubjectName xmlX509SubjectName) { - this._constructionElement.appendChild(xmlX509SubjectName.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addCertificate + * + * @param x509certificate + * @throws XMLSecurityException + */ + public void addCertificate(X509Certificate x509certificate) + throws XMLSecurityException { + this.add(new XMLX509Certificate(this.doc, x509certificate)); + } - /** - * Method addCertificate - * - * @param x509certificate - * @throws XMLSecurityException - */ - public void addCertificate(X509Certificate x509certificate) - throws XMLSecurityException { - this.add(new XMLX509Certificate(this._doc, x509certificate)); - } + /** + * Method addCertificate + * + * @param x509certificateBytes + */ + public void addCertificate(byte[] x509certificateBytes) { + this.add(new XMLX509Certificate(this.doc, x509certificateBytes)); + } - /** - * Method addCertificate - * - * @param x509certificateBytes - */ - public void addCertificate(byte[] x509certificateBytes) { - this.add(new XMLX509Certificate(this._doc, x509certificateBytes)); - } + /** + * Method add + * + * @param xmlX509Certificate + */ + public void add(XMLX509Certificate xmlX509Certificate) { + this.constructionElement.appendChild(xmlX509Certificate.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509Certificate - */ - public void add(XMLX509Certificate xmlX509Certificate) { - this._constructionElement.appendChild(xmlX509Certificate.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addCRL + * + * @param crlBytes + */ + public void addCRL(byte[] crlBytes) { + this.add(new XMLX509CRL(this.doc, crlBytes)); + } - /** - * Method addCRL - * - * @param crlBytes - */ - public void addCRL(byte[] crlBytes) { - this.add(new XMLX509CRL(this._doc, crlBytes)); - } + /** + * Method add + * + * @param xmlX509CRL + */ + public void add(XMLX509CRL xmlX509CRL) { + this.constructionElement.appendChild(xmlX509CRL.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method add - * - * @param xmlX509CRL - */ - public void add(XMLX509CRL xmlX509CRL) { - this._constructionElement.appendChild(xmlX509CRL.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addDigest + * + * @param x509certificate + * @param algorithmURI + * @throws XMLSecurityException + */ + public void addDigest(X509Certificate x509certificate, String algorithmURI) + throws XMLSecurityException { + this.add(new XMLX509Digest(this.doc, x509certificate, algorithmURI)); + } - /** - * Method addUnknownElement - * - * @param element - */ - public void addUnknownElement(Element element) { - this._constructionElement.appendChild(element); - XMLUtils.addReturnToElement(this._constructionElement); - } + /** + * Method addDigest + * + * @param x509CertificateDigestByes + * @param algorithmURI + */ + public void addDigest(byte[] x509certificateDigestBytes, String algorithmURI) { + this.add(new XMLX509Digest(this.doc, x509certificateDigestBytes, algorithmURI)); + } - /** - * Method lengthIssuerSerial - * - * @return the number of IssuerSerial elements in this X509Data - */ - public int lengthIssuerSerial() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509ISSUERSERIAL); - } + /** + * Method add + * + * @param XMLX509Digest + */ + public void add(XMLX509Digest xmlX509Digest) { + this.constructionElement.appendChild(xmlX509Digest.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method lengthSKI - * - * @return the number of SKI elements in this X509Data - */ - public int lengthSKI() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI); - } + /** + * Method addUnknownElement + * + * @param element + */ + public void addUnknownElement(Element element) { + this.constructionElement.appendChild(element); + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method lengthSubjectName - * - * @return the number of SubjectName elements in this X509Data - */ - public int lengthSubjectName() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509SUBJECTNAME); - } + /** + * Method lengthIssuerSerial + * + * @return the number of IssuerSerial elements in this X509Data + */ + public int lengthIssuerSerial() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509ISSUERSERIAL); + } - /** - * Method lengthCertificate - * - * @return the number of Certificate elements in this X509Data - */ - public int lengthCertificate() { - return this.length(Constants.SignatureSpecNS, - Constants._TAG_X509CERTIFICATE); - } + /** + * Method lengthSKI + * + * @return the number of SKI elements in this X509Data + */ + public int lengthSKI() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SKI); + } - /** - * Method lengthCRL - * - * @return the number of CRL elements in this X509Data - */ - public int lengthCRL() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL); - } + /** + * Method lengthSubjectName + * + * @return the number of SubjectName elements in this X509Data + */ + public int lengthSubjectName() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509SUBJECTNAME); + } - /** - * Method lengthUnknownElement - * - * @return the number of UnknownElement elements in this X509Data - */ - public int lengthUnknownElement() { + /** + * Method lengthCertificate + * + * @return the number of Certificate elements in this X509Data + */ + public int lengthCertificate() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CERTIFICATE); + } - int result = 0; - Node n=this._constructionElement.getFirstChild(); - while (n!=null){ + /** + * Method lengthCRL + * + * @return the number of CRL elements in this X509Data + */ + public int lengthCRL() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_X509CRL); + } - if ((n.getNodeType() == Node.ELEMENT_NODE) - &&!n.getNamespaceURI().equals(Constants.SignatureSpecNS)) { - result += 1; - } - n=n.getNextSibling(); - } + /** + * Method lengthDigest + * + * @return the number of X509Digest elements in this X509Data + */ + public int lengthDigest() { + return this.length(Constants.SignatureSpec11NS, Constants._TAG_X509DIGEST); + } - return result; - } + /** + * Method lengthUnknownElement + * + * @return the number of UnknownElement elements in this X509Data + */ + public int lengthUnknownElement() { + int result = 0; + Node n = this.constructionElement.getFirstChild(); + while (n != null){ + if ((n.getNodeType() == Node.ELEMENT_NODE) + && !n.getNamespaceURI().equals(Constants.SignatureSpecNS)) { + result++; + } + n = n.getNextSibling(); + } - /** - * Method itemIssuerSerial - * - * @param i - * @return the X509IssuerSerial, null if not present - * @throws XMLSecurityException - */ - public XMLX509IssuerSerial itemIssuerSerial(int i) - throws XMLSecurityException { + return result; + } - Element e = - XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509ISSUERSERIAL,i); + /** + * Method itemIssuerSerial + * + * @param i + * @return the X509IssuerSerial, null if not present + * @throws XMLSecurityException + */ + public XMLX509IssuerSerial itemIssuerSerial(int i) throws XMLSecurityException { + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509ISSUERSERIAL, i); - if (e != null) { - return new XMLX509IssuerSerial(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509IssuerSerial(e, this.baseURI); + } + return null; + } - /** - * Method itemSKI - * - * @param i - * @return the X509SKI, null if not present - * @throws XMLSecurityException - */ - public XMLX509SKI itemSKI(int i) throws XMLSecurityException { + /** + * Method itemSKI + * + * @param i + * @return the X509SKI, null if not present + * @throws XMLSecurityException + */ + public XMLX509SKI itemSKI(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509SKI,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509SKI, i); - if (e != null) { - return new XMLX509SKI(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509SKI(e, this.baseURI); + } + return null; + } - /** - * Method itemSubjectName - * - * @param i - * @return the X509SubjectName, null if not present - * @throws XMLSecurityException - */ - public XMLX509SubjectName itemSubjectName(int i) - throws XMLSecurityException { + /** + * Method itemSubjectName + * + * @param i + * @return the X509SubjectName, null if not present + * @throws XMLSecurityException + */ + public XMLX509SubjectName itemSubjectName(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509SUBJECTNAME,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509SUBJECTNAME, i); - if (e != null) { - return new XMLX509SubjectName(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509SubjectName(e, this.baseURI); + } + return null; + } - /** - * Method itemCertificate - * - * @param i - * @return the X509Certifacte, null if not present - * @throws XMLSecurityException - */ - public XMLX509Certificate itemCertificate(int i) - throws XMLSecurityException { + /** + * Method itemCertificate + * + * @param i + * @return the X509Certifacte, null if not present + * @throws XMLSecurityException + */ + public XMLX509Certificate itemCertificate(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509CERTIFICATE,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509CERTIFICATE, i); - if (e != null) { - return new XMLX509Certificate(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509Certificate(e, this.baseURI); + } + return null; + } - /** - * Method itemCRL - * - * @param i - * @return the X509CRL, null if not present - * @throws XMLSecurityException - */ - public XMLX509CRL itemCRL(int i) throws XMLSecurityException { + /** + * Method itemCRL + * + * @param i + * @return the X509CRL, null if not present + * @throws XMLSecurityException + */ + public XMLX509CRL itemCRL(int i) throws XMLSecurityException { - Element e = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_X509CRL,i); + Element e = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_X509CRL, i); - if (e != null) { - return new XMLX509CRL(e, this._baseURI); - } - return null; - } + if (e != null) { + return new XMLX509CRL(e, this.baseURI); + } + return null; + } - /** - * Method itemUnknownElement - * - * @param i - * @return the Unknown Element at i - * TODO implement - **/ - public Element itemUnknownElement(int i) { - log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:"+i); - return null; - } + /** + * Method itemDigest + * + * @param i + * @return the X509Digest, null if not present + * @throws XMLSecurityException + */ + public XMLX509Digest itemDigest(int i) throws XMLSecurityException { - /** - * Method containsIssuerSerial - * - * @return true if this X509Data contains a IssuerSerial - */ - public boolean containsIssuerSerial() { - return this.lengthIssuerSerial() > 0; - } + Element e = + XMLUtils.selectDs11Node( + this.constructionElement.getFirstChild(), Constants._TAG_X509DIGEST, i); - /** - * Method containsSKI - * - * @return true if this X509Data contains a SKI - */ - public boolean containsSKI() { - return this.lengthSKI() > 0; - } + if (e != null) { + return new XMLX509Digest(e, this.baseURI); + } + return null; + } - /** - * Method containsSubjectName - * - * @return true if this X509Data contains a SubjectName - */ - public boolean containsSubjectName() { - return this.lengthSubjectName() > 0; - } + /** + * Method itemUnknownElement + * + * @param i + * @return the Unknown Element at i + * TODO implement + **/ + public Element itemUnknownElement(int i) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "itemUnknownElement not implemented:" + i); + } + return null; + } - /** - * Method containsCertificate - * - * @return true if this X509Data contains a Certificate - */ - public boolean containsCertificate() { - return this.lengthCertificate() > 0; - } + /** + * Method containsIssuerSerial + * + * @return true if this X509Data contains a IssuerSerial + */ + public boolean containsIssuerSerial() { + return this.lengthIssuerSerial() > 0; + } - /** - * Method containsCRL - * - * @return true if this X509Data contains a CRL - */ - public boolean containsCRL() { - return this.lengthCRL() > 0; - } + /** + * Method containsSKI + * + * @return true if this X509Data contains a SKI + */ + public boolean containsSKI() { + return this.lengthSKI() > 0; + } - /** - * Method containsUnknownElement - * - * @return true if this X509Data contains an UnknownElement - */ - public boolean containsUnknownElement() { - return this.lengthUnknownElement() > 0; - } + /** + * Method containsSubjectName + * + * @return true if this X509Data contains a SubjectName + */ + public boolean containsSubjectName() { + return this.lengthSubjectName() > 0; + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509DATA; - } + /** + * Method containsCertificate + * + * @return true if this X509Data contains a Certificate + */ + public boolean containsCertificate() { + return this.lengthCertificate() > 0; + } + + /** + * Method containsDigest + * + * @return true if this X509Data contains an X509Digest + */ + public boolean containsDigest() { + return this.lengthDigest() > 0; + } + + /** + * Method containsCRL + * + * @return true if this X509Data contains a CRL + */ + public boolean containsCRL() { + return this.lengthCRL() > 0; + } + + /** + * Method containsUnknownElement + * + * @return true if this X509Data contains an UnknownElement + */ + public boolean containsUnknownElement() { + return this.lengthUnknownElement() > 0; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509DATA; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java index ef735c3dad6..2cfa51fc28c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/DSAKeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.keyvalues; @@ -37,104 +39,93 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class DSAKeyValue extends SignatureElementProxy - implements KeyValueContent { +public class DSAKeyValue extends SignatureElementProxy implements KeyValueContent { - /** - * Constructor DSAKeyValue - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public DSAKeyValue(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor DSAKeyValue + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public DSAKeyValue(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } - /** - * Constructor DSAKeyValue - * - * @param doc - * @param P - * @param Q - * @param G - * @param Y - */ - public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, - BigInteger Y) { + /** + * Constructor DSAKeyValue + * + * @param doc + * @param P + * @param Q + * @param G + * @param Y + */ + public DSAKeyValue(Document doc, BigInteger P, BigInteger Q, BigInteger G, BigInteger Y) { + super(doc); - super(doc); + XMLUtils.addReturnToElement(this.constructionElement); + this.addBigIntegerElement(P, Constants._TAG_P); + this.addBigIntegerElement(Q, Constants._TAG_Q); + this.addBigIntegerElement(G, Constants._TAG_G); + this.addBigIntegerElement(Y, Constants._TAG_Y); + } - XMLUtils.addReturnToElement(this._constructionElement); - this.addBigIntegerElement(P, Constants._TAG_P); - this.addBigIntegerElement(Q, Constants._TAG_Q); - this.addBigIntegerElement(G, Constants._TAG_G); - this.addBigIntegerElement(Y, Constants._TAG_Y); - } + /** + * Constructor DSAKeyValue + * + * @param doc + * @param key + * @throws IllegalArgumentException + */ + public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + super(doc); - /** - * Constructor DSAKeyValue - * - * @param doc - * @param key - * @throws IllegalArgumentException - */ - public DSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + XMLUtils.addReturnToElement(this.constructionElement); - super(doc); + if (key instanceof java.security.interfaces.DSAPublicKey) { + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), Constants._TAG_P); + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), Constants._TAG_Q); + this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), Constants._TAG_G); + this.addBigIntegerElement(((DSAPublicKey) key).getY(), Constants._TAG_Y); + } else { + Object exArgs[] = { Constants._TAG_DSAKEYVALUE, key.getClass().getName() }; - XMLUtils.addReturnToElement(this._constructionElement); + throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs)); + } + } - if (key instanceof java.security.interfaces.DSAPublicKey) { - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getP(), - Constants._TAG_P); - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getQ(), - Constants._TAG_Q); - this.addBigIntegerElement(((DSAPublicKey) key).getParams().getG(), - Constants._TAG_G); - this.addBigIntegerElement(((DSAPublicKey) key).getY(), - Constants._TAG_Y); - } else { - Object exArgs[] = { Constants._TAG_DSAKEYVALUE, - key.getClass().getName() }; + /** @inheritDoc */ + public PublicKey getPublicKey() throws XMLSecurityException { + try { + DSAPublicKeySpec pkspec = + new DSAPublicKeySpec( + this.getBigIntegerFromChildElement( + Constants._TAG_Y, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_P, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_Q, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_G, Constants.SignatureSpecNS + ) + ); + KeyFactory dsaFactory = KeyFactory.getInstance("DSA"); + PublicKey pk = dsaFactory.generatePublic(pkspec); - throw new IllegalArgumentException(I18n - .translate("KeyValue.IllegalArgument", exArgs)); - } - } + return pk; + } catch (NoSuchAlgorithmException ex) { + throw new XMLSecurityException("empty", ex); + } catch (InvalidKeySpecException ex) { + throw new XMLSecurityException("empty", ex); + } + } - /** @inheritDoc */ - public PublicKey getPublicKey() throws XMLSecurityException { - - try { - DSAPublicKeySpec pkspec = - new DSAPublicKeySpec(this - .getBigIntegerFromChildElement(Constants._TAG_Y, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants._TAG_P, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants._TAG_Q, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants - ._TAG_G, Constants.SignatureSpecNS)); - KeyFactory dsaFactory = KeyFactory.getInstance("DSA"); - PublicKey pk = dsaFactory.generatePublic(pkspec); - - return pk; - } catch (NoSuchAlgorithmException ex) { - throw new XMLSecurityException("empty", ex); - } catch (InvalidKeySpecException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_DSAKEYVALUE; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_DSAKEYVALUE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java index 31e761443c5..d5ebe5b6937 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/KeyValueContent.java @@ -2,46 +2,38 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.keyvalues; - - import java.security.PublicKey; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; -/** - * - * - * - * - * @author $Author: mullan $ - * - */ public interface KeyValueContent { - /** - * Method getPublicKey - * - * @return the public key - * @throws XMLSecurityException - */ - public PublicKey getPublicKey() - throws XMLSecurityException; + /** + * Method getPublicKey + * + * @return the public key + * @throws XMLSecurityException + */ + PublicKey getPublicKey() throws XMLSecurityException; + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java index 71b23cda593..a12b8b45bd9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/keyvalues/RSAKeyValue.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.keyvalues; @@ -37,93 +39,86 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class RSAKeyValue extends SignatureElementProxy - implements KeyValueContent { +public class RSAKeyValue extends SignatureElementProxy implements KeyValueContent { - /** - * Constructor RSAKeyValue - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public RSAKeyValue(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor RSAKeyValue + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public RSAKeyValue(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor RSAKeyValue - * - * @param doc - * @param modulus - * @param exponent - */ - public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) { + /** + * Constructor RSAKeyValue + * + * @param doc + * @param modulus + * @param exponent + */ + public RSAKeyValue(Document doc, BigInteger modulus, BigInteger exponent) { + super(doc); - super(doc); + XMLUtils.addReturnToElement(this.constructionElement); + this.addBigIntegerElement(modulus, Constants._TAG_MODULUS); + this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT); + } - XMLUtils.addReturnToElement(this._constructionElement); - this.addBigIntegerElement(modulus, Constants._TAG_MODULUS); - this.addBigIntegerElement(exponent, Constants._TAG_EXPONENT); - } + /** + * Constructor RSAKeyValue + * + * @param doc + * @param key + * @throws IllegalArgumentException + */ + public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + super(doc); - /** - * Constructor RSAKeyValue - * - * @param doc - * @param key - * @throws IllegalArgumentException - */ - public RSAKeyValue(Document doc, Key key) throws IllegalArgumentException { + XMLUtils.addReturnToElement(this.constructionElement); - super(doc); + if (key instanceof java.security.interfaces.RSAPublicKey ) { + this.addBigIntegerElement( + ((RSAPublicKey) key).getModulus(), Constants._TAG_MODULUS + ); + this.addBigIntegerElement( + ((RSAPublicKey) key).getPublicExponent(), Constants._TAG_EXPONENT + ); + } else { + Object exArgs[] = { Constants._TAG_RSAKEYVALUE, key.getClass().getName() }; - XMLUtils.addReturnToElement(this._constructionElement); + throw new IllegalArgumentException(I18n.translate("KeyValue.IllegalArgument", exArgs)); + } + } - if (key instanceof java.security.interfaces.RSAPublicKey ) { - this.addBigIntegerElement(((RSAPublicKey) key).getModulus(), - Constants._TAG_MODULUS); - this.addBigIntegerElement(((RSAPublicKey) key).getPublicExponent(), - Constants._TAG_EXPONENT); - } else { - Object exArgs[] = { Constants._TAG_RSAKEYVALUE, - key.getClass().getName() }; + /** @inheritDoc */ + public PublicKey getPublicKey() throws XMLSecurityException { + try { + KeyFactory rsaFactory = KeyFactory.getInstance("RSA"); - throw new IllegalArgumentException(I18n - .translate("KeyValue.IllegalArgument", exArgs)); - } - } + RSAPublicKeySpec rsaKeyspec = + new RSAPublicKeySpec( + this.getBigIntegerFromChildElement( + Constants._TAG_MODULUS, Constants.SignatureSpecNS + ), + this.getBigIntegerFromChildElement( + Constants._TAG_EXPONENT, Constants.SignatureSpecNS + ) + ); + PublicKey pk = rsaFactory.generatePublic(rsaKeyspec); - /** @inheritDoc */ - public PublicKey getPublicKey() throws XMLSecurityException { + return pk; + } catch (NoSuchAlgorithmException ex) { + throw new XMLSecurityException("empty", ex); + } catch (InvalidKeySpecException ex) { + throw new XMLSecurityException("empty", ex); + } + } - try { - KeyFactory rsaFactory = KeyFactory.getInstance("RSA"); - - // KeyFactory rsaFactory = KeyFactory.getInstance(JCE_RSA); - RSAPublicKeySpec rsaKeyspec = - new RSAPublicKeySpec(this - .getBigIntegerFromChildElement(Constants._TAG_MODULUS, Constants - .SignatureSpecNS), this - .getBigIntegerFromChildElement(Constants - ._TAG_EXPONENT, Constants.SignatureSpecNS)); - PublicKey pk = rsaFactory.generatePublic(rsaKeyspec); - - return pk; - } catch (NoSuchAlgorithmException ex) { - throw new XMLSecurityException("empty", ex); - } catch (InvalidKeySpecException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_RSAKEYVALUE; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_RSAKEYVALUE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java index b68c444dc08..0046c71d05c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509CRL.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -26,51 +28,43 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - * - */ -public class XMLX509CRL extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509CRL extends SignatureElementProxy implements XMLX509DataContent { - /** - * Constructor XMLX509CRL - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509CRL(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor XMLX509CRL + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509CRL(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor X509CRL - * - * @param doc - * @param crlBytes - */ - public XMLX509CRL(Document doc, byte[] crlBytes) { + /** + * Constructor X509CRL + * + * @param doc + * @param crlBytes + */ + public XMLX509CRL(Document doc, byte[] crlBytes) { + super(doc); - super(doc); + this.addBase64Text(crlBytes); + } - this.addBase64Text(crlBytes); - } + /** + * Method getCRLBytes + * + * @return the CRL bytes + * @throws XMLSecurityException + */ + public byte[] getCRLBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } - /** - * Method getCRLBytes - * - * @return the CRL bytes - * @throws XMLSecurityException - */ - public byte[] getCRLBytes() throws XMLSecurityException { - return this.getBytesFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509CRL; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509CRL; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java index 630d9ccc279..1a5931ff5d8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Certificate.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -25,6 +27,7 @@ import java.security.PublicKey; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; +import java.util.Arrays; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; @@ -32,135 +35,134 @@ import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class XMLX509Certificate extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509Certificate extends SignatureElementProxy implements XMLX509DataContent { - /** Field JCA_CERT_ID */ - public static final String JCA_CERT_ID = "X.509"; + /** Field JCA_CERT_ID */ + public static final String JCA_CERT_ID = "X.509"; - /** - * Constructor X509Certificate - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509Certificate(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor X509Certificate + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509Certificate(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor X509Certificate - * - * @param doc - * @param certificateBytes - */ - public XMLX509Certificate(Document doc, byte[] certificateBytes) { + /** + * Constructor X509Certificate + * + * @param doc + * @param certificateBytes + */ + public XMLX509Certificate(Document doc, byte[] certificateBytes) { + super(doc); - super(doc); + this.addBase64Text(certificateBytes); + } - this.addBase64Text(certificateBytes); - } + /** + * Constructor XMLX509Certificate + * + * @param doc + * @param x509certificate + * @throws XMLSecurityException + */ + public XMLX509Certificate(Document doc, X509Certificate x509certificate) + throws XMLSecurityException { + super(doc); - /** - * Constructor XMLX509Certificate - * - * @param doc - * @param x509certificate - * @throws XMLSecurityException - */ - public XMLX509Certificate(Document doc, X509Certificate x509certificate) - throws XMLSecurityException { + try { + this.addBase64Text(x509certificate.getEncoded()); + } catch (java.security.cert.CertificateEncodingException ex) { + throw new XMLSecurityException("empty", ex); + } + } - super(doc); + /** + * Method getCertificateBytes + * + * @return the certificate bytes + * @throws XMLSecurityException + */ + public byte[] getCertificateBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } - try { - this.addBase64Text(x509certificate.getEncoded()); - } catch (java.security.cert.CertificateEncodingException ex) { - throw new XMLSecurityException("empty", ex); - } - } + /** + * Method getX509Certificate + * + * @return the x509 certificate + * @throws XMLSecurityException + */ + public X509Certificate getX509Certificate() throws XMLSecurityException { + try { + byte certbytes[] = this.getCertificateBytes(); + CertificateFactory certFact = + CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); + X509Certificate cert = + (X509Certificate) certFact.generateCertificate( + new ByteArrayInputStream(certbytes) + ); - /** - * Method getCertificateBytes - * - * @return the certificate bytes - * @throws XMLSecurityException - */ - public byte[] getCertificateBytes() throws XMLSecurityException { - return this.getBytesFromTextChild(); - } + if (cert != null) { + return cert; + } - /** - * Method getX509Certificate - * - * @return the x509 certificate - * @throws XMLSecurityException - */ - public X509Certificate getX509Certificate() throws XMLSecurityException { + return null; + } catch (CertificateException ex) { + throw new XMLSecurityException("empty", ex); + } + } - try { - byte certbytes[] = this.getCertificateBytes(); - CertificateFactory certFact = - CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert = - (X509Certificate) certFact - .generateCertificate(new ByteArrayInputStream(certbytes)); + /** + * Method getPublicKey + * + * @return the publickey + * @throws XMLSecurityException + */ + public PublicKey getPublicKey() throws XMLSecurityException { + X509Certificate cert = this.getX509Certificate(); - if (cert != null) { - return cert; - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } catch (CertificateException ex) { - throw new XMLSecurityException("empty", ex); - } - } - - /** - * Method getPublicKey - * - * @return teh publickey - * @throws XMLSecurityException - */ - public PublicKey getPublicKey() throws XMLSecurityException { - - X509Certificate cert = this.getX509Certificate(); - - if (cert != null) { - return cert.getPublicKey(); - } - - return null; - } + return null; + } /** @inheritDoc */ public boolean equals(Object obj) { - - if (obj == null) { - return false; - } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509Certificate)) { return false; } XMLX509Certificate other = (XMLX509Certificate) obj; try { - - /** $todo$ or should be create X509Certificates and use the equals() from the Certs */ - return java.security.MessageDigest.isEqual - (other.getCertificateBytes(), this.getCertificateBytes()); + return Arrays.equals(other.getCertificateBytes(), this.getCertificateBytes()); } catch (XMLSecurityException ex) { return false; } } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509CERTIFICATE; - } + public int hashCode() { + int result = 17; + try { + byte[] bytes = getCertificateBytes(); + for (int i = 0; i < bytes.length; i++) { + result = 31 * result + bytes[i]; + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + return result; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509CERTIFICATE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java index 02bf9f82d39..2171572d3ab 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509DataContent.java @@ -2,32 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; - - - - /** * Just used for tagging contents that are allowed inside a ds:X509Data Element. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public interface XMLX509DataContent { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java new file mode 100644 index 00000000000..57acc678bd9 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509Digest.java @@ -0,0 +1,139 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.keys.content.x509; + +import java.security.MessageDigest; +import java.security.cert.X509Certificate; + +import com.sun.org.apache.xml.internal.security.algorithms.JCEMapper; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.Signature11ElementProxy; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Provides content model support for the dsig11:X509Digest element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class XMLX509Digest extends Signature11ElementProxy implements XMLX509DataContent { + + /** + * Constructor XMLX509Digest + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509Digest(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + } + + /** + * Constructor XMLX509Digest + * + * @param doc + * @param digestBytes + * @param algorithmURI + */ + public XMLX509Digest(Document doc, byte[] digestBytes, String algorithmURI) { + super(doc); + this.addBase64Text(digestBytes); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + } + + /** + * Constructor XMLX509Digest + * + * @param doc + * @param x509certificate + * @param algorithmURI + * @throws XMLSecurityException + */ + public XMLX509Digest(Document doc, X509Certificate x509certificate, String algorithmURI) throws XMLSecurityException { + super(doc); + this.addBase64Text(getDigestBytesFromCert(x509certificate, algorithmURI)); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + } + + /** + * Method getAlgorithmAttr + * + * @return the Algorithm attribute + */ + public Attr getAlgorithmAttr() { + return this.constructionElement.getAttributeNodeNS(null, Constants._ATT_ALGORITHM); + } + + /** + * Method getAlgorithm + * + * @return Algorithm string + */ + public String getAlgorithm() { + return this.getAlgorithmAttr().getNodeValue(); + } + + /** + * Method getDigestBytes + * + * @return the digestbytes + * @throws XMLSecurityException + */ + public byte[] getDigestBytes() throws XMLSecurityException { + return this.getBytesFromTextChild(); + } + + /** + * Method getDigestBytesFromCert + * + * @param cert + * @param algorithmURI + * @return digest bytes from the given certificate + * + * @throws XMLSecurityException + */ + public static byte[] getDigestBytesFromCert(X509Certificate cert, String algorithmURI) throws XMLSecurityException { + String jcaDigestAlgorithm = JCEMapper.translateURItoJCEID(algorithmURI); + if (jcaDigestAlgorithm == null) { + Object exArgs[] = { algorithmURI }; + throw new XMLSecurityException("XMLX509Digest.UnknownDigestAlgorithm", exArgs); + } + + try { + MessageDigest md = MessageDigest.getInstance(jcaDigestAlgorithm); + return md.digest(cert.getEncoded()); + } catch (Exception e) { + Object exArgs[] = { jcaDigestAlgorithm }; + throw new XMLSecurityException("XMLX509Digest.FailedDigest", exArgs); + } + + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509DIGEST; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java index 1d16b2b622f..cf3274377cb 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509IssuerSerial.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -31,17 +33,11 @@ import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; -/** - * - * @author $Author: mullan $ - */ -public class XMLX509IssuerSerial extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509IssuerSerial extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - XMLX509IssuerSerial.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XMLX509IssuerSerial.class.getName()); /** * Constructor XMLX509IssuerSerial @@ -50,8 +46,7 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param baseURI * @throws XMLSecurityException */ - public XMLX509IssuerSerial(Element element, String baseURI) - throws XMLSecurityException { + public XMLX509IssuerSerial(Element element, String baseURI) throws XMLSecurityException { super(element, baseURI); } @@ -62,11 +57,9 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - BigInteger x509SerialNumber) { - + public XMLX509IssuerSerial(Document doc, String x509IssuerName, BigInteger x509SerialNumber) { super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); addTextElement(x509IssuerName, Constants._TAG_X509ISSUERNAME); addTextElement(x509SerialNumber.toString(), Constants._TAG_X509SERIALNUMBER); } @@ -78,8 +71,7 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - String x509SerialNumber) { + public XMLX509IssuerSerial(Document doc, String x509IssuerName, String x509SerialNumber) { this(doc, x509IssuerName, new BigInteger(x509SerialNumber)); } @@ -90,10 +82,8 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param x509IssuerName * @param x509SerialNumber */ - public XMLX509IssuerSerial(Document doc, String x509IssuerName, - int x509SerialNumber) { - this(doc, x509IssuerName, - new BigInteger(Integer.toString(x509SerialNumber))); + public XMLX509IssuerSerial(Document doc, String x509IssuerName, int x509SerialNumber) { + this(doc, x509IssuerName, new BigInteger(Integer.toString(x509SerialNumber))); } /** @@ -103,10 +93,11 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @param x509certificate */ public XMLX509IssuerSerial(Document doc, X509Certificate x509certificate) { - - this(doc, - RFC2253Parser.normalize(x509certificate.getIssuerDN().getName()), - x509certificate.getSerialNumber()); + this( + doc, + x509certificate.getIssuerX500Principal().getName(), + x509certificate.getSerialNumber() + ); } /** @@ -115,11 +106,11 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @return the serial number */ public BigInteger getSerialNumber() { - - String text = this.getTextFromChildElement - (Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS); - if (log.isLoggable(java.util.logging.Level.FINE)) + String text = + this.getTextFromChildElement(Constants._TAG_X509SERIALNUMBER, Constants.SignatureSpecNS); + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "X509SerialNumber text: " + text); + } return new BigInteger(text); } @@ -139,27 +130,28 @@ public class XMLX509IssuerSerial extends SignatureElementProxy * @return the issuer name */ public String getIssuerName() { - - return RFC2253Parser - .normalize(this - .getTextFromChildElement(Constants._TAG_X509ISSUERNAME, - Constants.SignatureSpecNS)); + return RFC2253Parser.normalize( + this.getTextFromChildElement(Constants._TAG_X509ISSUERNAME, Constants.SignatureSpecNS) + ); } /** @inheritDoc */ public boolean equals(Object obj) { - - if (obj == null) { - return false; - } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509IssuerSerial)) { return false; } XMLX509IssuerSerial other = (XMLX509IssuerSerial) obj; return this.getSerialNumber().equals(other.getSerialNumber()) - && this.getIssuerName().equals(other.getIssuerName()); + && this.getIssuerName().equals(other.getIssuerName()); + } + + public int hashCode() { + int result = 17; + result = 31 * result + getSerialNumber().hashCode(); + result = 31 * result + getIssuerName().hashCode(); + return result; } /** @inheritDoc */ diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java index fbbb17e6a54..e4617daead9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SKI.java @@ -2,30 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; -import java.io.IOException; -import java.io.ByteArrayInputStream; -import java.io.InputStream; import java.security.cert.X509Certificate; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; +import java.util.Arrays; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Base64; @@ -37,14 +35,13 @@ import org.w3c.dom.Element; /** * Handles SubjectKeyIdentifier (SKI) for X.509v3. * - * @author $Author: mullan $ - * @see Interface X509Extension + * @see + * Interface X509Extension */ -public class XMLX509SKI extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509SKI extends SignatureElementProxy implements XMLX509DataContent { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLX509SKI.class.getName()); /** @@ -53,7 +50,7 @@ public class XMLX509SKI extends SignatureElementProxy * distinct keys used by the same subject to be differentiated * (e.g., as key updating occurs). *
- * A key identifer shall be unique with respect to all key identifiers + * A key identifier shall be unique with respect to all key identifiers * for the subject with which it is used. This extension is always non-critical. */ public static final String SKI_OID = "2.5.29.14"; @@ -77,7 +74,7 @@ public class XMLX509SKI extends SignatureElementProxy * @throws XMLSecurityException */ public XMLX509SKI(Document doc, X509Certificate x509certificate) - throws XMLSecurityException { + throws XMLSecurityException { super(doc); this.addBase64Text(XMLX509SKI.getSKIBytesFromCert(x509certificate)); } @@ -89,8 +86,7 @@ public class XMLX509SKI extends SignatureElementProxy * @param BaseURI * @throws XMLSecurityException */ - public XMLX509SKI(Element element, String BaseURI) - throws XMLSecurityException { + public XMLX509SKI(Element element, String BaseURI) throws XMLSecurityException { super(element, BaseURI); } @@ -117,9 +113,8 @@ public class XMLX509SKI extends SignatureElementProxy throws XMLSecurityException { if (cert.getVersion() < 3) { - Object exArgs[] = { new Integer(cert.getVersion()) }; - throw new XMLSecurityException("certificate.noSki.lowVersion", - exArgs); + Object exArgs[] = { Integer.valueOf(cert.getVersion()) }; + throw new XMLSecurityException("certificate.noSki.lowVersion", exArgs); } /* @@ -137,7 +132,7 @@ public class XMLX509SKI extends SignatureElementProxy * Strip away first four bytes from the extensionValue * The first two bytes are the tag and length of the extensionValue * OCTET STRING, and the next two bytes are the tag and length of - * the skid OCTET STRING. + * the ski OCTET STRING. */ byte skidValue[] = new byte[extensionValue.length - 4]; @@ -152,23 +147,35 @@ public class XMLX509SKI extends SignatureElementProxy /** @inheritDoc */ public boolean equals(Object obj) { - if (obj == null) { - return false; - } - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509SKI)) { return false; } XMLX509SKI other = (XMLX509SKI) obj; try { - return java.security.MessageDigest.isEqual(other.getSKIBytes(), - this.getSKIBytes()); + return Arrays.equals(other.getSKIBytes(), this.getSKIBytes()); } catch (XMLSecurityException ex) { return false; } } + public int hashCode() { + int result = 17; + try { + byte[] bytes = getSKIBytes(); + for (int i = 0; i < bytes.length; i++) { + result = 31 * result + bytes[i]; + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + return result; + + } + /** @inheritDoc */ public String getBaseLocalName() { return Constants._TAG_X509SKI; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java index 8d51da2e2fd..c183abbf8af 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/content/x509/XMLX509SubjectName.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.content.x509; @@ -30,65 +32,57 @@ import org.w3c.dom.Document; import org.w3c.dom.Element; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ -public class XMLX509SubjectName extends SignatureElementProxy - implements XMLX509DataContent { +public class XMLX509SubjectName extends SignatureElementProxy implements XMLX509DataContent { - /** - * Constructor X509SubjectName - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public XMLX509SubjectName(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor X509SubjectName + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public XMLX509SubjectName(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** - * Constructor X509SubjectName - * - * @param doc - * @param X509SubjectNameString - */ - public XMLX509SubjectName(Document doc, String X509SubjectNameString) { + /** + * Constructor X509SubjectName + * + * @param doc + * @param X509SubjectNameString + */ + public XMLX509SubjectName(Document doc, String X509SubjectNameString) { + super(doc); - super(doc); + this.addText(X509SubjectNameString); + } - this.addText(X509SubjectNameString); - } + /** + * Constructor XMLX509SubjectName + * + * @param doc + * @param x509certificate + */ + public XMLX509SubjectName(Document doc, X509Certificate x509certificate) { + this(doc, x509certificate.getSubjectX500Principal().getName()); + } - /** - * Constructor XMLX509SubjectName - * - * @param doc - * @param x509certificate - */ - public XMLX509SubjectName(Document doc, X509Certificate x509certificate) { - this(doc, - RFC2253Parser.normalize(x509certificate.getSubjectDN().getName())); - } - - /** - * Method getSubjectName - * - * - * @return the subject name - */ - public String getSubjectName() { - return RFC2253Parser.normalize(this.getTextFromTextChild()); - } + /** + * Method getSubjectName + * + * + * @return the subject name + */ + public String getSubjectName() { + return RFC2253Parser.normalize(this.getTextFromTextChild()); + } /** @inheritDoc */ public boolean equals(Object obj) { - if (obj == null) { - return false; - } - - if (!this.getClass().getName().equals(obj.getClass().getName())) { + if (!(obj instanceof XMLX509SubjectName)) { return false; } @@ -97,10 +91,16 @@ public class XMLX509SubjectName extends SignatureElementProxy String thisSubject = this.getSubjectName(); return thisSubject.equals(otherSubject); - } + } - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_X509SUBJECTNAME; - } + public int hashCode() { + int result = 17; + result = 31 * result + this.getSubjectName().hashCode(); + return result; + } + + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_X509SUBJECTNAME; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java index 3b3508005cb..614a34f41e6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/InvalidKeyResolverException.java @@ -2,88 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * - * @author $Author: mullan $ - */ public class InvalidKeyResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidKeyResolverException - * - */ - public InvalidKeyResolverException() { - super(); - } + /** + * Constructor InvalidKeyResolverException + * + */ + public InvalidKeyResolverException() { + super(); + } - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - */ - public InvalidKeyResolverException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + */ + public InvalidKeyResolverException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param exArgs - */ - public InvalidKeyResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param exArgs + */ + public InvalidKeyResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param _originalException - */ - public InvalidKeyResolverException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param originalException + */ + public InvalidKeyResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidKeyResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidKeyResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidKeyResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidKeyResolverException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java index 00c60165f8a..fe541ff044f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolver.java @@ -31,10 +31,13 @@ import java.util.concurrent.CopyOnWriteArrayList; import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DEREncodedKeyValueResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.DSAKeyValueResolver; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.KeyInfoReferenceResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RSAKeyValueResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.RetrievalMethodResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509CertificateResolver; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509DigestResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509IssuerSerialResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SKIResolver; import com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations.X509SubjectNameResolver; @@ -277,6 +280,9 @@ public class KeyResolver { keyResolverList.add(new KeyResolver(new RetrievalMethodResolver())); keyResolverList.add(new KeyResolver(new X509SubjectNameResolver())); keyResolverList.add(new KeyResolver(new X509IssuerSerialResolver())); + keyResolverList.add(new KeyResolver(new DEREncodedKeyValueResolver())); + keyResolverList.add(new KeyResolver(new KeyInfoReferenceResolver())); + keyResolverList.add(new KeyResolver(new X509DigestResolver())); resolverVector.addAll(keyResolverList); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java index f0069949b2f..028a0e9dec2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverException.java @@ -2,90 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - -/** - * - * - * - * - * @author $Author: mullan $ - * - */ public class KeyResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor KeyResolverException - * - */ - public KeyResolverException() { - super(); - } + /** + * Constructor KeyResolverException + * + */ + public KeyResolverException() { + super(); + } - /** - * Constructor KeyResolverException - * - * @param _msgID - */ - public KeyResolverException(String _msgID) { - super(_msgID); - } + /** + * Constructor KeyResolverException + * + * @param msgID + */ + public KeyResolverException(String msgID) { + super(msgID); + } - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param exArgs - */ - public KeyResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor KeyResolverException + * + * @param msgID + * @param exArgs + */ + public KeyResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param _originalException - */ - public KeyResolverException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor KeyResolverException + * + * @param msgID + * @param originalException + */ + public KeyResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor KeyResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public KeyResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor KeyResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public KeyResolverException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java index 3e5c82ccfe5..78622d79336 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/KeyResolverSpi.java @@ -2,24 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver; +import java.security.PrivateKey; import java.security.PublicKey; import java.security.cert.X509Certificate; import java.util.HashMap; @@ -30,78 +33,89 @@ import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import org.w3c.dom.Element; /** - * This class is abstract class for a child KeyInfo Elemnet. + * This class is an abstract class for a child KeyInfo Element. * - * If you want your KeyResolver, at first you must extend this class, and register + * If you want the your KeyResolver, at firstly you must extend this class, and register * as following in config.xml *

  *  <KeyResolver URI="http://www.w3.org/2000/09/xmldsig#KeyValue"
  *   JAVACLASS="MyPackage.MyKeyValueImpl"//gt;
  * 
- * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public abstract class KeyResolverSpi { - /** - * This method helps the {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} to decide whether a - * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi} is able to perform the requested action. - * - * @param element - * @param BaseURI - * @param storage - * @return - */ - public boolean engineCanResolve(Element element, String BaseURI, - StorageResolver storage) { - throw new UnsupportedOperationException(); - } - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved public key from the registered from the element. - * - * @throws KeyResolverException - */ - public PublicKey engineResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - throw new UnsupportedOperationException(); + /** Field properties */ + protected java.util.Map properties = null; + + protected boolean globalResolver = false; + + protected boolean secureValidation; + + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param baseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + throw new UnsupportedOperationException(); + } + + /** + * Method engineResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved public key from the registered from the element. + * + * @throws KeyResolverException + */ + public PublicKey engineResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + throw new UnsupportedOperationException(); }; - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved public key from the registered from the element. - * - * @throws KeyResolverException - */ + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved public key from the registered from the element. + * + * @throws KeyResolverException + */ public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolvePublicKey(element, BaseURI, storage); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolvePublicKey(element, baseURI, storage); } private KeyResolverSpi cloneIfNeeded() throws KeyResolverException { - KeyResolverSpi tmp=this; + KeyResolverSpi tmp = this; if (globalResolver) { - try { - tmp = (KeyResolverSpi) getClass().newInstance(); - } catch (InstantiationException e) { - throw new KeyResolverException("",e); - } catch (IllegalAccessException e) { - throw new KeyResolverException("",e); - } + try { + tmp = getClass().newInstance(); + } catch (InstantiationException e) { + throw new KeyResolverException("", e); + } catch (IllegalAccessException e) { + throw new KeyResolverException("", e); + } } return tmp; } @@ -110,116 +124,138 @@ public abstract class KeyResolverSpi { * Method engineResolveCertificate * * @param element - * @param BaseURI + * @param baseURI * @param storage * @return resolved X509Certificate key from the registered from the elements * * @throws KeyResolverException */ public X509Certificate engineResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException{ - throw new UnsupportedOperationException(); + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException{ + throw new UnsupportedOperationException(); }; - /** - * Method engineResolveCertificate - * - * @param element - * @param BaseURI - * @param storage - * @return resolved X509Certificate key from the registered from the elements - * - * @throws KeyResolverException - */ + /** + * Method engineLookupResolveX509Certificate + * + * @param element + * @param baseURI + * @param storage + * @return resolved X509Certificate key from the registered from the elements + * + * @throws KeyResolverException + */ public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolveX509Certificate(element, BaseURI, storage); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolveX509Certificate(element, baseURI, storage); } /** * Method engineResolveSecretKey * * @param element - * @param BaseURI + * @param baseURI * @param storage * @return resolved SecretKey key from the registered from the elements * * @throws KeyResolverException */ public SecretKey engineResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException{ - throw new UnsupportedOperationException(); + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException{ + throw new UnsupportedOperationException(); }; - /** - * Method engineResolveSecretKey - * - * @param element - * @param BaseURI - * @param storage - * @return resolved SecretKey key from the registered from the elements - * - * @throws KeyResolverException - */ - public SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - KeyResolverSpi tmp = cloneIfNeeded(); - if (!tmp.engineCanResolve(element, BaseURI, storage)) - return null; - return tmp.engineResolveSecretKey(element, BaseURI, storage); - } + /** + * Method engineLookupAndResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + KeyResolverSpi tmp = cloneIfNeeded(); + if (!tmp.engineCanResolve(element, baseURI, storage)) { + return null; + } + return tmp.engineResolveSecretKey(element, baseURI, storage); + } - /** Field _properties */ - protected java.util.Map _properties = null; + /** + * Method engineLookupAndResolvePrivateKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key from the registered from the elements + * + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + // This method was added later, it has no equivalent + // engineResolvePrivateKey() in the old API. + // We cannot throw UnsupportedOperationException because + // KeyResolverSpi implementations who don't know about + // this method would stop the search too early. + return null; + } - protected boolean globalResolver=false; + /** + * Method engineSetProperty + * + * @param key + * @param value + */ + public void engineSetProperty(String key, String value) { + if (properties == null) { + properties = new HashMap(); + } + properties.put(key, value); + } - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) - _properties=new HashMap(); - this._properties.put(key, value); - } + /** + * Method engineGetProperty + * + * @param key + * @return obtain the property appointed by key + */ + public String engineGetProperty(String key) { + if (properties == null) { + return null; + } - /** - * Method engineGetProperty - * - * @param key - * @return obtain the property appointed by key - */ - public String engineGetProperty(String key) { - if (_properties==null) - return null; + return properties.get(key); + } - return this._properties.get(key); - } + /** + * Method understandsProperty + * + * @param propertyToTest + * @return true if understood the property + */ + public boolean understandsProperty(String propertyToTest) { + if (properties == null) { + return false; + } - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understood the property - */ - public boolean understandsProperty(String propertyToTest) { - if (_properties==null) - return false; + return properties.get(propertyToTest) != null; + } - return this._properties.get(propertyToTest)!=null; - } - public void setGlobalResolver(boolean globalResolver) { + public void setGlobalResolver(boolean globalResolver) { this.globalResolver = globalResolver; - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java new file mode 100644 index 00000000000..dbd2e084f0c --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DEREncodedKeyValueResolver.java @@ -0,0 +1,83 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +import javax.crypto.SecretKey; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.DEREncodedKeyValue; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * KeyResolverSpi implementation which resolves public keys from a + * dsig11:DEREncodedKeyValue element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class DEREncodedKeyValueResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DEREncodedKeyValueResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_DERENCODEDKEYVALUE); + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + DEREncodedKeyValue derKeyValue = new DEREncodedKeyValue(element, baseURI); + return derKeyValue.getPublicKey(); + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** {@inheritDoc}. */ + public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java index 20bf7bad777..784d5fc874d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/DSAKeyValueResolver.java @@ -2,30 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.keyvalues.DSAKeyValue; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; @@ -34,66 +33,70 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class DSAKeyValueResolver extends KeyResolverSpi { - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { - if (element == null) { - return null; - } - Element dsaKeyElement=null; - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - if (isKeyValue) { - dsaKeyElement = - XMLUtils.selectDsNode(element.getFirstChild(),Constants._TAG_DSAKEYVALUE,0); - } else if (XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_DSAKEYVALUE)) { - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:DSAKeyValue directly (without KeyValue) - dsaKeyElement = element; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DSAKeyValueResolver.class.getName()); + + + /** + * Method engineResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (element == null) { + return null; + } + Element dsaKeyElement = null; + boolean isKeyValue = + XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE); + if (isKeyValue) { + dsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_DSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_DSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:DSAKeyValue directly (without KeyValue) + dsaKeyElement = element; + } + + if (dsaKeyElement == null) { + return null; + } + + try { + DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, BaseURI); + PublicKey pk = dsaKeyValue.getPublicKey(); + + return pk; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); } + //do nothing + } - if (dsaKeyElement == null) { - return null; - } - - try { - DSAKeyValue dsaKeyValue = new DSAKeyValue(dsaKeyElement, - BaseURI); - PublicKey pk = dsaKeyValue.getPublicKey(); - - return pk; - } catch (XMLSecurityException ex) { - //do nothing - } - - return null; - } + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage){ - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java index 6adc050e893..a1be10b977f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/EncryptedKeyResolver.java @@ -2,39 +2,43 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; import java.security.Key; import java.security.PublicKey; import java.security.cert.X509Certificate; +import java.util.ArrayList; +import java.util.List; import javax.crypto.SecretKey; import com.sun.org.apache.xml.internal.security.encryption.EncryptedKey; import com.sun.org.apache.xml.internal.security.encryption.XMLCipher; +import com.sun.org.apache.xml.internal.security.encryption.XMLEncryptionException; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; import com.sun.org.apache.xml.internal.security.utils.EncryptionConstants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** * The EncryptedKeyResolver is not a generic resolver. It can * only be for specific instantiations, as the key being unwrapped will @@ -47,78 +51,100 @@ import org.w3c.dom.Element; * * @author Berin Lautenbach */ - public class EncryptedKeyResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValueResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(EncryptedKeyResolver.class.getName()); + private Key kek; + private String algorithm; + private List internalKeyResolvers; - Key _kek; - String _algorithm; - - /** - * Constructor for use when a KEK needs to be derived from a KeyInfo - * list - * @param algorithm - */ - public EncryptedKeyResolver(String algorithm) { - _kek = null; - _algorithm=algorithm; - } - - /** - * Constructor used for when a KEK has been set - * @param algorithm - * @param kek - */ - - public EncryptedKeyResolver(String algorithm, Key kek) { - _algorithm = algorithm; - _kek = kek; + /** + * Constructor for use when a KEK needs to be derived from a KeyInfo + * list + * @param algorithm + */ + public EncryptedKeyResolver(String algorithm) { + kek = null; + this.algorithm = algorithm; + } + /** + * Constructor used for when a KEK has been set + * @param algorithm + * @param kek + */ + public EncryptedKeyResolver(String algorithm, Key kek) { + this.algorithm = algorithm; + this.kek = kek; + } + + /** + * This method is used to add a custom {@link KeyResolverSpi} to help + * resolve the KEK. + * + * @param realKeyResolver + */ + public void registerInternalKeyResolver(KeyResolverSpi realKeyResolver) { + if (internalKeyResolvers == null) { + internalKeyResolvers = new ArrayList(); } + internalKeyResolvers.add(realKeyResolver); + } /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - SecretKey key=null; - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "EncryptedKeyResolver - Can I resolve " + element.getTagName()); + if (element == null) { + return null; + } - if (element == null) { - return null; - } + SecretKey key = null; + boolean isEncryptedKey = + XMLUtils.elementIsInEncryptionSpace(element, EncryptionConstants._TAG_ENCRYPTEDKEY); + if (isEncryptedKey) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); + } + try { + XMLCipher cipher = XMLCipher.getInstance(); + cipher.init(XMLCipher.UNWRAP_MODE, kek); + if (internalKeyResolvers != null) { + int size = internalKeyResolvers.size(); + for (int i = 0; i < size; i++) { + cipher.registerInternalKeyResolver(internalKeyResolvers.get(i)); + } + } + EncryptedKey ek = cipher.loadEncryptedKey(element); + key = (SecretKey) cipher.decryptKey(ek, algorithm); + } catch (XMLEncryptionException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + } - boolean isEncryptedKey = XMLUtils.elementIsInEncryptionSpace(element, - EncryptionConstants._TAG_ENCRYPTEDKEY); - - if (isEncryptedKey) { - log.log(java.util.logging.Level.FINE, "Passed an Encrypted Key"); - try { - XMLCipher cipher = XMLCipher.getInstance(); - cipher.init(XMLCipher.UNWRAP_MODE, _kek); - EncryptedKey ek = cipher.loadEncryptedKey(element); - key = (SecretKey) cipher.decryptKey(ek, _algorithm); - } - catch (Exception e) {} - } - - return key; - } + return key; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java new file mode 100644 index 00000000000..0e63715e2df --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/KeyInfoReferenceResolver.java @@ -0,0 +1,290 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; + +import javax.crypto.SecretKey; +import javax.xml.XMLConstants; +import javax.xml.namespace.QName; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.parsers.ParserConfigurationException; + +import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.KeyInfo; +import com.sun.org.apache.xml.internal.security.keys.content.KeyInfoReference; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; +import org.w3c.dom.Attr; +import org.w3c.dom.Document; +import org.w3c.dom.Element; +import org.xml.sax.SAXException; + +/** + * KeyResolverSpi implementation which resolves public keys, private keys, secret keys, and X.509 certificates from a + * dsig11:KeyInfoReference element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class KeyInfoReferenceResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(KeyInfoReferenceResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignature11Space(element, Constants._TAG_KEYINFOREFERENCE); + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getPublicKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getX509Certificate(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getSecretKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public PrivateKey engineLookupAndResolvePrivateKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + KeyInfo referent = resolveReferentKeyInfo(element, baseURI, storage); + if (referent != null) { + return referent.getPrivateKey(); + } + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** + * Resolve the KeyInfoReference Element's URI attribute into a KeyInfo instance. + * + * @param element + * @param baseURI + * @param storage + * @return the KeyInfo which is referred to by this KeyInfoReference, or null if can not be resolved + * @throws XMLSecurityException + */ + private KeyInfo resolveReferentKeyInfo(Element element, String baseURI, StorageResolver storage) throws XMLSecurityException { + KeyInfoReference reference = new KeyInfoReference(element, baseURI); + Attr uriAttr = reference.getURIAttr(); + + XMLSignatureInput resource = resolveInput(uriAttr, baseURI, secureValidation); + + Element referentElement = null; + try { + referentElement = obtainReferenceElement(resource); + } catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + return null; + } + + if (referentElement == null) { + log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference URI returned null: " + uriAttr.getValue()); + return null; + } + + validateReference(referentElement); + + KeyInfo referent = new KeyInfo(referentElement, baseURI); + referent.addStorageResolver(storage); + return referent; + } + + /** + * Validate the Element referred to by the KeyInfoReference. + * + * @param referentElement + * + * @throws XMLSecurityException + */ + private void validateReference(Element referentElement) throws XMLSecurityException { + if (!XMLUtils.elementIsInSignatureSpace(referentElement, Constants._TAG_KEYINFO)) { + Object exArgs[] = { new QName(referentElement.getNamespaceURI(), referentElement.getLocalName()) }; + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.WrongType", exArgs); + } + + KeyInfo referent = new KeyInfo(referentElement, ""); + if (referent.containsKeyInfoReference()) { + if (secureValidation) { + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithSecure"); + } else { + // Don't support chains of references at this time. If do support in the future, this is where the code + // would go to validate that don't have a cycle, resulting in an infinite loop. This may be unrealistic + // to implement, and/or very expensive given remote URI references. + throw new XMLSecurityException("KeyInfoReferenceResolver.InvalidReferentElement.ReferenceWithoutSecure"); + } + } + + } + + /** + * Resolve the XML signature input represented by the specified URI. + * + * @param uri + * @param baseURI + * @param secureValidation + * @return + * @throws XMLSecurityException + */ + private XMLSignatureInput resolveInput(Attr uri, String baseURI, boolean secureValidation) + throws XMLSecurityException { + ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); + XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + return resource; + } + + /** + * Resolve the Element effectively represented by the XML signature input source. + * + * @param resource + * @return + * @throws CanonicalizationException + * @throws ParserConfigurationException + * @throws IOException + * @throws SAXException + * @throws KeyResolverException + */ + private Element obtainReferenceElement(XMLSignatureInput resource) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException, KeyResolverException { + + Element e; + if (resource.isElement()){ + e = (Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + log.log(java.util.logging.Level.FINE, "De-reference of KeyInfoReference returned an unsupported NodeSet"); + return null; + } else { + // Retrieved resource is a byte stream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + } + return e; + } + + /** + * Parses a byte array and returns the parsed Element. + * + * @param bytes + * @return the Document Element after parsing bytes + * @throws KeyResolverException if something goes wrong + */ + private Element getDocFromBytes(byte[] bytes) throws KeyResolverException { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(bytes)); + return doc.getDocumentElement(); + } catch (SAXException ex) { + throw new KeyResolverException("empty", ex); + } catch (IOException ex) { + throw new KeyResolverException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new KeyResolverException("empty", ex); + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java new file mode 100644 index 00000000000..708cda45049 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/PrivateKeyResolver.java @@ -0,0 +1,353 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.Key; +import java.security.KeyStore; +import java.security.KeyStoreException; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.CertificateEncodingException; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Enumeration; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.X509Data; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509IssuerSerial; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SubjectName; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a PrivateKey within a KeyStore based on the KeyInfo hints. + * For X509Data hints, the certificate associated with the private key entry must match. + * For a KeyName hint, the KeyName must match the alias of a PrivateKey entry within the KeyStore. + */ +public class PrivateKeyResolver extends KeyResolverSpi { + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(PrivateKeyResolver.class.getName()); + + private KeyStore keyStore; + private char[] password; + + /** + * Constructor. + */ + public PrivateKeyResolver(KeyStore keyStore, char[] password) { + this.keyStore = keyStore; + this.password = password; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param BaseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) { + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA) + || XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + return true; + } + + return false; + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param BaseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + PrivateKey privKey = resolveX509Data(element, baseURI); + if (privKey != null) { + return privKey; + } + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + log.log(java.util.logging.Level.FINE, "Can I resolve KeyName?"); + String keyName = element.getFirstChild().getNodeValue(); + + try { + Key key = keyStore.getKey(keyName, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + private PrivateKey resolveX509Data(Element element, String baseURI) { + log.log(java.util.logging.Level.FINE, "Can I resolve X509Data?"); + + try { + X509Data x509Data = new X509Data(element, baseURI); + + int len = x509Data.lengthSKI(); + for (int i = 0; i < len; i++) { + XMLX509SKI x509SKI = x509Data.itemSKI(i); + PrivateKey privKey = resolveX509SKI(x509SKI); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthIssuerSerial(); + for (int i = 0; i < len; i++) { + XMLX509IssuerSerial x509Serial = x509Data.itemIssuerSerial(i); + PrivateKey privKey = resolveX509IssuerSerial(x509Serial); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthSubjectName(); + for (int i = 0; i < len; i++) { + XMLX509SubjectName x509SubjectName = x509Data.itemSubjectName(i); + PrivateKey privKey = resolveX509SubjectName(x509SubjectName); + if (privKey != null) { + return privKey; + } + } + + len = x509Data.lengthCertificate(); + for (int i = 0; i < len; i++) { + XMLX509Certificate x509Cert = x509Data.itemCertificate(i); + PrivateKey privKey = resolveX509Certificate(x509Cert); + if (privKey != null) { + return privKey; + } + } + } catch (XMLSecurityException e) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } catch (KeyStoreException e) { + log.log(java.util.logging.Level.FINE, "KeyStoreException", e); + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Subject Key Identifier + */ + private PrivateKey resolveX509SKI(XMLX509SKI x509SKI) throws XMLSecurityException, KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509SKI?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509SKI certSKI = new XMLX509SKI(x509SKI.getDocument(), (X509Certificate) cert); + + if (certSKI.equals(x509SKI)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Issuer/Serial Number pair. + */ + private PrivateKey resolveX509IssuerSerial(XMLX509IssuerSerial x509Serial) throws KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509IssuerSerial?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509IssuerSerial certSerial = + new XMLX509IssuerSerial(x509Serial.getDocument(), (X509Certificate) cert); + + if (certSerial.equals(x509Serial)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Subject Name. + */ + private PrivateKey resolveX509SubjectName(XMLX509SubjectName x509SubjectName) throws KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509SubjectName?"); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + XMLX509SubjectName certSN = + new XMLX509SubjectName(x509SubjectName.getDocument(), (X509Certificate) cert); + + if (certSN.equals(x509SubjectName)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } + + /* + * Search for a private key entry in the KeyStore with the same Certificate. + */ + private PrivateKey resolveX509Certificate( + XMLX509Certificate x509Cert + ) throws XMLSecurityException, KeyStoreException { + log.log(java.util.logging.Level.FINE, "Can I resolve X509Certificate?"); + byte[] x509CertBytes = x509Cert.getCertificateBytes(); + + Enumeration aliases = keyStore.aliases(); + while (aliases.hasMoreElements()) { + String alias = aliases.nextElement(); + if (keyStore.isKeyEntry(alias)) { + + Certificate cert = keyStore.getCertificate(alias); + if (cert instanceof X509Certificate) { + byte[] certBytes = null; + + try { + certBytes = cert.getEncoded(); + } catch (CertificateEncodingException e1) { + } + + if (certBytes != null && Arrays.equals(certBytes, x509CertBytes)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + + try { + Key key = keyStore.getKey(alias, password); + if (key instanceof PrivateKey) { + return (PrivateKey) key; + } + } + catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + // Keep searching + } + } + } + } + } + + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java index fb38e872590..b493f98182d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RSAKeyValueResolver.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; @@ -34,69 +34,63 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class RSAKeyValueResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RSAKeyValueResolver.class.getName()); - - /** Field _rsaKeyElement */ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(RSAKeyValueResolver.class.getName()); - /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); - if (element == null) { - return null; - } + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + if (element == null) { + return null; + } - boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_KEYVALUE); - Element rsaKeyElement=null; - if (isKeyValue) { - rsaKeyElement = XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_RSAKEYVALUE, 0); - } else if (XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RSAKEYVALUE)) { - // this trick is needed to allow the RetrievalMethodResolver to eat a - // ds:RSAKeyValue directly (without KeyValue) - rsaKeyElement = element; - } + boolean isKeyValue = XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYVALUE); + Element rsaKeyElement = null; + if (isKeyValue) { + rsaKeyElement = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_RSAKEYVALUE, 0); + } else if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RSAKEYVALUE)) { + // this trick is needed to allow the RetrievalMethodResolver to eat a + // ds:RSAKeyValue directly (without KeyValue) + rsaKeyElement = element; + } + if (rsaKeyElement == null) { + return null; + } - if (rsaKeyElement == null) { - return null; - } + try { + RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, BaseURI); - try { - RSAKeyValue rsaKeyValue = new RSAKeyValue(rsaKeyElement, - BaseURI); + return rsaKeyValue.getPublicKey(); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } - return rsaKeyValue.getPublicKey(); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } + return null; + } - return null; - } + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) { - return null; - } - - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java index 4ba848a681d..e5159c084b6 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/RetrievalMethodResolver.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.io.ByteArrayInputStream; import java.io.IOException; import java.security.PublicKey; @@ -35,6 +35,8 @@ import java.util.ListIterator; import java.util.Set; import javax.xml.XMLConstants; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -51,11 +53,11 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; import org.w3c.dom.Attr; +import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; - /** * The RetrievalMethodResolver can retrieve public keys and certificates from * other locations. The location is specified using the ds:RetrievalMethod @@ -65,252 +67,325 @@ import org.xml.sax.SAXException; * RetrievalMethodResolver cannot handle itself, resolving of the extracted * element is delegated back to the KeyResolver mechanism. * - * @author $Author: mullan $ modified by Dave Garcia + * @author $Author: raul $ modified by Dave Garcia */ public class RetrievalMethodResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - RetrievalMethodResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(RetrievalMethodResolver.class.getName()); - /** - * Method engineResolvePublicKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - { - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RETRIEVALMETHOD)) { - return null; - } - - try { - //Create a retrieval method over the given element - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - String type = rm.getType(); - XMLSignatureInput resource=resolveInput(rm,BaseURI); - if (RetrievalMethod.TYPE_RAWX509.equals(type)) { - //a raw certificate, direct parsing is done! - X509Certificate cert=getRawCertificate(resource); - if (cert != null) { - return cert.getPublicKey(); - } - return null; - }; - Element e = obtainRefrenceElement(resource); - return resolveKey(e,BaseURI,storage); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "IOException", ex); - } catch (ParserConfigurationException e) { - log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); - } catch (SAXException e) { - log.log(java.util.logging.Level.FINE, "SAXException", e); - } - return null; - } - - static private Element obtainRefrenceElement(XMLSignatureInput resource) throws CanonicalizationException, ParserConfigurationException, IOException, SAXException, KeyResolverException { - Element e; - if (resource.isElement()){ - e=(Element) resource.getSubNode(); - } else if (resource.isNodeSet()) { - //Retrieved resource is a nodeSet - e=getDocumentElement(resource.getNodeSet()); - } else { - //Retrieved resource is an inputStream - byte inputBytes[] = resource.getBytes(); - e = getDocFromBytes(inputBytes); - //otherwise, we parse the resource, create an Element and delegate - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); - } - return e; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - { - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_RETRIEVALMETHOD)) { - return null; - } - - try { - RetrievalMethod rm = new RetrievalMethod(element, BaseURI); - String type = rm.getType(); - XMLSignatureInput resource=resolveInput(rm,BaseURI); - if (RetrievalMethod.TYPE_RAWX509.equals(type)) { - X509Certificate cert=getRawCertificate(resource); - return cert; - } - Element e = obtainRefrenceElement(resource); - return resolveCertificate(e,BaseURI,storage); - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "CertificateException", ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "IOException", ex); - } catch (ParserConfigurationException e) { - log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); - } catch (SAXException e) { - log.log(java.util.logging.Level.FINE, "SAXException", e); - } - return null; - } - - /** - * Retrieves a x509Certificate from the given information - * @param e - * @param BaseURI - * @param storage - * @return - * @throws KeyResolverException - */ - static private X509Certificate resolveCertificate(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); - //An element has been provided - if (e != null) { - return KeyResolver.getX509Certificate(e,BaseURI, storage); - } - return null; - } - - /** - * Retrieves a x509Certificate from the given information - * @param e - * @param BaseURI - * @param storage - * @return - * @throws KeyResolverException - */ - static private PublicKey resolveKey(Element e,String BaseURI,StorageResolver storage) throws KeyResolverException{ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}"+ e.getLocalName() + " Element"); - //An element has been provided - if (e != null) { - return KeyResolver.getPublicKey(e,BaseURI, storage); - } - return null; - } - - static private X509Certificate getRawCertificate(XMLSignatureInput resource) throws CanonicalizationException, IOException, CertificateException{ - byte inputBytes[] = resource.getBytes(); - // if the resource stores a raw certificate, we have to handle it - CertificateFactory certFact =CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); - X509Certificate cert =(X509Certificate) certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); - return cert; - } - /** - * Resolves the input from the given retrieval method - * @return - * @throws XMLSecurityException - */ - static private XMLSignatureInput resolveInput(RetrievalMethod rm,String BaseURI) throws XMLSecurityException{ - Attr uri = rm.getURIAttr(); - //Apply the trnasforms - Transforms transforms = rm.getTransforms(); - ResourceResolver resRes = ResourceResolver.getInstance(uri, BaseURI); - if (resRes != null) { - XMLSignatureInput resource = resRes.resolve(uri, BaseURI); - if (transforms != null) { - log.log(java.util.logging.Level.FINE, "We have Transforms"); - resource = transforms.performTransforms(resource); - } - return resource; - } - return null; - } - - /** - * Parses a byte array and returns the parsed Element. - * - * @param bytes - * @return the Document Element after parsing bytes - * @throws KeyResolverException if something goes wrong - */ - static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { - try { - javax.xml.parsers.DocumentBuilderFactory dbf =javax.xml.parsers.DocumentBuilderFactory.newInstance(); - dbf.setNamespaceAware(true); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder(); - org.w3c.dom.Document doc = - db.parse(new java.io.ByteArrayInputStream(bytes)); - return doc.getDocumentElement(); - } catch (org.xml.sax.SAXException ex) { - throw new KeyResolverException("empty", ex); - } catch (java.io.IOException ex) { - throw new KeyResolverException("empty", ex); - } catch (javax.xml.parsers.ParserConfigurationException ex) { - throw new KeyResolverException("empty", ex); - } - } - - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } - - static Element getDocumentElement(Set set) { - Iterator it=set.iterator(); - Element e=null; - while (it.hasNext()) { - Node currentNode=it.next(); - if (currentNode != null && currentNode.getNodeType() == Node.ELEMENT_NODE) { - e=(Element)currentNode; - break; - } - - } - List parents=new ArrayList(10); - - //Obtain all the parents of the elemnt - while (e != null) { - parents.add(e); - Node n=e.getParentNode(); - if (n == null || n.getNodeType() != Node.ELEMENT_NODE) { - break; - } - e=(Element)n; - } - //Visit them in reverse order. - ListIterator it2=parents.listIterator(parents.size()-1); - Element ele=null; - while (it2.hasPrevious()) { - ele=it2.previous(); - if (set.contains(ele)) { - return ele; - } + /** + * Method engineResolvePublicKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) { + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { + return null; } + + try { + // Create a retrieval method over the given element + RetrievalMethod rm = new RetrievalMethod(element, baseURI); + String type = rm.getType(); + XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + // a raw certificate, direct parsing is done! + X509Certificate cert = getRawCertificate(resource); + if (cert != null) { + return cert.getPublicKey(); + } return null; - } + } + Element e = obtainReferenceElement(resource); + + // Check to make sure that the reference is not to another RetrievalMethod + // which points to this element + if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) { + if (secureValidation) { + String error = "Error: It is forbidden to have one RetrievalMethod " + + "point to another with secure validation"; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, error); + } + return null; + } + RetrievalMethod rm2 = new RetrievalMethod(e, baseURI); + XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation); + Element e2 = obtainReferenceElement(resource2); + if (e2 == element) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other"); + } + return null; + } + } + + return resolveKey(e, baseURI, storage); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } + } catch (ParserConfigurationException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } + } catch (SAXException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + } + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage) { + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_RETRIEVALMETHOD)) { + return null; + } + + try { + RetrievalMethod rm = new RetrievalMethod(element, baseURI); + String type = rm.getType(); + XMLSignatureInput resource = resolveInput(rm, baseURI, secureValidation); + if (RetrievalMethod.TYPE_RAWX509.equals(type)) { + return getRawCertificate(resource); + } + + Element e = obtainReferenceElement(resource); + + // Check to make sure that the reference is not to another RetrievalMethod + // which points to this element + if (XMLUtils.elementIsInSignatureSpace(e, Constants._TAG_RETRIEVALMETHOD)) { + if (secureValidation) { + String error = "Error: It is forbidden to have one RetrievalMethod " + + "point to another with secure validation"; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, error); + } + return null; + } + RetrievalMethod rm2 = new RetrievalMethod(e, baseURI); + XMLSignatureInput resource2 = resolveInput(rm2, baseURI, secureValidation); + Element e2 = obtainReferenceElement(resource2); + if (e2 == element) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Error: Can't have RetrievalMethods pointing to each other"); + } + return null; + } + } + + return resolveCertificate(e, baseURI, storage); + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "CertificateException", ex); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "IOException", ex); + } + } catch (ParserConfigurationException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ParserConfigurationException", e); + } + } catch (SAXException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "SAXException", e); + } + } + return null; + } + + /** + * Retrieves a x509Certificate from the given information + * @param e + * @param baseURI + * @param storage + * @return + * @throws KeyResolverException + */ + private static X509Certificate resolveCertificate( + Element e, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); + } + // An element has been provided + if (e != null) { + return KeyResolver.getX509Certificate(e, baseURI, storage); + } + return null; + } + + /** + * Retrieves a PublicKey from the given information + * @param e + * @param baseURI + * @param storage + * @return + * @throws KeyResolverException + */ + private static PublicKey resolveKey( + Element e, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Now we have a {" + e.getNamespaceURI() + "}" + + e.getLocalName() + " Element"); + } + // An element has been provided + if (e != null) { + return KeyResolver.getPublicKey(e, baseURI, storage); + } + return null; + } + + private static Element obtainReferenceElement(XMLSignatureInput resource) + throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException, KeyResolverException { + Element e; + if (resource.isElement()){ + e = (Element) resource.getSubNode(); + } else if (resource.isNodeSet()) { + // Retrieved resource is a nodeSet + e = getDocumentElement(resource.getNodeSet()); + } else { + // Retrieved resource is an inputStream + byte inputBytes[] = resource.getBytes(); + e = getDocFromBytes(inputBytes); + // otherwise, we parse the resource, create an Element and delegate + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "we have to parse " + inputBytes.length + " bytes"); + } + } + return e; + } + + private static X509Certificate getRawCertificate(XMLSignatureInput resource) + throws CanonicalizationException, IOException, CertificateException { + byte inputBytes[] = resource.getBytes(); + // if the resource stores a raw certificate, we have to handle it + CertificateFactory certFact = + CertificateFactory.getInstance(XMLX509Certificate.JCA_CERT_ID); + X509Certificate cert = (X509Certificate) + certFact.generateCertificate(new ByteArrayInputStream(inputBytes)); + return cert; + } + + /** + * Resolves the input from the given retrieval method + * @return + * @throws XMLSecurityException + */ + private static XMLSignatureInput resolveInput( + RetrievalMethod rm, String baseURI, boolean secureValidation + ) throws XMLSecurityException { + Attr uri = rm.getURIAttr(); + // Apply the transforms + Transforms transforms = rm.getTransforms(); + ResourceResolver resRes = ResourceResolver.getInstance(uri, baseURI, secureValidation); + XMLSignatureInput resource = resRes.resolve(uri, baseURI, secureValidation); + if (transforms != null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "We have Transforms"); + } + resource = transforms.performTransforms(resource); + } + return resource; + } + + /** + * Parses a byte array and returns the parsed Element. + * + * @param bytes + * @return the Document Element after parsing bytes + * @throws KeyResolverException if something goes wrong + */ + private static Element getDocFromBytes(byte[] bytes) throws KeyResolverException { + try { + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setNamespaceAware(true); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + DocumentBuilder db = dbf.newDocumentBuilder(); + Document doc = db.parse(new ByteArrayInputStream(bytes)); + return doc.getDocumentElement(); + } catch (SAXException ex) { + throw new KeyResolverException("empty", ex); + } catch (IOException ex) { + throw new KeyResolverException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new KeyResolverException("empty", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } + + private static Element getDocumentElement(Set set) { + Iterator it = set.iterator(); + Element e = null; + while (it.hasNext()) { + Node currentNode = it.next(); + if (currentNode != null && Node.ELEMENT_NODE == currentNode.getNodeType()) { + e = (Element) currentNode; + break; + } + } + List parents = new ArrayList(); + + // Obtain all the parents of the elemnt + while (e != null) { + parents.add(e); + Node n = e.getParentNode(); + if (n == null || Node.ELEMENT_NODE != n.getNodeType()) { + break; + } + e = (Element) n; + } + // Visit them in reverse order. + ListIterator it2 = parents.listIterator(parents.size()-1); + Element ele = null; + while (it2.hasPrevious()) { + ele = (Element) it2.previous(); + if (set.contains(ele)) { + return ele; + } + } + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java new file mode 100644 index 00000000000..a5e239f2662 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SecretKeyResolver.java @@ -0,0 +1,129 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.Key; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a SecretKey within a KeyStore based on the KeyName. + * The KeyName is the key entry alias within the KeyStore. + */ +public class SecretKeyResolver extends KeyResolverSpi +{ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SecretKeyResolver.class.getName()); + + private KeyStore keyStore; + private char[] password; + + /** + * Constructor. + */ + public SecretKeyResolver(KeyStore keyStore, char[] password) { + this.keyStore = keyStore; + this.password = password; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param baseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String keyName = element.getFirstChild().getNodeValue(); + try { + Key key = keyStore.getKey(keyName, password); + if (key instanceof SecretKey) { + return (SecretKey) key; + } + } catch (Exception e) { + log.log(java.util.logging.Level.FINE, "Cannot recover the key", e); + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java new file mode 100644 index 00000000000..4b23ef1e207 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/SingleKeyResolver.java @@ -0,0 +1,172 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PrivateKey; +import java.security.PublicKey; +import java.security.cert.X509Certificate; +import javax.crypto.SecretKey; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * Resolves a single Key based on the KeyName. + */ +public class SingleKeyResolver extends KeyResolverSpi +{ + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SingleKeyResolver.class.getName()); + + private String keyName; + private PublicKey publicKey; + private PrivateKey privateKey; + private SecretKey secretKey; + + /** + * Constructor. + * @param keyName + * @param publicKey + */ + public SingleKeyResolver(String keyName, PublicKey publicKey) { + this.keyName = keyName; + this.publicKey = publicKey; + } + + /** + * Constructor. + * @param keyName + * @param privateKey + */ + public SingleKeyResolver(String keyName, PrivateKey privateKey) { + this.keyName = keyName; + this.privateKey = privateKey; + } + + /** + * Constructor. + * @param keyName + * @param secretKey + */ + public SingleKeyResolver(String keyName, SecretKey secretKey) { + this.keyName = keyName; + this.secretKey = secretKey; + } + + /** + * This method returns whether the KeyResolverSpi is able to perform the requested action. + * + * @param element + * @param BaseURI + * @param storage + * @return whether the KeyResolverSpi is able to perform the requested action. + */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + return XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME); + } + + /** + * Method engineLookupAndResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (publicKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return publicKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + return null; + } + + /** + * Method engineResolveSecretKey + * + * @param element + * @param baseURI + * @param storage + * @return resolved SecretKey key or null if no {@link SecretKey} could be obtained + * + * @throws KeyResolverException + */ + public SecretKey engineResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (secretKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return secretKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } + + /** + * Method engineResolvePrivateKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * @return resolved PrivateKey key or null if no {@link PrivateKey} could be obtained + * @throws KeyResolverException + */ + public PrivateKey engineLookupAndResolvePrivateKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + + if (privateKey != null + && XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) { + String name = element.getFirstChild().getNodeValue(); + if (keyName.equals(name)) { + return privateKey; + } + } + + log.log(java.util.logging.Level.FINE, "I can't"); + return null; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java index 06a49c6708e..06511c37c29 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509CertificateResolver.java @@ -2,30 +2,29 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; import java.security.cert.X509Certificate; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Certificate; import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; @@ -35,96 +34,93 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - /** * Resolves Certificates which are directly contained inside a * ds:X509Certificate Element. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class X509CertificateResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509CertificateResolver.class.getName()); + /** + * Method engineResolvePublicKey + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, BaseURI, storage); - /** - * Method engineResolvePublicKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + if (cert != null) { + return cert.getPublicKey(); + } - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + return null; + } - if (cert != null) { - return cert.getPublicKey(); - } + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String BaseURI, StorageResolver storage + ) throws KeyResolverException { - return null; - } - - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - - try { - Element[] els=XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509CERTIFICATE); - if ((els == null) || (els.length == 0)) { - Element el=XMLUtils.selectDsNode(element.getFirstChild(), - Constants._TAG_X509DATA,0); - if (el!=null) { - return engineLookupResolveX509Certificate(el, BaseURI, storage); - } - return null; - } - - // populate Object array - for (int i = 0; i < els.length; i++) { - XMLX509Certificate xmlCert=new XMLX509Certificate(els[i], BaseURI); - X509Certificate cert = xmlCert.getX509Certificate(); - if (cert!=null) { - return cert; + try { + Element[] els = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509CERTIFICATE); + if ((els == null) || (els.length == 0)) { + Element el = + XMLUtils.selectDsNode(element.getFirstChild(), Constants._TAG_X509DATA, 0); + if (el != null) { + return engineLookupResolveX509Certificate(el, BaseURI, storage); + } + return null; } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + // populate Object array + for (int i = 0; i < els.length; i++) { + XMLX509Certificate xmlCert = new XMLX509Certificate(els[i], BaseURI); + X509Certificate cert = xmlCert.getX509Certificate(); + if (cert != null) { + return cert; + } + } + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param BaseURI + * @param storage + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String BaseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java new file mode 100644 index 00000000000..c1b44e68a86 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509DigestResolver.java @@ -0,0 +1,164 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; + +import java.security.PublicKey; +import java.security.cert.Certificate; +import java.security.cert.X509Certificate; +import java.util.Arrays; +import java.util.Iterator; + +import javax.crypto.SecretKey; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.keys.content.X509Data; +import com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509Digest; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverException; +import com.sun.org.apache.xml.internal.security.keys.keyresolver.KeyResolverSpi; +import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver; +import com.sun.org.apache.xml.internal.security.utils.Constants; +import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import org.w3c.dom.Element; + +/** + * KeyResolverSpi implementation which resolves public keys and X.509 certificates from a + * dsig11:X509Digest element. + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public class X509DigestResolver extends KeyResolverSpi { + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509DigestResolver.class.getName()); + + /** {@inheritDoc}. */ + public boolean engineCanResolve(Element element, String baseURI, StorageResolver storage) { + if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + try { + X509Data x509Data = new X509Data(element, baseURI); + return x509Data.containsDigest(); + } catch (XMLSecurityException e) { + return false; + } + } else { + return false; + } + } + + /** {@inheritDoc}. */ + public PublicKey engineLookupAndResolvePublicKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + X509Certificate cert = this.engineLookupResolveX509Certificate(element, baseURI, storage); + + if (cert != null) { + return cert.getPublicKey(); + } + + return null; + } + + /** {@inheritDoc}. */ + public X509Certificate engineLookupResolveX509Certificate(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName()); + } + + if (!engineCanResolve(element, baseURI, storage)) { + return null; + } + + try { + return resolveCertificate(element, baseURI, storage); + } catch (XMLSecurityException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", e); + } + } + + return null; + } + + /** {@inheritDoc}. */ + public SecretKey engineLookupAndResolveSecretKey(Element element, String baseURI, StorageResolver storage) + throws KeyResolverException { + return null; + } + + /** + * Resolves from the storage resolver the actual certificate represented by the digest. + * + * @param element + * @param baseURI + * @param storage + * @return + * @throws XMLSecurityException + */ + private X509Certificate resolveCertificate(Element element, String baseURI, StorageResolver storage) + throws XMLSecurityException { + + XMLX509Digest x509Digests[] = null; + + Element x509childNodes[] = XMLUtils.selectDs11Nodes(element.getFirstChild(), Constants._TAG_X509DIGEST); + + if (x509childNodes == null || x509childNodes.length <= 0) { + return null; + } + + try { + checkStorage(storage); + + x509Digests = new XMLX509Digest[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509Digests[i] = new XMLX509Digest(x509childNodes[i], baseURI); + } + + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate) storageIterator.next(); + + for (int i = 0; i < x509Digests.length; i++) { + XMLX509Digest keyInfoDigest = x509Digests[i]; + byte[] certDigestBytes = XMLX509Digest.getDigestBytesFromCert(cert, keyInfoDigest.getAlgorithm()); + + if (Arrays.equals(keyInfoDigest.getDigestBytes(), certDigestBytes)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found certificate with: " + cert.getSubjectX500Principal().getName()); + } + return cert; + } + + } + } + + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method checkSrorage + * + * @param storage + * @throws KeyResolverException + */ + private void checkStorage(StorageResolver storage) throws KeyResolverException { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509DIGEST }; + KeyResolverException ex = new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java index 8f717e71689..1d00692bd03 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509IssuerSerialResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.keys.content.X509Data; @@ -35,114 +37,114 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; import com.sun.org.apache.xml.internal.security.utils.Constants; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class X509IssuerSerialResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - X509IssuerSerialResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509IssuerSerialResolver.class.getName()); - /** @inheritDoc */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** @inheritDoc */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** @inheritDoc */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - - X509Data x509data = null; - try { - x509data = new X509Data(element, BaseURI); - } catch (XMLSignatureException ex) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - if (x509data == null) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - - if (!x509data.containsIssuerSerial()) { - return null; - } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - throw ex; - } - - int noOfISS = x509data.lengthIssuerSerial(); - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); + /** @inheritDoc */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + X509Data x509data = null; + try { + x509data = new X509Data(element, baseURI); + } catch (XMLSignatureException ex) { if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " - + certSerial.getIssuerName()); - log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " - + certSerial.getSerialNumber().toString()); + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + + if (!x509data.containsIssuerSerial()) { + return null; + } + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509ISSUERSERIAL }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + throw ex; } - for (int i=0; i storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509IssuerSerial certSerial = new XMLX509IssuerSerial(element.getOwnerDocument(), cert); - if (certSerial.equals(xmliss)) { - log.log(java.util.logging.Level.FINE, "match !!! "); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate Issuer: " + certSerial.getIssuerName()); + log.log(java.util.logging.Level.FINE, "Found Certificate Serial: " + certSerial.getSerialNumber().toString()); + } - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + for (int i = 0; i < noOfISS; i++) { + XMLX509IssuerSerial xmliss = x509data.itemIssuerSerial(i); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Element Issuer: " + + xmliss.getIssuerName()); + log.log(java.util.logging.Level.FINE, "Found Element Serial: " + + xmliss.getSerialNumber().toString()); + } + + if (certSerial.equals(xmliss)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + } + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "no match..."); + } + } } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } - /** @inheritDoc */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) { - return null; - } + /** @inheritDoc */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java index ac90842059e..8dd381e59ba 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SKIResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -35,124 +37,121 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * - * @author $Author: mullan $ - */ public class X509SKIResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(X509SKIResolver.class.getName()); - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** + * Method engineResolvePublicKey + * + * @param element + * @param baseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - } - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA)) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - /** Field _x509childObject[] */ - XMLX509SKI x509childObject[] = null; - - Element x509childNodes[] = null; - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509SKI); - - if (!((x509childNodes != null) - && (x509childNodes.length > 0))) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SKI }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); - - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = new XMLX509SKI[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SKI(x509childNodes[i], BaseURI); - } - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); - - for (int i = 0; i < x509childObject.length; i++) { - if (certSKI.equals(x509childObject[i])) { - log.log(java.util.logging.Level.FINE, "Return PublicKey from " - + cert.getSubjectDN().getName()); - - return cert; - } + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); } - } - } catch (XMLSecurityException ex) { - throw new KeyResolverException("empty", ex); - } + return null; + } + /** Field _x509childObject[] */ + XMLX509SKI x509childObject[] = null; - return null; - } + Element x509childNodes[] = null; + x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SKI); - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + if (!((x509childNodes != null) && (x509childNodes.length > 0))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509SKI }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; + } + + x509childObject = new XMLX509SKI[x509childNodes.length]; + + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SKI(x509childNodes[i], baseURI); + } + + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SKI certSKI = new XMLX509SKI(element.getOwnerDocument(), cert); + + for (int i = 0; i < x509childObject.length; i++) { + if (certSKI.equals(x509childObject[i])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Return PublicKey from " + cert.getSubjectX500Principal().getName()); + } + + return cert; + } + } + } + } catch (XMLSecurityException ex) { + throw new KeyResolverException("empty", ex); + } + + return null; + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java index 05e82226c4c..dc2ca4abd5a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/keyresolver/implementations/X509SubjectNameResolver.java @@ -2,28 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.keyresolver.implementations; - - import java.security.PublicKey; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; +import java.util.Iterator; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -35,133 +37,140 @@ import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Element; - -/** - * - * @author $Author: mullan $ - */ public class X509SubjectNameResolver extends KeyResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - X509SubjectNameResolver.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(X509SubjectNameResolver.class.getName()); - /** - * Method engineResolvePublicKey - * - * @param element - * @param BaseURI - * @param storage - * @return null if no {@link PublicKey} could be obtained - * @throws KeyResolverException - */ - public PublicKey engineLookupAndResolvePublicKey( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { + /** + * Method engineResolvePublicKey + * + * @param element + * @param BaseURI + * @param storage + * @return null if no {@link PublicKey} could be obtained + * @throws KeyResolverException + */ + public PublicKey engineLookupAndResolvePublicKey( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { - X509Certificate cert = this.engineLookupResolveX509Certificate(element, - BaseURI, storage); + X509Certificate cert = + this.engineLookupResolveX509Certificate(element, baseURI, storage); - if (cert != null) { - return cert.getPublicKey(); - } + if (cert != null) { + return cert.getPublicKey(); + } - return null; - } + return null; + } - /** - * Method engineResolveX509Certificate - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - * @throws KeyResolverException - */ - public X509Certificate engineLookupResolveX509Certificate( - Element element, String BaseURI, StorageResolver storage) - throws KeyResolverException { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); - Element[] x509childNodes = null; - XMLX509SubjectName x509childObject[] = null; + /** + * Method engineResolveX509Certificate + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + * @throws KeyResolverException + */ + public X509Certificate engineLookupResolveX509Certificate( + Element element, String baseURI, StorageResolver storage + ) throws KeyResolverException { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Can I resolve " + element.getTagName() + "?"); + } + Element[] x509childNodes = null; + XMLX509SubjectName x509childObject[] = null; - if (!XMLUtils.elementIsInSignatureSpace(element, - Constants._TAG_X509DATA) ) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; - } - x509childNodes = XMLUtils.selectDsNodes(element.getFirstChild(), - Constants._TAG_X509SUBJECTNAME); + if (!XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + x509childNodes = + XMLUtils.selectDsNodes(element.getFirstChild(), Constants._TAG_X509SUBJECTNAME); if (!((x509childNodes != null) - && (x509childNodes.length > 0))) { - log.log(java.util.logging.Level.FINE, "I can't"); - return null; + && (x509childNodes.length > 0))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I can't"); + } + return null; + } + + try { + if (storage == null) { + Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; + KeyResolverException ex = + new KeyResolverException("KeyResolver.needStorageResolver", exArgs); + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "", ex); + } + + throw ex; } - try { - if (storage == null) { - Object exArgs[] = { Constants._TAG_X509SUBJECTNAME }; - KeyResolverException ex = - new KeyResolverException("KeyResolver.needStorageResolver", - exArgs); + x509childObject = new XMLX509SubjectName[x509childNodes.length]; - log.log(java.util.logging.Level.INFO, "", ex); - - throw ex; - } - - x509childObject = - new XMLX509SubjectName[x509childNodes.length]; - - for (int i = 0; i < x509childNodes.length; i++) { - x509childObject[i] = - new XMLX509SubjectName(x509childNodes[i], - BaseURI); - } - - while (storage.hasNext()) { - X509Certificate cert = storage.next(); - XMLX509SubjectName certSN = - new XMLX509SubjectName(element.getOwnerDocument(), cert); - - log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); - - for (int i = 0; i < x509childObject.length; i++) { - log.log(java.util.logging.Level.FINE, "Found Element SN: " - + x509childObject[i].getSubjectName()); - - if (certSN.equals(x509childObject[i])) { - log.log(java.util.logging.Level.FINE, "match !!! "); - - return cert; - } - log.log(java.util.logging.Level.FINE, "no match..."); + for (int i = 0; i < x509childNodes.length; i++) { + x509childObject[i] = new XMLX509SubjectName(x509childNodes[i], baseURI); } - } - return null; - } catch (XMLSecurityException ex) { - log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + Iterator storageIterator = storage.getIterator(); + while (storageIterator.hasNext()) { + X509Certificate cert = (X509Certificate)storageIterator.next(); + XMLX509SubjectName certSN = + new XMLX509SubjectName(element.getOwnerDocument(), cert); - throw new KeyResolverException("generic.EmptyMessage", ex); - } - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Certificate SN: " + certSN.getSubjectName()); + } - /** - * Method engineResolveSecretKey - * @inheritDoc - * @param element - * @param BaseURI - * @param storage - * - */ - public javax.crypto.SecretKey engineLookupAndResolveSecretKey( - Element element, String BaseURI, StorageResolver storage) - { - return null; - } + for (int i = 0; i < x509childObject.length; i++) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found Element SN: " + + x509childObject[i].getSubjectName()); + } + + if (certSN.equals(x509childObject[i])) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "match !!! "); + } + + return cert; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "no match..."); + } + } + } + + return null; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "XMLSecurityException", ex); + } + + throw new KeyResolverException("generic.EmptyMessage", ex); + } + } + + /** + * Method engineResolveSecretKey + * @inheritDoc + * @param element + * @param baseURI + * @param storage + * + */ + public javax.crypto.SecretKey engineLookupAndResolveSecretKey( + Element element, String baseURI, StorageResolver storage + ) { + return null; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java index 7b11e848e8f..88392495d33 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolver.java @@ -2,197 +2,187 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; import java.security.KeyStore; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Iterator; import java.util.List; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.implementations.KeyStoreResolver; import com.sun.org.apache.xml.internal.security.keys.storage.implementations.SingleCertificateResolver; - /** * This class collects customized resolvers for Certificates. - * - * @author $Author: mullan $ */ public class StorageResolver { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(StorageResolver.class.getName()); - /** Field _storageResolvers */ - List _storageResolvers = null; + /** Field storageResolvers */ + private List storageResolvers = null; - /** Field _iterator */ - Iterator _iterator = null; + /** + * Constructor StorageResolver + * + */ + public StorageResolver() {} - /** - * Constructor StorageResolver - * - */ - public StorageResolver() {} + /** + * Constructor StorageResolver + * + * @param resolver + */ + public StorageResolver(StorageResolverSpi resolver) { + this.add(resolver); + } - /** - * Constructor StorageResolver - * - * @param resolver - */ - public StorageResolver(StorageResolverSpi resolver) { - this.add(resolver); - } + /** + * Method addResolver + * + * @param resolver + */ + public void add(StorageResolverSpi resolver) { + if (storageResolvers == null) { + storageResolvers = new ArrayList(); + } + this.storageResolvers.add(resolver); + } - /** - * Method addResolver - * - * @param resolver - */ - public void add(StorageResolverSpi resolver) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._storageResolvers.add(resolver); + /** + * Constructor StorageResolver + * + * @param keyStore + */ + public StorageResolver(KeyStore keyStore) { + this.add(keyStore); + } - this._iterator = null; - } + /** + * Method addKeyStore + * + * @param keyStore + */ + public void add(KeyStore keyStore) { + try { + this.add(new KeyStoreResolver(keyStore)); + } catch (StorageResolverException ex) { + log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); + } + } - /** - * Constructor StorageResolver - * - * @param keyStore - */ - public StorageResolver(KeyStore keyStore) { - this.add(keyStore); - } + /** + * Constructor StorageResolver + * + * @param x509certificate + */ + public StorageResolver(X509Certificate x509certificate) { + this.add(x509certificate); + } - /** - * Method addKeyStore - * - * @param keyStore - */ - public void add(KeyStore keyStore) { + /** + * Method addCertificate + * + * @param x509certificate + */ + public void add(X509Certificate x509certificate) { + this.add(new SingleCertificateResolver(x509certificate)); + } - try { - this.add(new KeyStoreResolver(keyStore)); - } catch (StorageResolverException ex) { - log.log(java.util.logging.Level.SEVERE, "Could not add KeyStore because of: ", ex); - } - } + /** + * Method getIterator + * @return the iterator for the resolvers. + */ + public Iterator getIterator() { + return new StorageResolverIterator(this.storageResolvers.iterator()); + } - /** - * Constructor StorageResolver - * - * @param x509certificate - */ - public StorageResolver(X509Certificate x509certificate) { - this.add(x509certificate); - } + /** + * Class StorageResolverIterator + * This iterates over all the Certificates found in all the resolvers. + */ + static class StorageResolverIterator implements Iterator { - /** - * Method addCertificate - * - * @param x509certificate - */ - public void add(X509Certificate x509certificate) { - this.add(new SingleCertificateResolver(x509certificate)); - } + /** Field resolvers */ + Iterator resolvers = null; - /** - * Method getIterator - * @return the iterator for the resolvers. - * - */ - public Iterator getIterator() { + /** Field currentResolver */ + Iterator currentResolver = null; - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } + /** + * Constructor StorageResolverIterator + * + * @param resolvers + */ + public StorageResolverIterator(Iterator resolvers) { + this.resolvers = resolvers; + currentResolver = findNextResolver(); + } - return this._iterator; - } + /** @inheritDoc */ + public boolean hasNext() { + if (currentResolver == null) { + return false; + } - /** - * Method hasNext - * - * @return true if there is more elements. - */ - public boolean hasNext() { + if (currentResolver.hasNext()) { + return true; + } - if (this._iterator == null) { - if (_storageResolvers==null) - _storageResolvers=new ArrayList(); - this._iterator = new StorageResolverIterator(this._storageResolvers.iterator()); - } + currentResolver = findNextResolver(); + return (currentResolver != null); + } - return this._iterator.hasNext(); - } + /** @inheritDoc */ + public Certificate next() { + if (hasNext()) { + return currentResolver.next(); + } - /** - * Method next - * - * @return the next element - */ - public X509Certificate next() { - return (X509Certificate) this._iterator.next(); - } + throw new NoSuchElementException(); + } - /** - * Class StorageResolverIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class StorageResolverIterator implements Iterator { + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } - /** Field _resolvers */ - Iterator _resolvers = null; + // Find the next storage with at least one element and return its Iterator + private Iterator findNextResolver() { + while (resolvers.hasNext()) { + StorageResolverSpi resolverSpi = resolvers.next(); + Iterator iter = resolverSpi.getIterator(); + if (iter.hasNext()) { + return iter; + } + } - /** - * Constructor FilesystemIterator - * - * @param resolvers - */ - public StorageResolverIterator(Iterator resolvers) { - this._resolvers = resolvers; - } - - /** @inheritDoc */ - public boolean hasNext() { - return _resolvers.hasNext(); - } - - /** @inheritDoc */ - public Object next() { - return _resolvers.next(); - } - - /** - * Method remove - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + return null; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java index 29dff030f78..af8af531aab 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverException.java @@ -2,86 +2,82 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; -/** - * - * @author $Author: mullan $ - */ public class StorageResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor StorageResolverException - * - */ - public StorageResolverException() { - super(); - } + /** + * Constructor StorageResolverException + * + */ + public StorageResolverException() { + super(); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - */ - public StorageResolverException(String _msgID) { - super(_msgID); - } + /** + * Constructor StorageResolverException + * + * @param msgID + */ + public StorageResolverException(String msgID) { + super(msgID); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param exArgs - */ - public StorageResolverException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param exArgs + */ + public StorageResolverException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param _originalException - */ - public StorageResolverException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param originalException + */ + public StorageResolverException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor StorageResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public StorageResolverException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor StorageResolverException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public StorageResolverException(String msgID, Object exArgs[], + Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java index 07211253d22..7cc075a36f9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/StorageResolverSpi.java @@ -2,39 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage; - - +import java.security.cert.Certificate; import java.util.Iterator; - -/** - * - * @author $Author: mullan $ - */ public abstract class StorageResolverSpi { - /** - * Method getIterator - * - * @return the iterator for the storage - */ - public abstract Iterator getIterator(); + /** + * Method getIterator + * + * @return the iterator for the storage + */ + public abstract Iterator getIterator(); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java index 3b38e4a2572..6d7057e1e45 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/CertsInFilesystemDirectoryResolver.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; @@ -24,6 +26,7 @@ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; +import java.security.cert.Certificate; import java.security.cert.CertificateException; import java.security.cert.CertificateExpiredException; import java.security.cert.CertificateFactory; @@ -39,188 +42,188 @@ import com.sun.org.apache.xml.internal.security.utils.Base64; /** * This {@link StorageResolverSpi} makes all raw (binary) {@link X509Certificate}s - * which reside as files in a single directory available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ + * which reside as files in a single directory available to the + * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. */ public class CertsInFilesystemDirectoryResolver extends StorageResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger( - CertsInFilesystemDirectoryResolver.class.getName()); + CertsInFilesystemDirectoryResolver.class.getName() + ); - /** Field _merlinsCertificatesDir */ - String _merlinsCertificatesDir = null; + /** Field merlinsCertificatesDir */ + private String merlinsCertificatesDir = null; - /** Field _certs */ - private List _certs = new ArrayList(); + /** Field certs */ + private List certs = new ArrayList(); - /** Field _iterator */ - Iterator _iterator = null; + /** + * @param directoryName + * @throws StorageResolverException + */ + public CertsInFilesystemDirectoryResolver(String directoryName) + throws StorageResolverException { + this.merlinsCertificatesDir = directoryName; - /** - * - * - * @param directoryName - * @throws StorageResolverException - */ - public CertsInFilesystemDirectoryResolver(String directoryName) - throws StorageResolverException { + this.readCertsFromHarddrive(); + } - this._merlinsCertificatesDir = directoryName; + /** + * Method readCertsFromHarddrive + * + * @throws StorageResolverException + */ + private void readCertsFromHarddrive() throws StorageResolverException { - this.readCertsFromHarddrive(); + File certDir = new File(this.merlinsCertificatesDir); + List al = new ArrayList(); + String[] names = certDir.list(); - this._iterator = new FilesystemIterator(this._certs); - } + for (int i = 0; i < names.length; i++) { + String currentFileName = names[i]; - /** - * Method readCertsFromHarddrive - * - * @throws StorageResolverException - */ - private void readCertsFromHarddrive() throws StorageResolverException { + if (currentFileName.endsWith(".crt")) { + al.add(names[i]); + } + } - File certDir = new File(this._merlinsCertificatesDir); - ArrayList al = new ArrayList(); - String[] names = certDir.list(); + CertificateFactory cf = null; - for (int i = 0; i < names.length; i++) { - String currentFileName = names[i]; + try { + cf = CertificateFactory.getInstance("X.509"); + } catch (CertificateException ex) { + throw new StorageResolverException("empty", ex); + } - if (currentFileName.endsWith(".crt")) { - al.add(names[i]); - } - } + if (cf == null) { + throw new StorageResolverException("empty"); + } - CertificateFactory cf = null; + for (int i = 0; i < al.size(); i++) { + String filename = certDir.getAbsolutePath() + File.separator + al.get(i); + File file = new File(filename); + boolean added = false; + String dn = null; - try { - cf = CertificateFactory.getInstance("X.509"); - } catch (CertificateException ex) { - throw new StorageResolverException("empty", ex); - } + FileInputStream fis = null; + try { + fis = new FileInputStream(file); + X509Certificate cert = + (X509Certificate) cf.generateCertificate(fis); - if (cf == null) { - throw new StorageResolverException("empty"); - } + //add to ArrayList + cert.checkValidity(); + this.certs.add(cert); - for (int i = 0; i < al.size(); i++) { - String filename = certDir.getAbsolutePath() + File.separator - + al.get(i); - File file = new File(filename); - boolean added = false; - String dn = null; + dn = cert.getSubjectX500Principal().getName(); + added = true; + } catch (FileNotFoundException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateNotYetValidException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateExpiredException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } catch (CertificateException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } finally { + try { + if (fis != null) { + fis.close(); + } + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); + } + } + } - try { - FileInputStream fis = new FileInputStream(file); - X509Certificate cert = - (X509Certificate) cf.generateCertificate(fis); - - fis.close(); - - //add to ArrayList - cert.checkValidity(); - this._certs.add(cert); - - dn = cert.getSubjectDN().getName(); - added = true; - } catch (FileNotFoundException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (IOException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateNotYetValidException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateExpiredException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } catch (CertificateException ex) { - log.log(java.util.logging.Level.FINE, "Could not add certificate from file " + filename, ex); - } - - if (added) { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (added && log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Added certificate: " + dn); - } - } - } + } + } + } - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } + /** @inheritDoc */ + public Iterator getIterator() { + return new FilesystemIterator(this.certs); + } - /** - * Class FilesystemIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - private static class FilesystemIterator implements Iterator { + /** + * Class FilesystemIterator + */ + private static class FilesystemIterator implements Iterator { - /** Field _certs */ - List _certs = null; + /** Field certs */ + List certs = null; - /** Field _i */ - int _i; + /** Field i */ + int i; - /** - * Constructor FilesystemIterator - * - * @param certs - */ - public FilesystemIterator(List certs) { - this._certs = certs; - this._i = 0; - } + /** + * Constructor FilesystemIterator + * + * @param certs + */ + public FilesystemIterator(List certs) { + this.certs = certs; + this.i = 0; + } - /** @inheritDoc */ - public boolean hasNext() { - return (this._i < this._certs.size()); - } + /** @inheritDoc */ + public boolean hasNext() { + return (this.i < this.certs.size()); + } - /** @inheritDoc */ - public X509Certificate next() { - return this._certs.get(this._i++); - } + /** @inheritDoc */ + public Certificate next() { + return this.certs.get(this.i++); + } - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + /** + * Method remove + * + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + } - /** - * Method main - * - * @param unused - * @throws Exception - */ - public static void main(String unused[]) throws Exception { + /** + * Method main + * + * @param unused + * @throws Exception + */ + public static void main(String unused[]) throws Exception { - CertsInFilesystemDirectoryResolver krs = - new CertsInFilesystemDirectoryResolver( - "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs"); + CertsInFilesystemDirectoryResolver krs = + new CertsInFilesystemDirectoryResolver( + "data/ie/baltimore/merlin-examples/merlin-xmldsig-eighteen/certs"); - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI - .getSKIBytesFromCert(cert); + for (Iterator i = krs.getIterator(); i.hasNext(); ) { + X509Certificate cert = (X509Certificate) i.next(); + byte[] ski = + com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI.getSKIBytesFromCert(cert); - System.out.println(); - System.out.println("Base64(SKI())= \"" - + Base64.encode(ski) + "\""); - System.out.println("cert.getSerialNumber()= \"" - + cert.getSerialNumber().toString() + "\""); - System.out.println("cert.getSubjectDN().getName()= \"" - + cert.getSubjectDN().getName() + "\""); - System.out.println("cert.getIssuerDN().getName()= \"" - + cert.getIssuerDN().getName() + "\""); - } - } + System.out.println(); + System.out.println("Base64(SKI())= \"" + + Base64.encode(ski) + "\""); + System.out.println("cert.getSerialNumber()= \"" + + cert.getSerialNumber().toString() + "\""); + System.out.println("cert.getSubjectX500Principal().getName()= \"" + + cert.getSubjectX500Principal().getName() + "\""); + System.out.println("cert.getIssuerX500Principal().getName()= \"" + + cert.getIssuerX500Principal().getName() + "\""); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java index 2a5662101b8..1e325d121ee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/KeyStoreResolver.java @@ -2,147 +2,152 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; import java.security.KeyStore; import java.security.KeyStoreException; -import java.security.cert.X509Certificate; +import java.security.cert.Certificate; import java.util.Enumeration; import java.util.Iterator; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; - /** * Makes the Certificates from a JAVA {@link KeyStore} object available to the * {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ */ public class KeyStoreResolver extends StorageResolverSpi { - /** Field _keyStore */ - KeyStore _keyStore = null; + /** Field keyStore */ + private KeyStore keyStore = null; - /** Field _iterator */ - Iterator _iterator = null; - - /** - * Constructor KeyStoreResolver - * - * @param keyStore is the keystore which contains the Certificates - * @throws StorageResolverException - */ - public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException { - this._keyStore = keyStore; - this._iterator = new KeyStoreIterator(this._keyStore); - } - - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } - - /** - * Class KeyStoreIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class KeyStoreIterator implements Iterator { - - /** Field _keyStore */ - KeyStore _keyStore = null; - - /** Field _aliases */ - Enumeration _aliases = null; - - /** - * Constructor KeyStoreIterator - * - * @param keyStore - * @throws StorageResolverException - */ - public KeyStoreIterator(KeyStore keyStore) - throws StorageResolverException { - - try { - this._keyStore = keyStore; - this._aliases = this._keyStore.aliases(); - } catch (KeyStoreException ex) { + /** + * Constructor KeyStoreResolver + * + * @param keyStore is the keystore which contains the Certificates + * @throws StorageResolverException + */ + public KeyStoreResolver(KeyStore keyStore) throws StorageResolverException { + this.keyStore = keyStore; + // Do a quick check on the keystore + try { + keyStore.aliases(); + } catch (KeyStoreException ex) { throw new StorageResolverException("generic.EmptyMessage", ex); - } - } + } + } - /** @inheritDoc */ - public boolean hasNext() { - return this._aliases.hasMoreElements(); - } + /** @inheritDoc */ + public Iterator getIterator() { + return new KeyStoreIterator(this.keyStore); + } - /** @inheritDoc */ - @SuppressWarnings("unchecked") - public X509Certificate next() { + /** + * Class KeyStoreIterator + */ + static class KeyStoreIterator implements Iterator { - String alias = this._aliases.nextElement(); + /** Field keyStore */ + KeyStore keyStore = null; + + /** Field aliases */ + Enumeration aliases = null; + + /** Field nextCert */ + Certificate nextCert = null; + + /** + * Constructor KeyStoreIterator + * + * @param keyStore + */ + public KeyStoreIterator(KeyStore keyStore) { + try { + this.keyStore = keyStore; + this.aliases = this.keyStore.aliases(); + } catch (KeyStoreException ex) { + // empty Enumeration + this.aliases = new Enumeration() { + public boolean hasMoreElements() { + return false; + } + public String nextElement() { + return null; + } + }; + } + } + + /** @inheritDoc */ + public boolean hasNext() { + if (nextCert == null) { + nextCert = findNextCert(); + } + + return (nextCert != null); + } + + /** @inheritDoc */ + public Certificate next() { + if (nextCert == null) { + // maybe caller did not call hasNext() + nextCert = findNextCert(); + + if (nextCert == null) { + throw new NoSuchElementException(); + } + } + + Certificate ret = nextCert; + nextCert = null; + return ret; + } + + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + + // Find the next entry that contains a certificate and return it. + // In particular, this skips over entries containing symmetric keys. + private Certificate findNextCert() { + while (this.aliases.hasMoreElements()) { + String alias = this.aliases.nextElement(); + try { + Certificate cert = this.keyStore.getCertificate(alias); + if (cert != null) { + return cert; + } + } catch (KeyStoreException ex) { + return null; + } + } - try { - return (X509Certificate)this._keyStore.getCertificate(alias); - } catch (KeyStoreException ex) { return null; - } - } + } - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + } - /** - * Method main - * - * @param unused - * @throws Exception - */ - public static void main(String unused[]) throws Exception { - - KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); - - ks.load( - new java.io.FileInputStream( - "data/com/sun/org/apache/xml/internal/security/samples/input/keystore.jks"), - "xmlsecurity".toCharArray()); - - KeyStoreResolver krs = new KeyStoreResolver(ks); - - for (Iterator i = krs.getIterator(); i.hasNext(); ) { - X509Certificate cert = i.next(); - byte[] ski = - com.sun.org.apache.xml.internal.security.keys.content.x509.XMLX509SKI - .getSKIBytesFromCert(cert); - - System.out.println(com.sun.org.apache.xml.internal.security.utils.Base64.encode(ski)); - } - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java index 3048bb123ac..e007051fb10 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/keys/storage/implementations/SingleCertificateResolver.java @@ -2,102 +2,93 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.keys.storage.implementations; +import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.Iterator; +import java.util.NoSuchElementException; import com.sun.org.apache.xml.internal.security.keys.storage.StorageResolverSpi; - /** * This {@link StorageResolverSpi} makes a single {@link X509Certificate} * available to the {@link com.sun.org.apache.xml.internal.security.keys.storage.StorageResolver}. - * - * @author $Author: mullan $ */ public class SingleCertificateResolver extends StorageResolverSpi { - /** Field _certificate */ - X509Certificate _certificate = null; + /** Field certificate */ + private X509Certificate certificate = null; - /** Field _iterator */ - Iterator _iterator = null; + /** + * @param x509cert the single {@link X509Certificate} + */ + public SingleCertificateResolver(X509Certificate x509cert) { + this.certificate = x509cert; + } - /** - * - * - * @param x509cert the single {@link X509Certificate} - */ - public SingleCertificateResolver(X509Certificate x509cert) { - this._certificate = x509cert; - this._iterator = new InternalIterator(this._certificate); - } + /** @inheritDoc */ + public Iterator getIterator() { + return new InternalIterator(this.certificate); + } - /** @inheritDoc */ - public Iterator getIterator() { - return this._iterator; - } + /** + * Class InternalIterator + */ + static class InternalIterator implements Iterator { - /** - * Class InternalIterator - * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ - */ - static class InternalIterator implements Iterator { + /** Field alreadyReturned */ + boolean alreadyReturned = false; - /** Field _alreadyReturned */ - boolean _alreadyReturned = false; + /** Field certificate */ + X509Certificate certificate = null; - /** Field _certificate */ - X509Certificate _certificate = null; + /** + * Constructor InternalIterator + * + * @param x509cert + */ + public InternalIterator(X509Certificate x509cert) { + this.certificate = x509cert; + } - /** - * Constructor InternalIterator - * - * @param x509cert - */ - public InternalIterator(X509Certificate x509cert) { - this._certificate = x509cert; - } + /** @inheritDoc */ + public boolean hasNext() { + return !this.alreadyReturned; + } - /** @inheritDoc */ - public boolean hasNext() { - return (!this._alreadyReturned); - } + /** @inheritDoc */ + public Certificate next() { + if (this.alreadyReturned) { + throw new NoSuchElementException(); + } + this.alreadyReturned = true; + return this.certificate; + } - /** @inheritDoc */ - public X509Certificate next() { - - this._alreadyReturned = true; - - return this._certificate; - } - - /** - * Method remove - * - */ - public void remove() { - throw new UnsupportedOperationException( - "Can't remove keys from KeyStore"); - } - } + /** + * Method remove + */ + public void remove() { + throw new UnsupportedOperationException("Can't remove keys from KeyStore"); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml index aea1595741b..55c396c012e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/config.xml @@ -52,9 +52,6 @@ - - @@ -78,6 +75,12 @@ JAVACLASS="com.sun.org.apache.xml.internal.security.algorithms.implementations.SignatureBaseRSA$SignatureRSASHA512" /> + + + @@ -97,7 +100,7 @@ Description="MD5 message digest from RFC 1321" AlgorithmClass="MessageDigest" RequirementLevel="NOT RECOMMENDED" - SpecificationURL="http://www.ietf.org/internet-drafts/draft-eastlake-xmldsig-uri-02.txt" + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" JCEName="MD5"/> + SpecificationURL="http://www.ietf.org/rfc/rfc4051.txt" + JCEName="SHA1withECDSA"/> + + + + + + @@ -260,7 +284,31 @@ KeyLength="256" RequiredKey="AES" JCEName="AES/CBC/ISO10126Padding"/> + + + + + + + JCEName="RSA/ECB/OAEPPadding"/> + + - - - - + @@ -330,32 +378,8 @@ + DESCRIPTION="A simple resolver for requests of XPointer fragments" /> - - - - - - - - - - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties deleted file mode 100644 index e67ae2c79ef..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/log4j.properties +++ /dev/null @@ -1,36 +0,0 @@ -# ------------------------------------------------------------------------ -# -# Logging Configuration -# -# ------------------------------------------------------------------------ -# -log4j.rootLogger=DEBUG, LOGTXT - -######################################################################## -# -# Logging based on packages -# -######################################################################## -log4j.logger.com.sun.org.apache.xml.internal.security=DEBUG, LOGTXT -log4j.logger.com.sun.org.apache.xml.internal.security.test.AllTests=DEBUG, LOGTXT - -######################################################################## -# -# Logfile definitions -# -######################################################################## -#Console Log -log4j.appender.Console=org.apache.log4j.ConsoleAppender -log4j.appender.Console.Threshold=DEBUG -log4j.appender.Console.layout=org.apache.log4j.PatternLayout -log4j.appender.Console.layout.ConversionPattern=%-5p %C{1}:%L - %m\n -log4j.appender.Console.Target=System.err - -#LOGTXT Log -log4j.appender.LOGTXT=org.apache.log4j.FileAppender -log4j.appender.LOGTXT.File=log.txt -log4j.appender.LOGTXT.Append=true -log4j.appender.LOGTXT.Threshold=DEBUG -log4j.appender.LOGTXT.layout=org.apache.log4j.PatternLayout -log4j.appender.LOGTXT.layout.ConversionPattern=%-5p %C{1}:%L - %m\n - diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties index c285aa0f87d..746361d2923 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_de.properties @@ -5,6 +5,7 @@ algorithm.extendsWrongClass = Kann URI {0} nicht f algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. +algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0} algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms algorithms.NoSuchAlgorithm = Der Algorithmus {0} ist nicht verfügbar. Original Nachricht war: {1} algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm @@ -88,8 +89,13 @@ prefix.AlreadyAssigned = Sie binden den Prefix {0} an den Namespace {1} aber er signature.Canonicalizer.UnknownCanonicalizer = Unbekannter Canonicalizer. Kein Handler installiert für URI {0} signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first +signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled +signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled signature.signaturePropertyHasNoTarget = Das Target Attribut der SignatureProperty muss gesetzt sein +signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation +signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation signature.Transform.ErrorDuringTransform = Während der Transformation {0} trat eine {1} auf. +signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled signature.Transform.NotYetImplemented = Transform {0} noch nicht implementiert signature.Transform.NullPointerTransform = Null pointer als URI übergeben. Programmierfehler? signature.Transform.UnknownTransform = Unbekannte Transformation. Kein Handler installiert für URI {0} @@ -103,6 +109,7 @@ signature.Verification.InvalidDigestOrReference = Ung signature.Verification.keyStore = Öffnen des KeyStore fehlgeschlagen signature.Verification.MissingID = Cannot resolve element with ID {0} signature.Verification.MissingResources = Kann die externe Resource {0} nicht auflösen +signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected signature.Verification.NoSignatureElement = Input Dokument enthält kein {0} Element mit dem Namespace {1} signature.Verification.Reference.NoInput = Die Reference für den URI {0} hat keinen XMLSignatureInput erhalten. signature.Verification.SignatureError = Signatur Fehler diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties index f15104e94b5..a01124ee85f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/resource/xmlsecurity_en.properties @@ -1,126 +1,131 @@ -algorithm.alreadyRegistered = URI {0} already assigned to class {1} -algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH -algorithm.ClassDoesNotExist = Class {0} does not exist -algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} -algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. -algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. -algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. -algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms -algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} -algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm -algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} -algorithms.operationOnlyVerification = A public key can only used for verification of a signature. -algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. -attributeValueIllegal = The attribute {0} has value {1} but must be {2} -c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} -c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} -c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} -c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} -c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" -c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} -c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} -c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} -c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation -c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) -certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} -certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString -certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier -defaultNamespaceCannotBeSetHere = Default namespace cannot be set here -ElementProxy.nullElement = Cannot create an ElementProxy from a null argument -empty = {0} -encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} -encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams -encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt -encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap -encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit -encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. -encryption.RSAOAEP.dataHashWrong = data hash wrong -encryption.RSAOAEP.dataStartWrong = data wrong start {0} -encryption.RSAOAEP.dataTooShort = data too short -encryption.RSAPKCS15.blockTruncated = block truncated -encryption.RSAPKCS15.noDataInBlock = no data in block -encryption.RSAPKCS15.unknownBlockType = unknown block type -encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers -endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at how to solve this problem. -errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. -errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. -errorMessages.IOException = Other file I/O and similar exceptions. -errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. -errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. -errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} -errorMessages.NotYetImplementedException = Functionality not yet there. -errorMessages.XMLSignatureException = Verification failed for some other reason. -decoding.divisible.four = It should be divisible by four -decoding.general = Error while decoding -FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. -FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} -FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} -FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} -generic.dontHaveConstructionElement = I do not have a construction Element -generic.EmptyMessage = {0} -generic.NotYetImplemented = {0} Not YET implemented ;-(( -java.security.InvalidKeyException = Invalid key -java.security.NoSuchProviderException = Unknown or unsupported provider -java.security.UnknownKeyType = Unknown or unsupported key type {0} -KeyInfo.needKeyResolver = More than one keyResovler have to be registered -KeyInfo.nokey = Cannot get key from {0} -KeyInfo.noKey = Cannot get the public key -KeyInfo.wrongNumberOfObject = Need {0} keyObjects -KeyInfo.wrongUse = This object was made for getting {0} -keyResolver.alreadyRegistered = {1} class has already been registered for {0} -KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} -KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} -KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} -KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} -KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} -KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} -KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} -KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} -KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} -KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} -KeyStore.alreadyRegistered = {0} Class has already been registered for {1} -KeyStore.register = {1} type class register error in class {0} -KeyStore.registerStore.register = Registeration error for type {0} -KeyValue.IllegalArgument = Cannot create a {0} from {1} -namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} -notYetInitialized = The module {0} is not yet initialized -prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} -signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} -signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature -signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first -signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled -signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled -signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set -signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform -signature.Transform.NotYetImplemented = Transform {0} not yet implemented -signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? -signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} -signature.Transform.node = Current Node: {0} -signature.Transform.nodeAndType = Current Node: {0}, type: {1} -signature.Util.BignumNonPositive = bigInteger.signum() must be positive -signature.Util.NonTextNode = Not a text node -signature.Util.TooManyChilds = Too many childs of Type {0} in {1} -signature.Verification.certificateError = Certificate error -signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References -signature.Verification.internalError = Internal error -signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} -signature.Verification.keyStore = KeyStore error -signature.Verification.MissingID = Cannot resolve element with ID {0} -signature.Verification.MissingResources = Cannot resolve external resource {0} -signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected -signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} -signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput -signature.Verification.SignatureError = Signature error -signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} -signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it -signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference -transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. -transform.init.NotInitialized = -transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization -utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 -Base64Decoding = Error while decoding -utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} -xml.WrongContent = Cannot find {0} in {1} -xml.WrongElement = Cannot create a {0} from a {1} element -xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node -xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} +algorithm.alreadyRegistered = URI {0} already assigned to class {1} +algorithm.classDoesNotExist = Cannot register URI {0} to class {1} because this class does not exist in CLASSPATH +algorithm.ClassDoesNotExist = Class {0} does not exist +algorithm.extendsWrongClass = Cannot register URI {0} to class {1} because it does not extend {2} +algorithms.CannotUseAlgorithmParameterSpecOnDSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating DSA signatures. +algorithms.CannotUseAlgorithmParameterSpecOnRSA = Sorry, but you cannot use a AlgorithmParameterSpec object for creating RSA signatures. +algorithms.CannotUseSecureRandomOnMAC = Sorry, but you cannot use a SecureRandom object for creating MACs. +algorithms.HMACOutputLengthMin = HMACOutputLength must not be less than {0} +algorithms.HMACOutputLengthOnlyForHMAC = A HMACOutputLength can only be specified for HMAC integrity algorithms +algorithms.NoSuchAlgorithm = The requested algorithm {0} does not exist. Original Message was: {1} +algorithms.NoSuchMap = The algorithm URI "{0}" could not be mapped to a JCE algorithm +algorithms.NoSuchProvider = The specified Provider {0} does not exist. Original Message was: {1} +algorithms.operationOnlyVerification = A public key can only used for verification of a signature. +algorithms.WrongKeyForThisOperation = Sorry, you supplied the wrong key type for this operation! You supplied a {0} but a {1} is needed. +attributeValueIllegal = The attribute {0} has value {1} but must be {2} +c14n.Canonicalizer.Exception = Exception during Canonicalization: Original Message was {0} +c14n.Canonicalizer.IllegalNode = Illegal node type {0}, node name was {1} +c14n.Canonicalizer.NoSuchCanonicalizer = No canonicalizer found with URI {0} +c14n.Canonicalizer.ParserConfigurationException = ParserConfigurationException during Canonicalization: Original Message was {0} +c14n.Canonicalizer.RelativeNamespace = Element {0} has a relative namespace: {1}="{2}" +c14n.Canonicalizer.SAXException = SAXException during Canonicalization: Original Message was {0} +c14n.Canonicalizer.TraversalNotSupported = This DOM document does not support Traversal {0} +c14n.Canonicalizer.UnsupportedEncoding = Unsupported encoding {0} +c14n.Canonicalizer.UnsupportedOperation = This canonicalizer does not support this operation +c14n.XMLUtils.circumventBug2650forgotten = The tree has not been prepared for canonicalization using XMLUtils#circumventBug2650(Document) +certificate.noSki.lowVersion = Certificate cannot contain a SubjectKeyIdentifier because it is only X509v{0} +certificate.noSki.notOctetString = Certificates SubjectKeyIdentifier is not a OctetString +certificate.noSki.null = Certificate does not contain a SubjectKeyIdentifier +defaultNamespaceCannotBeSetHere = Default namespace cannot be set here +ElementProxy.nullElement = Cannot create an ElementProxy from a null argument +empty = {0} +encryption.algorithmCannotBeUsedForEncryptedData = encryption.algorithmCannotBeUsedForEncryptedData {0} +encryption.algorithmCannotEatInitParams = encryption.algorithmCannotEatInitParams +encryption.algorithmCannotEncryptDecrypt = encryption.algorithmCannotEncryptDecrypt +encryption.algorithmCannotWrapUnWrap = encryption.algorithmCannotWrapUnWrap +encryption.ExplicitKeySizeMismatch = The xenc:KeySize element requests a key size of {0} bit but the algorithm implements {1} bit +encryption.nonceLongerThanDecryptedPlaintext = The given nonce is longer than the available plaintext. I Cannot strip away this. +encryption.RSAOAEP.dataHashWrong = data hash wrong +encryption.RSAOAEP.dataStartWrong = data wrong start {0} +encryption.RSAOAEP.dataTooShort = data too short +encryption.RSAPKCS15.blockTruncated = block truncated +encryption.RSAPKCS15.noDataInBlock = no data in block +encryption.RSAPKCS15.unknownBlockType = unknown block type +encryption.nokey = No Key Encryption Key loaded and cannot determine using key resolvers +endorsed.jdk1.4.0 = Since it seems that nobody reads our installation notes, we must do it in the exception messages. Hope you read them. You did NOT use the endorsed mechanism from JDK 1.4 properly; look at how to solve this problem. +errorMessages.InvalidDigestValueException = INVALID signature -- check reference resolution. +errorMessages.InvalidSignatureValueException = INVALID signature -- core validation failed. +errorMessages.IOException = Other file I/O and similar exceptions. +errorMessages.MissingKeyFailureException = Cannot verify because of missing public key. Provide it via addResource and try again. +errorMessages.MissingResourceFailureException = Cannot verify because of unresolved references. Provide it via addResource and try again. +errorMessages.NoSuchAlgorithmException = Unknown Algorithm {0} +errorMessages.NotYetImplementedException = Functionality not yet there. +errorMessages.XMLSignatureException = Verification failed for some other reason. +decoding.divisible.four = It should be divisible by four +decoding.general = Error while decoding +FileKeyStorageImpl.addToDefaultFromRemoteNotImplemented = Method addToDefaultFromRemote() not yet implemented. +FileKeyStorageImpl.NoCert.Context = Not found such a X509Certificate including context {0} +FileKeyStorageImpl.NoCert.IssNameSerNo = Not found such a X509Certificate with IssuerName {0} and serial number {1} +FileKeyStorageImpl.NoCert.SubjName = Not found such a X509Certificate including SubjectName {0} +generic.dontHaveConstructionElement = I do not have a construction Element +generic.EmptyMessage = {0} +generic.NotYetImplemented = {0} Not YET implemented ;-(( +java.security.InvalidKeyException = Invalid key +java.security.NoSuchProviderException = Unknown or unsupported provider +java.security.UnknownKeyType = Unknown or unsupported key type {0} +KeyInfo.needKeyResolver = More than one keyResovler have to be registered +KeyInfo.nokey = Cannot get key from {0} +KeyInfo.noKey = Cannot get the public key +KeyInfo.wrongNumberOfObject = Need {0} keyObjects +KeyInfo.wrongUse = This object was made for getting {0} +keyResolver.alreadyRegistered = {1} class has already been registered for {0} +KeyResolver.needStorageResolver = Need a StorageResolver to retrieve a Certificate from a {0} +KeyResoverSpiImpl.cannotGetCert = Cannot get the Certificate that include or in {1} in implement class {0} +KeyResoverSpiImpl.elementGeneration = Cannot make {1} element in implement class {0} +KeyResoverSpiImpl.getPoublicKey = Cannot get the public key from implement class {0} +KeyResoverSpiImpl.InvalidElement = Cannot set (2) Element in implement class {0} +KeyResoverSpiImpl.keyStore = KeyStorage error in implement class {0} +KeyResoverSpiImpl.need.Element = {1} type of Element is needed in implement class {0} +KeyResoverSpiImpl.wrongCRLElement = Cannot make CRL from {1} in implement class {0} +KeyResoverSpiImpl.wrongKeyObject = Need {1} type of KeyObject for generation Element in implement class{0} +KeyResoverSpiImpl.wrongNumberOfObject = Need {1} keyObject in implement class {0} +KeyStore.alreadyRegistered = {0} Class has already been registered for {1} +KeyStore.register = {1} type class register error in class {0} +KeyStore.registerStore.register = Registeration error for type {0} +KeyValue.IllegalArgument = Cannot create a {0} from {1} +namespacePrefixAlreadyUsedByOtherURI = Namespace prefix {0} already used by other URI {1} +notYetInitialized = The module {0} is not yet initialized +prefix.AlreadyAssigned = You want to assign {0} as prefix for namespace {1} but it is already assigned for {2} +signature.Canonicalizer.UnknownCanonicalizer = Unknown canonicalizer. No handler installed for URI {0} +signature.DSA.invalidFormat = Invalid ASN.1 encoding of the DSA signature +signature.Generation.signBeforeGetValue = You have to XMLSignature.sign(java.security.PrivateKey) first +signature.Reference.ForbiddenResolver = It is forbidden to access resolver {0} when secure validation is enabled +signature.signatureAlgorithm = It is forbidden to use algorithm {0} when secure validation is enabled +signature.signaturePropertyHasNoTarget = The Target attribute of the SignatureProperty must be set +signature.tooManyReferences = {0} references are contained in the Manifest, maximum {1} are allowed with secure validation +signature.tooManyTransforms = {0} transforms are contained in the Reference, maximum {1} are allowed with secure validation +signature.Transform.ErrorDuringTransform = A {1} was thrown during the {0} transform +signature.Transform.ForbiddenTransform = Transform {0} is forbidden when secure validation is enabled +signature.Transform.NotYetImplemented = Transform {0} not yet implemented +signature.Transform.NullPointerTransform = Null pointer as URI. Programming bug? +signature.Transform.UnknownTransform = Unknown transformation. No handler installed for URI {0} +signature.Transform.node = Current Node: {0} +signature.Transform.nodeAndType = Current Node: {0}, type: {1} +signature.Util.BignumNonPositive = bigInteger.signum() must be positive +signature.Util.NonTextNode = Not a text node +signature.Util.TooManyChilds = Too many childs of Type {0} in {1} +signature.Verification.certificateError = Certificate error +signature.Verification.IndexOutOfBounds = Index {0} illegal. We only have {1} References +signature.Verification.internalError = Internal error +signature.Verification.InvalidDigestOrReference = Invalid digest of reference {0} +signature.Verification.keyStore = KeyStore error +signature.Verification.MissingID = Cannot resolve element with ID {0} +signature.Verification.MissingResources = Cannot resolve external resource {0} +signature.Verification.MultipleIDs = Multiple Elements with the same ID {0} were detected +signature.Verification.NoSignatureElement = Input document contains no {0} Element in namespace {1} +signature.Verification.Reference.NoInput = The Reference for URI {0} has no XMLSignatureInput +signature.Verification.SignatureError = Signature error +signature.XMLSignatureInput.MissingConstuctor = Cannot construct a XMLSignatureInput from class {0} +signature.XMLSignatureInput.SerializeDOM = Input initialized with DOM Element. Use Canonicalization to serialize it +signature.XMLSignatureInput.nodesetReference = Unable to convert to nodeset the reference +transform.Init.IllegalContextArgument = Invalid context argument of class {0}. Must be String, org.w3c.dom.NodeList or java.io.InputStream. +transform.init.NotInitialized = +transform.init.wrongURI = Initialized with wrong URI. How could this happen? We implement {0} but {1} was used during initialization +transform.envelopedSignatureTransformNotInSignatureElement = Enveloped Transform cannot find Signature element +utils.Base64.IllegalBitlength = Illegal byte length; Data to be decoded must be a multiple of 4 +Base64Decoding = Error while decoding +utils.resolver.noClass = Could not find a resolver for URI {0} and Base {1} +xml.WrongContent = Cannot find {0} in {1} +xml.WrongElement = Cannot create a {0} from a {1} element +xpath.funcHere.documentsDiffer = The XPath is not in the same document as the context node +xpath.funcHere.noXPathContext = Try to evaluate an XPath which uses the here() function but XPath is not inside an ds:XPath Element. XPath was : {0} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java index 57da56c5cb2..7801315c02d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidDigestValueException.java @@ -2,85 +2,85 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - /** - * Raised when the computed hash value doesn't match the given DigestValue. Additional human readable info is passed to the constructor -- this being the benefit of raising an exception or returning a value. + * Raised when the computed hash value doesn't match the given DigestValue. + * Additional human readable info is passed to the constructor -- this being the benefit + * of raising an exception or returning a value. * * @author Christian Geuer-Pollmann */ public class InvalidDigestValueException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidDigestValueException - * - */ - public InvalidDigestValueException() { - super(); - } + /** + * Constructor InvalidDigestValueException + * + */ + public InvalidDigestValueException() { + super(); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - */ - public InvalidDigestValueException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + */ + public InvalidDigestValueException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param exArgs - */ - public InvalidDigestValueException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param exArgs + */ + public InvalidDigestValueException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param _originalException - */ - public InvalidDigestValueException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param originalException + */ + public InvalidDigestValueException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidDigestValueException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidDigestValueException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidDigestValueException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidDigestValueException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java index 397c1293492..a216ebb4d17 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/InvalidSignatureValueException.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - /** * Raised if testing the signature value over DigestValue fails because of invalid signature. * @@ -30,58 +30,56 @@ package com.sun.org.apache.xml.internal.security.signature; */ public class InvalidSignatureValueException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidSignatureValueException - * - */ - public InvalidSignatureValueException() { - super(); - } + /** + * Constructor InvalidSignatureValueException + * + */ + public InvalidSignatureValueException() { + super(); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - */ - public InvalidSignatureValueException(String _msgID) { - super(_msgID); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + */ + public InvalidSignatureValueException(String msgID) { + super(msgID); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param exArgs - */ - public InvalidSignatureValueException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param exArgs + */ + public InvalidSignatureValueException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param _originalException - */ - public InvalidSignatureValueException(String _msgID, - Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param originalException + */ + public InvalidSignatureValueException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor InvalidSignatureValueException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public InvalidSignatureValueException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor InvalidSignatureValueException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public InvalidSignatureValueException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java index 351dee5edaf..01d76effdff 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Manifest.java @@ -2,33 +2,33 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; -import java.util.Set; import java.util.Map; +import java.util.Set; import javax.xml.parsers.ParserConfigurationException; @@ -38,7 +38,6 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.I18n; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver; @@ -50,523 +49,561 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.xml.sax.SAXException; - - /** * Handles <ds:Manifest> elements. *

This element holds the Reference elements

- * @author $author: $ */ public class Manifest extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** + * The maximum number of references per Manifest, if secure validation is enabled. + */ + public static final int MAXIMUM_REFERENCE_COUNT = 30; + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(Manifest.class.getName()); - /** Field _references */ - List _references; - Element[] _referencesEl; + /** Field references */ + private List references; + private Element[] referencesEl; - /** Field verificationResults[] */ - private boolean verificationResults[] = null; + /** Field verificationResults[] */ + private boolean verificationResults[] = null; - /** Field _resolverProperties */ - Map _resolverProperties = null; + /** Field resolverProperties */ + private Map resolverProperties = null; - /** Field _perManifestResolvers */ - List _perManifestResolvers = null; + /** Field perManifestResolvers */ + private List perManifestResolvers = null; - /** - * Consturts {@link Manifest} - * - * @param doc the {@link Document} in which XMLsignature is placed - */ - public Manifest(Document doc) { + private boolean secureValidation; - super(doc); + /** + * Constructs {@link Manifest} + * + * @param doc the {@link Document} in which XMLsignature is placed + */ + public Manifest(Document doc) { + super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); - this._references = new ArrayList(); - } + this.references = new ArrayList(); + } - /** - * Constructor Manifest - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public Manifest(Element element, String BaseURI) - throws XMLSecurityException { + /** + * Constructor Manifest + * + * @param element + * @param baseURI + * @throws XMLSecurityException + */ + public Manifest(Element element, String baseURI) throws XMLSecurityException { + this(element, baseURI, false); - super(element, BaseURI); + } + /** + * Constructor Manifest + * + * @param element + * @param baseURI + * @param secureValidation + * @throws XMLSecurityException + */ + public Manifest( + Element element, String baseURI, boolean secureValidation + ) throws XMLSecurityException { + super(element, baseURI); - Attr attr = element.getAttributeNodeNS(null, "Id"); - if (attr != null) { - element.setIdAttributeNode(attr, true); - } - - // check out Reference children - this._referencesEl = XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(), - Constants._TAG_REFERENCE); - int le = this._referencesEl.length; - { - if (le == 0) { + Attr attr = element.getAttributeNodeNS(null, "Id"); + if (attr != null) { + element.setIdAttributeNode(attr, true); + } + this.secureValidation = secureValidation; + // check out Reference children + this.referencesEl = + XMLUtils.selectDsNodes( + this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE + ); + int le = this.referencesEl.length; + if (le == 0) { // At least one Reference must be present. Bad. - Object exArgs[] = { Constants._TAG_REFERENCE, - Constants._TAG_MANIFEST }; + Object exArgs[] = { Constants._TAG_REFERENCE, Constants._TAG_MANIFEST }; throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, I18n.translate("xml.WrongContent", exArgs)); - } - } + } - // create Vector - this._references = new ArrayList(le); + if (secureValidation && le > MAXIMUM_REFERENCE_COUNT) { + Object exArgs[] = { le, MAXIMUM_REFERENCE_COUNT }; - for (int i = 0; i < le; i++) { - Element refElem = this._referencesEl[i]; - Attr refAttr = refElem.getAttributeNodeNS(null, "Id"); - if (refAttr != null) { - refElem.setIdAttributeNode(refAttr, true); - } - this._references.add(null); - } - } + throw new XMLSecurityException("signature.tooManyReferences", exArgs); + } - /** - * This addDocument method is used to add a new resource to the - * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built - * from the supplied values. - * - * @param BaseURI the URI of the resource where the XML instance was stored - * @param referenceURI URI attribute in Reference for specifing where data is - * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered list of transformations to be performed. - * @param digestURI The digest algorthim URI to be used. - * @param ReferenceId - * @param ReferenceType - * @throws XMLSignatureException - */ - public void addDocument( - String BaseURI, String referenceURI, Transforms transforms, String digestURI, String ReferenceId, String ReferenceType) - throws XMLSignatureException { + // create List + this.references = new ArrayList(le); - // the this._doc is handed implicitly by the this.getOwnerDocument() - Reference ref = new Reference(this._doc, BaseURI, referenceURI, this, - transforms, digestURI); + for (int i = 0; i < le; i++) { + Element refElem = referencesEl[i]; + Attr refAttr = refElem.getAttributeNodeNS(null, "Id"); + if (refAttr != null) { + refElem.setIdAttributeNode(refAttr, true); + } + this.references.add(null); + } + } - if (ReferenceId != null) { - ref.setId(ReferenceId); - } + /** + * This addDocument method is used to add a new resource to the + * signed info. A {@link com.sun.org.apache.xml.internal.security.signature.Reference} is built + * from the supplied values. + * + * @param baseURI the URI of the resource where the XML instance was stored + * @param referenceURI URI attribute in Reference for specifying + * where data is + * @param transforms com.sun.org.apache.xml.internal.security.signature.Transforms object with an ordered + * list of transformations to be performed. + * @param digestURI The digest algorithm URI to be used. + * @param referenceId + * @param referenceType + * @throws XMLSignatureException + */ + public void addDocument( + String baseURI, String referenceURI, Transforms transforms, + String digestURI, String referenceId, String referenceType + ) throws XMLSignatureException { + // the this.doc is handed implicitly by the this.getOwnerDocument() + Reference ref = + new Reference(this.doc, baseURI, referenceURI, this, transforms, digestURI); - if (ReferenceType != null) { - ref.setType(ReferenceType); - } + if (referenceId != null) { + ref.setId(referenceId); + } - // add Reference object to our cache vector - this._references.add(ref); + if (referenceType != null) { + ref.setType(referenceType); + } - // add the Element of the Reference object to the Manifest/SignedInfo - this._constructionElement.appendChild(ref.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - } + // add Reference object to our cache vector + this.references.add(ref); - /** - * The calculation of the DigestValues in the References must be after the - * References are already added to the document and during the signing - * process. This ensures that all neccesary data is in place. - * - * @throws ReferenceNotInitializedException - * @throws XMLSignatureException - */ - public void generateDigestValues() - throws XMLSignatureException, ReferenceNotInitializedException { - - for (int i = 0; i < this.getLength(); i++) { + // add the Element of the Reference object to the Manifest/SignedInfo + this.constructionElement.appendChild(ref.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + } + /** + * The calculation of the DigestValues in the References must be after the + * References are already added to the document and during the signing + * process. This ensures that all necessary data is in place. + * + * @throws ReferenceNotInitializedException + * @throws XMLSignatureException + */ + public void generateDigestValues() + throws XMLSignatureException, ReferenceNotInitializedException { + for (int i = 0; i < this.getLength(); i++) { // update the cached Reference object, the Element content is automatically updated - Reference currentRef = this._references.get(i); - + Reference currentRef = this.references.get(i); currentRef.generateDigestValue(); - } - } + } + } - /** - * Return the nonnegative number of added references. - * - * @return the number of references - */ - public int getLength() { - return this._references.size(); - } - - /** - * Return the ith reference. Valid i - * values are 0 to {link@ getSize}-1. - * - * @param i Index of the requested {@link Reference} - * @return the ith reference - * @throws XMLSecurityException - */ - public Reference item(int i) throws XMLSecurityException { - - if (this._references.get(i) == null) { + /** + * Return the nonnegative number of added references. + * + * @return the number of references + */ + public int getLength() { + return this.references.size(); + } + /** + * Return the ith reference. Valid i + * values are 0 to {link@ getSize}-1. + * + * @param i Index of the requested {@link Reference} + * @return the ith reference + * @throws XMLSecurityException + */ + public Reference item(int i) throws XMLSecurityException { + if (this.references.get(i) == null) { // not yet constructed, so _we_ have to - Reference ref = new Reference(_referencesEl[i], this._baseURI, this); + Reference ref = + new Reference(referencesEl[i], this.baseURI, this, secureValidation); - this._references.set(i, ref); - } + this.references.set(i, ref); + } - return this._references.get(i); + return this.references.get(i); + } - } + /** + * Sets the Id attribute + * + * @param Id the Id attribute in ds:Manifest + */ + public void setId(String Id) { + if (Id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } - /** - * Sets the Id attribute - * - * @param Id the Id attribute in ds:Manifest - */ - public void setId(String Id) { + /** + * Returns the Id attribute + * + * @return the Id attribute in ds:Manifest + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } + /** + * Used to do a reference + * validation of all enclosed references using the {@link Reference#verify} method. + * + *

This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. The results of the individual reference + * validations are available by using the {@link #getVerificationResult(int)} method + * + * @return true if all References verify, false if one or more do not verify. + * @throws MissingResourceFailureException if a {@link Reference} does not verify + * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} + * because of an uninitialized {@link XMLSignatureInput} + * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify + * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify() + * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException + * @throws XMLSecurityException + */ + public boolean verifyReferences() + throws MissingResourceFailureException, XMLSecurityException { + return this.verifyReferences(false); + } - /** - * Returns the Id attribute - * - * @return the Id attribute in ds:Manifest - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } + /** + * Used to do a reference + * validation of all enclosed references using the {@link Reference#verify} method. + * + *

This step loops through all {@link Reference}s and does verify the hash + * values. If one or more verifications fail, the method returns + * false. If all verifications are successful, + * it returns true. The results of the individual reference + * validations are available by using the {@link #getVerificationResult(int)} method + * + * @param followManifests + * @return true if all References verify, false if one or more do not verify. + * @throws MissingResourceFailureException if a {@link Reference} does not verify + * (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} + * because of an uninitialized {@link XMLSignatureInput} + * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify + * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean) + * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException + * @throws XMLSecurityException + */ + public boolean verifyReferences(boolean followManifests) + throws MissingResourceFailureException, XMLSecurityException { + if (referencesEl == null) { + this.referencesEl = + XMLUtils.selectDsNodes( + this.constructionElement.getFirstChild(), Constants._TAG_REFERENCE + ); + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "verify " + referencesEl.length + " References"); + log.log(java.util.logging.Level.FINE, "I am " + (followManifests + ? "" : "not") + " requested to follow nested Manifests"); + } + if (referencesEl.length == 0) { + throw new XMLSecurityException("empty"); + } + if (secureValidation && referencesEl.length > MAXIMUM_REFERENCE_COUNT) { + Object exArgs[] = { referencesEl.length, MAXIMUM_REFERENCE_COUNT }; - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

This step loops through all {@link Reference}s and does verify the hash - * values. If one or more verifications fail, the method returns - * false. If all verifications are successful, - * it returns true. The results of the individual reference - * validations are available by using the {@link #getVerificationResult(int)} method - * - * @return true if all References verify, false if one or more do not verify. - * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput} - * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify - * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify() - * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException - * @throws XMLSecurityException - */ - public boolean verifyReferences() - throws MissingResourceFailureException, XMLSecurityException { - return this.verifyReferences(false); - } + throw new XMLSecurityException("signature.tooManyReferences", exArgs); + } - /** - * Used to do a reference - * validation of all enclosed references using the {@link Reference#verify} method. - * - *

This step loops through all {@link Reference}s and does verify the hash - * values. If one or more verifications fail, the method returns - * false. If all verifications are successful, - * it returns true. The results of the individual reference - * validations are available by using the {@link #getVerificationResult(int)} method - * - * @param followManifests - * @return true if all References verify, false if one or more do not verify. - * @throws MissingResourceFailureException if a {@link Reference} does not verify (throws a {@link com.sun.org.apache.xml.internal.security.signature.ReferenceNotInitializedException} because of an uninitialized {@link XMLSignatureInput} - * @see com.sun.org.apache.xml.internal.security.signature.Reference#verify - * @see com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify(boolean) - * @see com.sun.org.apache.xml.internal.security.signature.MissingResourceFailureException - * @throws XMLSecurityException - */ - public boolean verifyReferences(boolean followManifests) - throws MissingResourceFailureException, XMLSecurityException { - if (_referencesEl==null) { - this._referencesEl = - XMLUtils.selectDsNodes(this._constructionElement.getFirstChild(), - Constants._TAG_REFERENCE); - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "verify " +_referencesEl.length + " References"); - log.log(java.util.logging.Level.FINE, "I am " + (followManifests - ? "" - : "not") + " requested to follow nested Manifests"); - } - boolean verify = true; + this.verificationResults = new boolean[referencesEl.length]; + boolean verify = true; + for (int i = 0; i < this.referencesEl.length; i++) { + Reference currentRef = + new Reference(referencesEl[i], this.baseURI, this, secureValidation); - if (_referencesEl.length==0) { - throw new XMLSecurityException("empty"); - } + this.references.set(i, currentRef); - this.verificationResults = - new boolean[_referencesEl.length]; + // if only one item does not verify, the whole verification fails + try { + boolean currentRefVerified = currentRef.verify(); - for (int i = - 0; i < this._referencesEl.length; i++) { - Reference currentRef = - new Reference(_referencesEl[i], this._baseURI, this); + this.setVerificationResult(i, currentRefVerified); - this._references.set(i, currentRef); + if (!currentRefVerified) { + verify = false; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType()); + } - /* if only one item does not verify, the whole verification fails */ - try { - boolean currentRefVerified = currentRef.verify(); + // was verification successful till now and do we want to verify the Manifest? + if (verify && followManifests && currentRef.typeIsReferenceToManifest()) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest"); + } - this.setVerificationResult(i, currentRefVerified); + try { + XMLSignatureInput signedManifestNodes = + currentRef.dereferenceURIandPerformTransforms(null); + Set nl = signedManifestNodes.getNodeSet(); + Manifest referencedManifest = null; + Iterator nlIterator = nl.iterator(); - if (!currentRefVerified) { - verify = false; - } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "The Reference has Type " + currentRef.getType()); + findManifest: while (nlIterator.hasNext()) { + Node n = nlIterator.next(); - // was verification successful till now and do we want to verify the Manifest? - if (verify && followManifests - && currentRef.typeIsReferenceToManifest()) { - log.log(java.util.logging.Level.FINE, "We have to follow a nested Manifest"); - - try { - XMLSignatureInput signedManifestNodes = - currentRef.dereferenceURIandPerformTransforms(null); - Set nl = signedManifestNodes.getNodeSet(); - Manifest referencedManifest = null; - Iterator nlIterator = nl.iterator(); - - findManifest: while (nlIterator.hasNext()) { - Node n = nlIterator.next(); - - if ((n.getNodeType() == Node.ELEMENT_NODE) && ((Element) n) - .getNamespaceURI() - .equals(Constants.SignatureSpecNS) && ((Element) n) - .getLocalName().equals(Constants._TAG_MANIFEST)) { - try { - referencedManifest = - new Manifest((Element) n, - signedManifestNodes.getSourceURI()); - - break findManifest; - } catch (XMLSecurityException ex) { - - // Hm, seems not to be a ds:Manifest + if ((n.getNodeType() == Node.ELEMENT_NODE) + && ((Element) n).getNamespaceURI().equals(Constants.SignatureSpecNS) + && ((Element) n).getLocalName().equals(Constants._TAG_MANIFEST) + ) { + try { + referencedManifest = + new Manifest( + (Element)n, signedManifestNodes.getSourceURI(), secureValidation + ); + break findManifest; + } catch (XMLSecurityException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // Hm, seems not to be a ds:Manifest + } + } } - } - } - if (referencedManifest == null) { + if (referencedManifest == null) { + // The Reference stated that it points to a ds:Manifest + // but we did not find a ds:Manifest in the signed area + throw new MissingResourceFailureException("empty", currentRef); + } - // The Reference stated that it points to a ds:Manifest - // but we did not find a ds:Manifest in the signed area - throw new MissingResourceFailureException("empty", - currentRef); - } + referencedManifest.perManifestResolvers = this.perManifestResolvers; + referencedManifest.resolverProperties = this.resolverProperties; - referencedManifest._perManifestResolvers = - this._perManifestResolvers; - referencedManifest._resolverProperties = - this._resolverProperties; + boolean referencedManifestValid = + referencedManifest.verifyReferences(followManifests); - boolean referencedManifestValid = - referencedManifest.verifyReferences(followManifests); + if (!referencedManifestValid) { + verify = false; - if (!referencedManifestValid) { - verify = false; + log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)"); + } else { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)"); + } + } + } catch (IOException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } catch (SAXException ex) { + throw new ReferenceNotInitializedException("empty", ex); + } + } + } catch (ReferenceNotInitializedException ex) { + Object exArgs[] = { currentRef.getURI() }; - log.log(java.util.logging.Level.WARNING, "The nested Manifest was invalid (bad)"); - } else { - log.log(java.util.logging.Level.FINE, "The nested Manifest was valid (good)"); - } - } catch (IOException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } catch (SAXException ex) { - throw new ReferenceNotInitializedException("empty", ex); - } + throw new MissingResourceFailureException( + "signature.Verification.Reference.NoInput", exArgs, ex, currentRef + ); } - } catch (ReferenceNotInitializedException ex) { - Object exArgs[] = { currentRef.getURI() }; + } - throw new MissingResourceFailureException( - "signature.Verification.Reference.NoInput", exArgs, ex, - currentRef); - } - } + return verify; + } - return verify; - } + /** + * Method setVerificationResult + * + * @param index + * @param verify + */ + private void setVerificationResult(int index, boolean verify) { + if (this.verificationResults == null) { + this.verificationResults = new boolean[this.getLength()]; + } - /** - * Method setVerificationResult - * - * @param index - * @param verify - */ - private void setVerificationResult(int index, boolean verify) - { + this.verificationResults[index] = verify; + } - if (this.verificationResults == null) { - this.verificationResults = new boolean[this.getLength()]; - } + /** + * After verifying a {@link Manifest} or a {@link SignedInfo} using the + * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods, + * the individual results can be retrieved with this method. + * + * @param index an index of into a {@link Manifest} or a {@link SignedInfo} + * @return the results of reference validation at the specified index + * @throws XMLSecurityException + */ + public boolean getVerificationResult(int index) throws XMLSecurityException { + if ((index < 0) || (index > this.getLength() - 1)) { + Object exArgs[] = { Integer.toString(index), Integer.toString(this.getLength()) }; + Exception e = + new IndexOutOfBoundsException( + I18n.translate("signature.Verification.IndexOutOfBounds", exArgs) + ); - this.verificationResults[index] = verify; - } + throw new XMLSecurityException("generic.EmptyMessage", e); + } - /** - * After verifying a {@link Manifest} or a {@link SignedInfo} using the - * {@link Manifest#verifyReferences()} or {@link SignedInfo#verify()} methods, - * the individual results can be retrieved with this method. - * - * @param index an index of into a {@link Manifest} or a {@link SignedInfo} - * @return the results of reference validation at the specified index - * @throws XMLSecurityException - */ - public boolean getVerificationResult(int index) throws XMLSecurityException { + if (this.verificationResults == null) { + try { + this.verifyReferences(); + } catch (Exception ex) { + throw new XMLSecurityException("generic.EmptyMessage", ex); + } + } - if ((index < 0) || (index > this.getLength() - 1)) { - Object exArgs[] = { Integer.toString(index), - Integer.toString(this.getLength()) }; - Exception e = - new IndexOutOfBoundsException(I18n - .translate("signature.Verification.IndexOutOfBounds", exArgs)); + return this.verificationResults[index]; + } - throw new XMLSecurityException("generic.EmptyMessage", e); - } + /** + * Adds Resource Resolver for retrieving resources at specified URI attribute + * in reference element + * + * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of + * {@link ResourceResolverSpi} for retrieving resource. + */ + public void addResourceResolver(ResourceResolver resolver) { + if (resolver == null) { + return; + } + if (perManifestResolvers == null) { + perManifestResolvers = new ArrayList(); + } + this.perManifestResolvers.add(resolver); + } - if (this.verificationResults == null) { - try { - this.verifyReferences(); - } catch (Exception ex) { - throw new XMLSecurityException("generic.EmptyMessage", ex); - } - } + /** + * Adds Resource Resolver for retrieving resources at specified URI attribute + * in reference element + * + * @param resolverSpi the implementation subclass of {@link ResourceResolverSpi} for + * retrieving the resource. + */ + public void addResourceResolver(ResourceResolverSpi resolverSpi) { + if (resolverSpi == null) { + return; + } + if (perManifestResolvers == null) { + perManifestResolvers = new ArrayList(); + } + perManifestResolvers.add(new ResourceResolver(resolverSpi)); + } - return this.verificationResults[index]; - } + /** + * Get the Per-Manifest Resolver List + * @return the per-manifest Resolver List + */ + public List getPerManifestResolvers() { + return perManifestResolvers; + } - /** - * Adds Resource Resolver for retrieving resources at specified URI attribute in reference element - * - * @param resolver {@link ResourceResolver} can provide the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource. - */ - public void addResourceResolver(ResourceResolver resolver) { + /** + * Get the resolver property map + * @return the resolver property map + */ + public Map getResolverProperties() { + return resolverProperties; + } - if (resolver == null) { - return; - } - if (_perManifestResolvers==null) - _perManifestResolvers = new ArrayList(); - this._perManifestResolvers.add(resolver); + /** + * Used to pass parameters like proxy servers etc to the ResourceResolver + * implementation. + * + * @param key the key + * @param value the value + */ + public void setResolverProperty(String key, String value) { + if (resolverProperties == null) { + resolverProperties = new HashMap(10); + } + this.resolverProperties.put(key, value); + } - } + /** + * Returns the value at specified key + * + * @param key the key + * @return the value + */ + public String getResolverProperty(String key) { + return this.resolverProperties.get(key); + } - /** - * Adds Resource Resolver for retrieving resources at specified URI attribute in reference element - * - * @param resolverSpi the implemenatin subclass of {@link ResourceResolverSpi} for retrieving resource. - */ - public void addResourceResolver(ResourceResolverSpi resolverSpi) { + /** + * Method getSignedContentItem + * + * @param i + * @return The signed content of the i reference. + * + * @throws XMLSignatureException + */ + public byte[] getSignedContentItem(int i) throws XMLSignatureException { + try { + return this.getReferencedContentAfterTransformsItem(i).getBytes(); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } catch (CanonicalizationException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new XMLSignatureException("empty", ex); + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } - if (resolverSpi == null) { - return; - } - if (_perManifestResolvers==null) - _perManifestResolvers = new ArrayList(); - this._perManifestResolvers.add(new ResourceResolver(resolverSpi)); + /** + * Method getReferencedContentPriorTransformsItem + * + * @param i + * @return The contents before transformation of the reference i. + * @throws XMLSecurityException + */ + public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i) + throws XMLSecurityException { + return this.item(i).getContentsBeforeTransformation(); + } - } + /** + * Method getReferencedContentAfterTransformsItem + * + * @param i + * @return The contents after transformation of the reference i. + * @throws XMLSecurityException + */ + public XMLSignatureInput getReferencedContentAfterTransformsItem(int i) + throws XMLSecurityException { + return this.item(i).getContentsAfterTransformation(); + } - /** - * Used to pass parameters like proxy servers etc to the ResourceResolver - * implementation. - * - * @param key the key - * @param value the value - */ - public void setResolverProperty(String key, String value) { - if (_resolverProperties==null) { - _resolverProperties=new HashMap(10); - } - this._resolverProperties.put(key, value); - } + /** + * Method getSignedContentLength + * + * @return The number of references contained in this reference. + */ + public int getSignedContentLength() { + return this.getLength(); + } - /** - * Returns the value at specified key - * - * @param key the key - * @return the value - */ - public String getResolverProperty(String key) { - return this._resolverProperties.get(key); - } - - /** - * Method getSignedContentItem - * - * @param i - * @return The signed content of the i reference. - * - * @throws XMLSignatureException - */ - public byte[] getSignedContentItem(int i) throws XMLSignatureException { - - try { - return this.getReferencedContentAfterTransformsItem(i).getBytes(); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } catch (CanonicalizationException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException("empty", ex); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", ex); - } - } - - /** - * Method getReferencedContentPriorTransformsItem - * - * @param i - * @return The contents before transformation of the reference i. - * @throws XMLSecurityException - */ - public XMLSignatureInput getReferencedContentBeforeTransformsItem(int i) - throws XMLSecurityException { - return this.item(i).getContentsBeforeTransformation(); - } - - /** - * Method getReferencedContentAfterTransformsItem - * - * @param i - * @return The contents after transformation of the reference i. - * @throws XMLSecurityException - */ - public XMLSignatureInput getReferencedContentAfterTransformsItem(int i) - throws XMLSecurityException { - return this.item(i).getContentsAfterTransformation(); - } - - /** - * Method getSignedContentLength - * - * @return The nu,ber of references contained in this reference. - */ - public int getSignedContentLength() { - return this.getLength(); - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public String getBaseLocalName() { - return Constants._TAG_MANIFEST; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public String getBaseLocalName() { + return Constants._TAG_MANIFEST; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java index 99f76041ee4..7da105d37be 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/MissingResourceFailureException.java @@ -2,28 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - - - /** * Thrown by {@link com.sun.org.apache.xml.internal.security.signature.SignedInfo#verify()} when * testing the signature fails because of uninitialized @@ -34,97 +32,93 @@ package com.sun.org.apache.xml.internal.security.signature; */ public class MissingResourceFailureException extends XMLSignatureException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** Field uninitializedReference */ - Reference uninitializedReference = null; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * MissingKeyResourceFailureException constructor. - * @param _msgID - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Reference reference) { + /** Field uninitializedReference */ + private Reference uninitializedReference = null; - super(_msgID); + /** + * MissingKeyResourceFailureException constructor. + * @param msgID + * @param reference + * @see #getReference + */ + public MissingResourceFailureException(String msgID, Reference reference) { + super(msgID); - this.uninitializedReference = reference; - } + this.uninitializedReference = reference; + } - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param exArgs - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Object exArgs[], - Reference reference) { + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param exArgs + * @param reference + * @see #getReference + */ + public MissingResourceFailureException(String msgID, Object exArgs[], Reference reference) { + super(msgID, exArgs); - super(_msgID, exArgs); + this.uninitializedReference = reference; + } - this.uninitializedReference = reference; - } + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param originalException + * @param reference + * @see #getReference + */ + public MissingResourceFailureException( + String msgID, Exception originalException, Reference reference + ) { + super(msgID, originalException); - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param _originalException - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, - Exception _originalException, - Reference reference) { + this.uninitializedReference = reference; + } - super(_msgID, _originalException); + /** + * Constructor MissingResourceFailureException + * + * @param msgID + * @param exArgs + * @param originalException + * @param reference + * @see #getReference + */ + public MissingResourceFailureException( + String msgID, Object exArgs[], Exception originalException, Reference reference + ) { + super(msgID, exArgs, originalException); - this.uninitializedReference = reference; - } + this.uninitializedReference = reference; + } - /** - * Constructor MissingResourceFailureException - * - * @param _msgID - * @param exArgs - * @param _originalException - * @param reference - * @see #getReference - */ - public MissingResourceFailureException(String _msgID, Object exArgs[], - Exception _originalException, - Reference reference) { + /** + * used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} + * + * @param reference the Reference object + * @see #getReference + */ + public void setReference(Reference reference) { + this.uninitializedReference = reference; + } - super(_msgID, exArgs, _originalException); - - this.uninitializedReference = reference; - } - - /** - * used to set the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} - * - * @param reference the Reference object - * @see #getReference - */ - public void setReference(Reference reference) { - this.uninitializedReference = reference; - } - - /** - * used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} - * - * This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput} - * to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification. - * - * @return the Reference object - * @see #setReference - */ - public Reference getReference() { - return this.uninitializedReference; - } + /** + * used to get the uninitialized {@link com.sun.org.apache.xml.internal.security.signature.Reference} + * + * This allows to supply the correct {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput} + * to the {@link com.sun.org.apache.xml.internal.security.signature.Reference} to try again verification. + * + * @return the Reference object + * @see #setReference + */ + public Reference getReference() { + return this.uninitializedReference; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java index 2ccf7a06905..6b670c1b274 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/NodeFilter.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; @@ -24,30 +26,30 @@ import org.w3c.dom.Node; /** * An interface to tell to the c14n if a node is included or not in the output - * @author raul - * */ public interface NodeFilter { - /** - * Tells if a node must be outputed in c14n. - * @param n - * @return 1 if the node should be outputed. - * 0 if node must not be outputed, - * -1 if the node and all it's child must not be output. - * - */ - public int isNodeInclude(Node n); - /** - * Tells if a node must be outputed in a c14n. - * The caller must assured that this method is always call - * in document order. The implementations can use this - * restriction to optimize the transformation. - * @param n - * @param level the relative level in the tree - * @return 1 if the node should be outputed. - * 0 if node must not be outputed, - * -1 if the node and all it's child must not be output. - */ - public int isNodeIncludeDO(Node n, int level); + + /** + * Tells if a node must be output in c14n. + * @param n + * @return 1 if the node should be output. + * 0 if node must not be output, + * -1 if the node and all it's child must not be output. + * + */ + int isNodeInclude(Node n); + + /** + * Tells if a node must be output in a c14n. + * The caller must assured that this method is always call + * in document order. The implementations can use this + * restriction to optimize the transformation. + * @param n + * @param level the relative level in the tree + * @return 1 if the node should be output. + * 0 if node must not be output, + * -1 if the node and all it's child must not be output. + */ + int isNodeIncludeDO(Node n, int level); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java index 8bbc4db2a62..bf2473295dc 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ObjectContainer.java @@ -2,27 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.utils.Constants; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -38,111 +39,99 @@ import org.w3c.dom.Node; */ public class ObjectContainer extends SignatureElementProxy { - /** - * Constructs {@link ObjectContainer} - * - * @param doc the {@link Document} in which Object element is placed - */ - public ObjectContainer(Document doc) { + /** + * Constructs {@link ObjectContainer} + * + * @param doc the {@link Document} in which Object element is placed + */ + public ObjectContainer(Document doc) { + super(doc); + } - super(doc); - } + /** + * Constructs {@link ObjectContainer} from {@link Element} + * + * @param element is Object element + * @param baseURI the URI of the resource where the XML instance was stored + * @throws XMLSecurityException + */ + public ObjectContainer(Element element, String baseURI) throws XMLSecurityException { + super(element, baseURI); + } - /** - * Constructs {@link ObjectContainer} from {@link Element} - * - * @param element is Object element - * @param BaseURI the URI of the resource where the XML instance was stored - * @throws XMLSecurityException - */ - public ObjectContainer(Element element, String BaseURI) - throws XMLSecurityException { + /** + * Sets the Id attribute + * + * @param Id Id attribute + */ + public void setId(String Id) { + if (Id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } - super(element, BaseURI); - } + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - /** - * Sets the Id attribute - * - * @param Id Id attribute - */ - public void setId(String Id) { + /** + * Sets the MimeType attribute + * + * @param MimeType the MimeType attribute + */ + public void setMimeType(String MimeType) { + if (MimeType != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, MimeType); + } + } - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } + /** + * Returns the MimeType attribute + * + * @return the MimeType attribute + */ + public String getMimeType() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); + } - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } + /** + * Sets the Encoding attribute + * + * @param Encoding the Encoding attribute + */ + public void setEncoding(String Encoding) { + if (Encoding != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, Encoding); + } + } - /** - * Sets the MimeType attribute - * - * @param MimeType the MimeType attribute - */ - public void setMimeType(String MimeType) { + /** + * Returns the Encoding attribute + * + * @return the Encoding attribute + */ + public String getEncoding() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); + } - if ( (MimeType != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_MIMETYPE, - MimeType); - } - } + /** + * Adds child Node + * + * @param node child Node + * @return the new node in the tree. + */ + public Node appendChild(Node node) { + return this.constructionElement.appendChild(node); + } - /** - * Returns the MimeType attribute - * - * @return the MimeType attribute - */ - public String getMimeType() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_MIMETYPE); - } - - /** - * Sets the Encoding attribute - * - * @param Encoding the Encoding attribute - */ - public void setEncoding(String Encoding) { - - if ((Encoding != null)) { - this._constructionElement.setAttributeNS(null, Constants._ATT_ENCODING, - Encoding); - } - } - - /** - * Returns the Encoding attribute - * - * @return the Encoding attribute - */ - public String getEncoding() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ENCODING); - } - - /** - * Adds child Node - * - * @param node child Node - * @return the new node in the tree. - */ - public Node appendChild(Node node) { - - Node result = null; - - result = this._constructionElement.appendChild(node); - - return result; - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_OBJECT; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_OBJECT; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java index 57bb7fa0f77..ece475c983d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/Reference.java @@ -2,31 +2,32 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.HashSet; +import java.util.Iterator; import java.util.Set; import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorithm; @@ -34,6 +35,10 @@ import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; import com.sun.org.apache.xml.internal.security.c14n.InvalidCanonicalizerException; import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceNodeSetData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceOctetStreamData; +import com.sun.org.apache.xml.internal.security.signature.reference.ReferenceSubTreeData; import com.sun.org.apache.xml.internal.security.transforms.InvalidTransformException; import com.sun.org.apache.xml.internal.security.transforms.Transform; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; @@ -42,7 +47,6 @@ import com.sun.org.apache.xml.internal.security.transforms.params.InclusiveNames import com.sun.org.apache.xml.internal.security.utils.Base64; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.DigesterOutputStream; -import com.sun.org.apache.xml.internal.security.utils.IdResolver; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; @@ -54,7 +58,6 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; - /** * Handles <ds:Reference> elements. * @@ -64,17 +67,17 @@ import org.w3c.dom.Text; * *

Create a new reference

*
- * Document _doc;
+ * Document doc;
  * MessageDigestAlgorithm sha1 = MessageDigestAlgorithm.getInstance("http://#sha1");
  * Reference ref = new Reference(new XMLSignatureInput(new FileInputStream("1.gif"),
  *                               "http://localhost/1.gif",
  *                               (Transforms) null, sha1);
- * Element refElem = ref.toElement(_doc);
+ * Element refElem = ref.toElement(doc);
  * 
* *

Verify a reference

*
- * Element refElem = _doc.getElement("Reference"); // PSEUDO
+ * Element refElem = doc.getElement("Reference"); // PSEUDO
  * Reference ref = new Reference(refElem);
  * String url = ref.getURI();
  * ref.setData(new XMLSignatureInput(new FileInputStream(url)));
@@ -103,689 +106,697 @@ import org.w3c.dom.Text;
  */
 public class Reference extends SignatureElementProxy {
 
-   /**
-    * Look up useC14N11 system property. If true, an explicit C14N11 transform
-    * will be added if necessary when generating the signature. See section
-    * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
-    */
-   private static boolean useC14N11 =
-      AccessController.doPrivileged(new PrivilegedAction() {
-         public Boolean run() {
-            return Boolean.getBoolean
-               ("com.sun.org.apache.xml.internal.security.useC14N11");
-         }
-      });
+    /** Field OBJECT_URI */
+    public static final String OBJECT_URI = Constants.SignatureSpecNS + Constants._TAG_OBJECT;
 
-/*
-   static {
-      try {
-         useC14N11 = Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11");
-      } catch (Exception e) {
-         // ignore exceptions
-      }
-   }
-*/
+    /** Field MANIFEST_URI */
+    public static final String MANIFEST_URI = Constants.SignatureSpecNS + Constants._TAG_MANIFEST;
 
-   /** Field CacheSignedNodes */
-   public final static boolean CacheSignedNodes = false;
+    /**
+     * The maximum number of transforms per reference, if secure validation is enabled.
+     */
+    public static final int MAXIMUM_TRANSFORM_COUNT = 5;
 
-   /** {@link java.util.logging} logging facility */
-    static java.util.logging.Logger log =
+    private boolean secureValidation;
+
+    /**
+     * Look up useC14N11 system property. If true, an explicit C14N11 transform
+     * will be added if necessary when generating the signature. See section
+     * 3.1.1 of http://www.w3.org/2007/xmlsec/Drafts/xmldsig-core/ for more info.
+     */
+    private static boolean useC14N11 = (
+        AccessController.doPrivileged(new PrivilegedAction() {
+            public Boolean run() {
+                return Boolean.valueOf(Boolean.getBoolean("com.sun.org.apache.xml.internal.security.useC14N11"));
+            }
+        })).booleanValue();
+
+    /** {@link org.apache.commons.logging} logging facility */
+    private static final java.util.logging.Logger log =
         java.util.logging.Logger.getLogger(Reference.class.getName());
 
-   /** Field OBJECT_URI */
-   public static final String OBJECT_URI = Constants.SignatureSpecNS
-                                           + Constants._TAG_OBJECT;
-
-   /** Field MANIFEST_URI */
-   public static final String MANIFEST_URI = Constants.SignatureSpecNS
-                                             + Constants._TAG_MANIFEST;
-   //J-
-   Manifest _manifest = null;
-   XMLSignatureInput _transformsOutput;
-   //J+
-
-private Transforms transforms;
-
-private Element digestMethodElem;
-
-private Element digestValueElement;
-
-   /**
-    * Constructor Reference
-    *
-    * @param doc the {@link Document} in which XMLsignature is placed
-    * @param BaseURI the URI of the resource where the XML instance will be stored
-    * @param ReferenceURI URI indicate where is data which will digested
-    * @param manifest
-    * @param transforms {@link Transforms} applied to data
-    * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is applied to the data
-    * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
-    * @throws XMLSignatureException
-    */
-   protected Reference(Document doc, String BaseURI, String ReferenceURI, Manifest manifest, Transforms transforms, String messageDigestAlgorithm)
-           throws XMLSignatureException {
-
-      super(doc);
-
-      XMLUtils.addReturnToElement(this._constructionElement);
-
-      this._baseURI = BaseURI;
-      this._manifest = manifest;
-
-      this.setURI(ReferenceURI);
-
-      // important: The ds:Reference must be added to the associated ds:Manifest
-      //            or ds:SignedInfo _before_ the this.resolverResult() is called.
-      // this._manifest.appendChild(this._constructionElement);
-      // this._manifest.appendChild(this._doc.createTextNode("\n"));
-
-      if (transforms != null) {
-          this.transforms=transforms;
-         this._constructionElement.appendChild(transforms.getElement());
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-      {
-         MessageDigestAlgorithm mda =
-            MessageDigestAlgorithm.getInstance(this._doc,
-                                               messageDigestAlgorithm);
-
-         digestMethodElem=mda.getElement();
-         this._constructionElement.appendChild(digestMethodElem);
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-      {
-         digestValueElement =
-            XMLUtils.createElementInSignatureSpace(this._doc,
-                                                   Constants._TAG_DIGESTVALUE);
-
-         this._constructionElement.appendChild(digestValueElement);
-         XMLUtils.addReturnToElement(this._constructionElement);
-      }
-   }
-
-
-   /**
-    * Build a {@link Reference} from an {@link Element}
-    *
-    * @param element Reference element
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs. We need this because the Manifest has the individual {@link ResourceResolver}s whcih have been set by the user
-    * @throws XMLSecurityException
-    */
-   protected Reference(Element element, String BaseURI, Manifest manifest)
-           throws XMLSecurityException {
-
-      super(element, BaseURI);
-      this._baseURI=BaseURI;
-      Element el=XMLUtils.getNextElement(element.getFirstChild());
-      if (Constants._TAG_TRANSFORMS.equals(el.getLocalName()) &&
-                  Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
-          transforms = new Transforms(el,this._baseURI);
-          el=XMLUtils.getNextElement(el.getNextSibling());
-      }
-      digestMethodElem = el;
-      digestValueElement =XMLUtils.getNextElement(digestMethodElem.getNextSibling());;
-      this._manifest = manifest;
-   }
-
-   /**
-    * Returns {@link MessageDigestAlgorithm}
-    *
-    *
-    * @return {@link MessageDigestAlgorithm}
-    *
-    * @throws XMLSignatureException
-    */
-   public MessageDigestAlgorithm getMessageDigestAlgorithm()
-           throws XMLSignatureException {
-
-      if (digestMethodElem == null) {
-         return null;
-      }
-
-      String uri = digestMethodElem.getAttributeNS(null,
-         Constants._ATT_ALGORITHM);
-
-          if (uri == null) {
-                  return null;
-          }
-
-      return MessageDigestAlgorithm.getInstance(this._doc, uri);
-   }
-
-   /**
-    * Sets the URI of this Reference element
-    *
-    * @param URI the URI of this Reference element
-    */
-   public void setURI(String URI) {
-
-      if ( URI != null) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_URI,
-                                                  URI);
-      }
-   }
-
-   /**
-    * Returns the URI of this Reference element
-    *
-    * @return URI the URI of this Reference element
-    */
-   public String getURI() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_URI);
-   }
-
-   /**
-    * Sets the Id attribute of this Reference element
-    *
-    * @param Id the Id attribute of this Reference element
-    */
-   public void setId(String Id) {
-
-      if ( Id != null ) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
-
-   /**
-    * Returns the Id attribute of this Reference element
-    *
-    * @return Id the Id attribute of this Reference element
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
-
-   /**
-    * Sets the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element
-    *
-    * @param Type the type attribute of the Reference
-    */
-   public void setType(String Type) {
-
-      if (Type != null) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_TYPE,
-                                                  Type);
-      }
-   }
-
-   /**
-    * Return the type atttibute of the Reference indicate whether an ds:Object, ds:SignatureProperty, or ds:Manifest element
-    *
-    * @return the type attribute of the Reference
-    */
-   public String getType() {
-      return this._constructionElement.getAttributeNS(null,
-              Constants._ATT_TYPE);
-   }
-
-   /**
-    * Method isReferenceToObject
-    *
-    * This returns true if the Type attribute of the
-    * Refernce element points to a #Object element
-    *
-    * @return true if the Reference type indicates that this Reference points to an Object
-    */
-   public boolean typeIsReferenceToObject() {
-
-      if (Reference.OBJECT_URI.equals(this.getType())) {
-         return true;
-      }
-
-      return false;
-   }
-
-   /**
-    * Method isReferenceToManifest
-    *
-    * This returns true if the Type attribute of the
-    * Refernce element points to a #Manifest element
-    *
-    * @return true if the Reference type indicates that this Reference points to a {@link Manifest}
-    */
-   public boolean typeIsReferenceToManifest() {
-
-      if (Reference.MANIFEST_URI.equals(this.getType())) {
-         return true;
-      }
-
-      return false;
-   }
-
-   /**
-    * Method setDigestValueElement
-    *
-    * @param digestValue
-    */
-   private void setDigestValueElement(byte[] digestValue)
-   {
-         Node n=digestValueElement.getFirstChild();
-         while (n!=null) {
-               digestValueElement.removeChild(n);
-               n = n.getNextSibling();
-         }
-
-         String base64codedValue = Base64.encode(digestValue);
-         Text t = this._doc.createTextNode(base64codedValue);
-
-         digestValueElement.appendChild(t);
-   }
-
-   /**
-    * Method generateDigestValue
-    *
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   public void generateDigestValue()
-           throws XMLSignatureException, ReferenceNotInitializedException {
-      this.setDigestValueElement(this.calculateDigest(false));
-   }
-
-   /**
-    * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
-    * @return the XMLSignatureInput of the source of this reference
-    * @throws ReferenceNotInitializedException If the resolver found any
-    *  problem resolving the reference
-    */
-   public XMLSignatureInput getContentsBeforeTransformation()
-           throws ReferenceNotInitializedException {
-
-      try {
-         Attr URIAttr = this._constructionElement.getAttributeNodeNS(null,
-            Constants._ATT_URI);
-         String URI;
-
-         if (URIAttr == null) {
-            URI = null;
-         } else {
-            URI = URIAttr.getNodeValue();
-         }
-
-         ResourceResolver resolver = ResourceResolver.getInstance(URIAttr,
-            this._baseURI, this._manifest._perManifestResolvers);
-
-         if (resolver == null) {
-            Object exArgs[] = { URI };
-
-            throw new ReferenceNotInitializedException(
-               "signature.Verification.Reference.NoInput", exArgs);
-         }
-
-         resolver.addProperties(this._manifest._resolverProperties);
-
-         XMLSignatureInput input = resolver.resolve(URIAttr, this._baseURI);
-
-
-         return input;
-      }  catch (ResourceResolverException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
-
-   /**
-    * Returns the data which is referenced by the URI attribute. This method
-    * only works works after a call to verify.
-    * @return a XMLSignature with a byte array.
-    * @throws ReferenceNotInitializedException
-    *
-    * @deprecated use getContentsBeforeTransformation
-    */
-   @Deprecated
-   public XMLSignatureInput getTransformsInput() throws ReferenceNotInitializedException
-        {
-                XMLSignatureInput input=getContentsBeforeTransformation();
-                XMLSignatureInput result;
-                try {
-                        result = new XMLSignatureInput(input.getBytes());
-                } catch (CanonicalizationException ex) {
-                         throw new ReferenceNotInitializedException("empty", ex);
-                } catch (IOException ex) {
-                         throw new ReferenceNotInitializedException("empty", ex);
-                }
-                result.setSourceURI(input.getSourceURI());
-                return result;
-
-   }
-
-   private XMLSignatureInput getContentsAfterTransformation(XMLSignatureInput input, OutputStream os)
-           throws XMLSignatureException {
-
-      try {
-         Transforms transforms = this.getTransforms();
-         XMLSignatureInput output = null;
-
-         if (transforms != null) {
-            output = transforms.performTransforms(input,os);
-            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
-
-            //this._transformsOutput.setSourceURI(output.getSourceURI());
-         } else {
-            output = input;
-         }
-
-         return output;
-      } catch (ResourceResolverException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (CanonicalizationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
-
-   /**
-    * Returns the XMLSignatureInput which is the result of the Transforms.
-    * @return a XMLSignatureInput with all transformations applied.
-    * @throws XMLSignatureException
-    */
-   public XMLSignatureInput getContentsAfterTransformation()
-           throws XMLSignatureException {
-
-      XMLSignatureInput input = this.getContentsBeforeTransformation();
-
-      return this.getContentsAfterTransformation(input, null);
-   }
-
-   /**
-    * This method returns the XMLSignatureInput which represents the node set before
-    * some kind of canonicalization is applied for the first time.
-    * @return Gets a the node doing everything till the first c14n is needed
-    *
-    * @throws XMLSignatureException
-    */
-   public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
-           throws XMLSignatureException {
-
-      try {
-         XMLSignatureInput input = this.getContentsBeforeTransformation();
-         XMLSignatureInput output = input;
-         Transforms transforms = this.getTransforms();
-
-         if (transforms != null) {
-            doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
-               Transform t = transforms.item(i);
-               String URI = t.getURI();
-
-               if (URI.equals(Transforms
-                       .TRANSFORM_C14N_EXCL_OMIT_COMMENTS) || URI
-                          .equals(Transforms
-                             .TRANSFORM_C14N_EXCL_WITH_COMMENTS) || URI
-                                .equals(Transforms
-                                   .TRANSFORM_C14N_OMIT_COMMENTS) || URI
-                                      .equals(Transforms
-                                         .TRANSFORM_C14N_WITH_COMMENTS)) {
-
-                  break doTransforms;
-               }
-
-               output = t.performTransform(output, null);
+    private Manifest manifest;
+    private XMLSignatureInput transformsOutput;
+
+    private Transforms transforms;
+
+    private Element digestMethodElem;
+
+    private Element digestValueElement;
+
+    private ReferenceData referenceData;
+
+    /**
+     * Constructor Reference
+     *
+     * @param doc the {@link Document} in which XMLsignature is placed
+     * @param baseURI the URI of the resource where the XML instance will be stored
+     * @param referenceURI URI indicate where is data which will digested
+     * @param manifest
+     * @param transforms {@link Transforms} applied to data
+     * @param messageDigestAlgorithm {@link MessageDigestAlgorithm Digest algorithm} which is
+     * applied to the data
+     * TODO should we throw XMLSignatureException if MessageDigestAlgoURI is wrong?
+     * @throws XMLSignatureException
+     */
+    protected Reference(
+        Document doc, String baseURI, String referenceURI, Manifest manifest,
+        Transforms transforms, String messageDigestAlgorithm
+    ) throws XMLSignatureException {
+        super(doc);
+
+        XMLUtils.addReturnToElement(this.constructionElement);
+
+        this.baseURI = baseURI;
+        this.manifest = manifest;
+
+        this.setURI(referenceURI);
+
+        // important: The ds:Reference must be added to the associated ds:Manifest
+        //            or ds:SignedInfo _before_ the this.resolverResult() is called.
+        // this.manifest.appendChild(this.constructionElement);
+        // this.manifest.appendChild(this.doc.createTextNode("\n"));
+
+        if (transforms != null) {
+            this.transforms=transforms;
+            this.constructionElement.appendChild(transforms.getElement());
+            XMLUtils.addReturnToElement(this.constructionElement);
+        }
+        MessageDigestAlgorithm mda =
+            MessageDigestAlgorithm.getInstance(this.doc, messageDigestAlgorithm);
+
+        digestMethodElem = mda.getElement();
+        this.constructionElement.appendChild(digestMethodElem);
+        XMLUtils.addReturnToElement(this.constructionElement);
+
+        digestValueElement =
+            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_DIGESTVALUE);
+
+        this.constructionElement.appendChild(digestValueElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
+
+
+    /**
+     * Build a {@link Reference} from an {@link Element}
+     *
+     * @param element Reference element
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
+     * We need this because the Manifest has the individual {@link ResourceResolver}s which have
+     * been set by the user
+     * @throws XMLSecurityException
+     */
+    protected Reference(Element element, String baseURI, Manifest manifest) throws XMLSecurityException {
+        this(element, baseURI, manifest, false);
+    }
+
+    /**
+     * Build a {@link Reference} from an {@link Element}
+     *
+     * @param element Reference element
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param manifest is the {@link Manifest} of {@link SignedInfo} in which the Reference occurs.
+     * @param secureValidation whether secure validation is enabled or not
+     * We need this because the Manifest has the individual {@link ResourceResolver}s which have
+     * been set by the user
+     * @throws XMLSecurityException
+     */
+    protected Reference(Element element, String baseURI, Manifest manifest, boolean secureValidation)
+        throws XMLSecurityException {
+        super(element, baseURI);
+        this.secureValidation = secureValidation;
+        this.baseURI = baseURI;
+        Element el = XMLUtils.getNextElement(element.getFirstChild());
+        if (Constants._TAG_TRANSFORMS.equals(el.getLocalName())
+            && Constants.SignatureSpecNS.equals(el.getNamespaceURI())) {
+            transforms = new Transforms(el, this.baseURI);
+            transforms.setSecureValidation(secureValidation);
+            if (secureValidation && transforms.getLength() > MAXIMUM_TRANSFORM_COUNT) {
+                Object exArgs[] = { transforms.getLength(), MAXIMUM_TRANSFORM_COUNT };
+
+                throw new XMLSecurityException("signature.tooManyTransforms", exArgs);
+            }
+            el = XMLUtils.getNextElement(el.getNextSibling());
+        }
+        digestMethodElem = el;
+        digestValueElement = XMLUtils.getNextElement(digestMethodElem.getNextSibling());
+        this.manifest = manifest;
+    }
+
+    /**
+     * Returns {@link MessageDigestAlgorithm}
+     *
+     *
+     * @return {@link MessageDigestAlgorithm}
+     *
+     * @throws XMLSignatureException
+     */
+    public MessageDigestAlgorithm getMessageDigestAlgorithm() throws XMLSignatureException {
+        if (digestMethodElem == null) {
+            return null;
+        }
+
+        String uri = digestMethodElem.getAttributeNS(null, Constants._ATT_ALGORITHM);
+
+        if (uri == null) {
+            return null;
+        }
+
+        if (secureValidation && MessageDigestAlgorithm.ALGO_ID_DIGEST_NOT_RECOMMENDED_MD5.equals(uri)) {
+            Object exArgs[] = { uri };
+
+            throw new XMLSignatureException("signature.signatureAlgorithm", exArgs);
+        }
+
+        return MessageDigestAlgorithm.getInstance(this.doc, uri);
+    }
+
+    /**
+     * Sets the URI of this Reference element
+     *
+     * @param uri the URI of this Reference element
+     */
+    public void setURI(String uri) {
+        if (uri != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_URI, uri);
+        }
+    }
+
+    /**
+     * Returns the URI of this Reference element
+     *
+     * @return URI the URI of this Reference element
+     */
+    public String getURI() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_URI);
+    }
+
+    /**
+     * Sets the Id attribute of this Reference element
+     *
+     * @param id the Id attribute of this Reference element
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
+
+    /**
+     * Returns the Id attribute of this Reference element
+     *
+     * @return Id the Id attribute of this Reference element
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
+
+    /**
+     * Sets the type atttibute of the Reference indicate whether an
+     * ds:Object, ds:SignatureProperty, or ds:Manifest
+     * element.
+     *
+     * @param type the type attribute of the Reference
+     */
+    public void setType(String type) {
+        if (type != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_TYPE, type);
+        }
+    }
+
+    /**
+     * Return the type atttibute of the Reference indicate whether an
+     * ds:Object, ds:SignatureProperty, or ds:Manifest
+     * element
+     *
+     * @return the type attribute of the Reference
+     */
+    public String getType() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_TYPE);
+    }
+
+    /**
+     * Method isReferenceToObject
+     *
+     * This returns true if the Type attribute of the
+     * Reference element points to a #Object element
+     *
+     * @return true if the Reference type indicates that this Reference points to an
+     * Object
+     */
+    public boolean typeIsReferenceToObject() {
+        if (Reference.OBJECT_URI.equals(this.getType())) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Method isReferenceToManifest
+     *
+     * This returns true if the Type attribute of the
+     * Reference element points to a #Manifest element
+     *
+     * @return true if the Reference type indicates that this Reference points to a
+     * {@link Manifest}
+     */
+    public boolean typeIsReferenceToManifest() {
+        if (Reference.MANIFEST_URI.equals(this.getType())) {
+            return true;
+        }
+
+        return false;
+    }
+
+    /**
+     * Method setDigestValueElement
+     *
+     * @param digestValue
+     */
+    private void setDigestValueElement(byte[] digestValue) {
+        Node n = digestValueElement.getFirstChild();
+        while (n != null) {
+            digestValueElement.removeChild(n);
+            n = n.getNextSibling();
+        }
+
+        String base64codedValue = Base64.encode(digestValue);
+        Text t = this.doc.createTextNode(base64codedValue);
+
+        digestValueElement.appendChild(t);
+    }
+
+    /**
+     * Method generateDigestValue
+     *
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    public void generateDigestValue()
+        throws XMLSignatureException, ReferenceNotInitializedException {
+        this.setDigestValueElement(this.calculateDigest(false));
+    }
+
+    /**
+     * Returns the XMLSignatureInput which is created by de-referencing the URI attribute.
+     * @return the XMLSignatureInput of the source of this reference
+     * @throws ReferenceNotInitializedException If the resolver found any
+     * problem resolving the reference
+     */
+    public XMLSignatureInput getContentsBeforeTransformation()
+        throws ReferenceNotInitializedException {
+        try {
+            Attr uriAttr =
+                this.constructionElement.getAttributeNodeNS(null, Constants._ATT_URI);
+
+            ResourceResolver resolver =
+                ResourceResolver.getInstance(
+                    uriAttr, this.baseURI, this.manifest.getPerManifestResolvers(), secureValidation
+                );
+            resolver.addProperties(this.manifest.getResolverProperties());
+
+            return resolver.resolve(uriAttr, this.baseURI, secureValidation);
+        }  catch (ResourceResolverException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
+
+    private XMLSignatureInput getContentsAfterTransformation(
+        XMLSignatureInput input, OutputStream os
+    ) throws XMLSignatureException {
+        try {
+            Transforms transforms = this.getTransforms();
+            XMLSignatureInput output = null;
+
+            if (transforms != null) {
+                output = transforms.performTransforms(input, os);
+                this.transformsOutput = output;//new XMLSignatureInput(output.getBytes());
+
+                //this.transformsOutput.setSourceURI(output.getSourceURI());
+            } else {
+                output = input;
             }
 
+            return output;
+        } catch (ResourceResolverException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
+
+    /**
+     * Returns the XMLSignatureInput which is the result of the Transforms.
+     * @return a XMLSignatureInput with all transformations applied.
+     * @throws XMLSignatureException
+     */
+    public XMLSignatureInput getContentsAfterTransformation()
+        throws XMLSignatureException {
+        XMLSignatureInput input = this.getContentsBeforeTransformation();
+        cacheDereferencedElement(input);
+
+        return this.getContentsAfterTransformation(input, null);
+    }
+
+    /**
+     * This method returns the XMLSignatureInput which represents the node set before
+     * some kind of canonicalization is applied for the first time.
+     * @return Gets a the node doing everything till the first c14n is needed
+     *
+     * @throws XMLSignatureException
+     */
+    public XMLSignatureInput getNodesetBeforeFirstCanonicalization()
+        throws XMLSignatureException {
+        try {
+            XMLSignatureInput input = this.getContentsBeforeTransformation();
+            cacheDereferencedElement(input);
+            XMLSignatureInput output = input;
+            Transforms transforms = this.getTransforms();
+
+            if (transforms != null) {
+                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+                    Transform t = transforms.item(i);
+                    String uri = t.getURI();
+
+                    if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_WITH_COMMENTS)) {
+                        break doTransforms;
+                    }
+
+                    output = t.performTransform(output, null);
+                }
+
             output.setSourceURI(input.getSourceURI());
-         }
-         return output;
-      } catch (IOException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (ResourceResolverException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (CanonicalizationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidCanonicalizerException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            }
+            return output;
+        } catch (IOException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (ResourceResolverException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidCanonicalizerException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Method getHTMLRepresentation
-    * @return The HTML of the transformation
-    * @throws XMLSignatureException
-    */
-   public String getHTMLRepresentation() throws XMLSignatureException {
+    /**
+     * Method getHTMLRepresentation
+     * @return The HTML of the transformation
+     * @throws XMLSignatureException
+     */
+    public String getHTMLRepresentation() throws XMLSignatureException {
+        try {
+            XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
 
-      try {
-         XMLSignatureInput nodes = this.getNodesetBeforeFirstCanonicalization();
-         Set inclusiveNamespaces = new HashSet();
-
-         {
             Transforms transforms = this.getTransforms();
             Transform c14nTransform = null;
 
             if (transforms != null) {
-               doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
-                  Transform t = transforms.item(i);
-                  String URI = t.getURI();
+                doTransforms: for (int i = 0; i < transforms.getLength(); i++) {
+                    Transform t = transforms.item(i);
+                    String uri = t.getURI();
 
-                  if (URI.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
-                          || URI.equals(
-                             Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
-                     c14nTransform = t;
-
-                     break doTransforms;
-                  }
-               }
+                    if (uri.equals(Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS)
+                        || uri.equals(Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS)) {
+                        c14nTransform = t;
+                        break doTransforms;
+                    }
+                }
             }
 
-            if (c14nTransform != null) {
+            Set inclusiveNamespaces = new HashSet();
+            if (c14nTransform != null
+                && (c14nTransform.length(
+                    InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                    InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1)) {
 
-               if (c14nTransform
-                       .length(InclusiveNamespaces
-                          .ExclusiveCanonicalizationNamespace, InclusiveNamespaces
-                          ._TAG_EC_INCLUSIVENAMESPACES) == 1) {
-
-                  // there is one InclusiveNamespaces element
-                  InclusiveNamespaces in = new InclusiveNamespaces(
+                // there is one InclusiveNamespaces element
+                InclusiveNamespaces in =
+                    new InclusiveNamespaces(
                         XMLUtils.selectNode(
-                        c14nTransform.getElement().getFirstChild(),
-                                                InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
-                        InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0), this.getBaseURI());
+                            c14nTransform.getElement().getFirstChild(),
+                            InclusiveNamespaces.ExclusiveCanonicalizationNamespace,
+                            InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,
+                            0
+                        ), this.getBaseURI());
 
-                  inclusiveNamespaces = InclusiveNamespaces.prefixStr2Set(
-                     in.getInclusiveNamespaces());
-               }
+                inclusiveNamespaces =
+                    InclusiveNamespaces.prefixStr2Set(in.getInclusiveNamespaces());
             }
-         }
 
-         return nodes.getHTMLRepresentation(inclusiveNamespaces);
-      } catch (TransformationException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (InvalidTransformException ex) {
-         throw new XMLSignatureException("empty", ex);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+            return nodes.getHTMLRepresentation(inclusiveNamespaces);
+        } catch (TransformationException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (InvalidTransformException ex) {
+            throw new XMLSignatureException("empty", ex);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * This method only works works after a call to verify.
-    * @return the transformed output(i.e. what is going to be digested).
-    */
-   public XMLSignatureInput getTransformsOutput() {
-      return this._transformsOutput;
-   }
+    /**
+     * This method only works works after a call to verify.
+     * @return the transformed output(i.e. what is going to be digested).
+     */
+    public XMLSignatureInput getTransformsOutput() {
+        return this.transformsOutput;
+    }
 
-   /**
-    * This method returns the {@link XMLSignatureInput} which is referenced by the
-    * URI Attribute.
-    * @param os where to write the transformation can be null.
-    * @return the element to digest
-    *
-    * @throws XMLSignatureException
-    * @see Manifest#verifyReferences()
-    */
-   protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
-           throws XMLSignatureException {
+    /**
+     * Get the ReferenceData that corresponds to the cached representation of the dereferenced
+     * object before transformation.
+     */
+    public ReferenceData getReferenceData() {
+        return referenceData;
+    }
 
-      try {
-         XMLSignatureInput input = this.getContentsBeforeTransformation();
-         XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
+    /**
+     * This method returns the {@link XMLSignatureInput} which is referenced by the
+     * URI Attribute.
+     * @param os where to write the transformation can be null.
+     * @return the element to digest
+     *
+     * @throws XMLSignatureException
+     * @see Manifest#verifyReferences()
+     */
+    protected XMLSignatureInput dereferenceURIandPerformTransforms(OutputStream os)
+        throws XMLSignatureException {
+        try {
+            XMLSignatureInput input = this.getContentsBeforeTransformation();
+            cacheDereferencedElement(input);
 
-         /* at this stage, this._transformsInput and this._transformsOutput
-          * contain a huge amount of nodes. When we do not cache these nodes
-          * but only preserve the octets, the memory footprint is dramatically
-          * reduced.
-          */
-         if (!Reference.CacheSignedNodes) {
+            XMLSignatureInput output = this.getContentsAfterTransformation(input, os);
+            this.transformsOutput = output;
+            return output;
+        } catch (XMLSecurityException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
 
-            this._transformsOutput = output;//new XMLSignatureInput(output.getBytes());
+    /**
+     * Store the dereferenced Element(s) so that it/they can be retrieved later.
+     */
+    private void cacheDereferencedElement(XMLSignatureInput input) {
+        if (input.isNodeSet()) {
+            try {
+                final Set s = input.getNodeSet();
+                referenceData = new ReferenceNodeSetData() {
+                    public Iterator iterator() {
+                        return new Iterator() {
 
-            //this._transformsOutput.setSourceURI(output.getSourceURI());
-         }
-         return output;
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
+                            Iterator sIterator = s.iterator();
 
-   /**
-    * Method getTransforms
-    *
-    * @return The transforms that applied this reference.
-    * @throws InvalidTransformException
-    * @throws TransformationException
-    * @throws XMLSecurityException
-    * @throws XMLSignatureException
-    */
-   public Transforms getTransforms()
-           throws XMLSignatureException, InvalidTransformException,
-                  TransformationException, XMLSecurityException {
+                            public boolean hasNext() {
+                                return sIterator.hasNext();
+                            }
 
-      return transforms;
-   }
+                            public Node next() {
+                                return sIterator.next();
+                            }
 
-   /**
-    * Method getReferencedBytes
-    *
-    * @return the bytes that will be used to generated digest.
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   public byte[] getReferencedBytes()
-           throws ReferenceNotInitializedException, XMLSignatureException {
-    try {
-        XMLSignatureInput output=this.dereferenceURIandPerformTransforms(null);
+                            public void remove() {
+                                throw new UnsupportedOperationException();
+                            }
+                        };
+                    }
+                };
+            } catch (Exception e) {
+                // log a warning
+                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + e);
+            }
+        } else if (input.isElement()) {
+            referenceData = new ReferenceSubTreeData
+                (input.getSubNode(), input.isExcludeComments());
+        } else if (input.isOctetStream() || input.isByteArray()) {
+            try {
+                referenceData = new ReferenceOctetStreamData
+                    (input.getOctetStream(), input.getSourceURI(),
+                        input.getMIMEType());
+            } catch (IOException ioe) {
+                // log a warning
+                log.log(java.util.logging.Level.WARNING, "cannot cache dereferenced data: " + ioe);
+            }
+        }
+    }
 
-        byte[] signedBytes = output.getBytes();
+    /**
+     * Method getTransforms
+     *
+     * @return The transforms that applied this reference.
+     * @throws InvalidTransformException
+     * @throws TransformationException
+     * @throws XMLSecurityException
+     * @throws XMLSignatureException
+     */
+    public Transforms getTransforms()
+        throws XMLSignatureException, InvalidTransformException,
+        TransformationException, XMLSecurityException {
+        return transforms;
+    }
 
-        return signedBytes;
-     } catch (IOException ex) {
-        throw new ReferenceNotInitializedException("empty", ex);
-     } catch (CanonicalizationException ex) {
-        throw new ReferenceNotInitializedException("empty", ex);
-     }
-
-   }
+    /**
+     * Method getReferencedBytes
+     *
+     * @return the bytes that will be used to generated digest.
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    public byte[] getReferencedBytes()
+        throws ReferenceNotInitializedException, XMLSignatureException {
+        try {
+            XMLSignatureInput output = this.dereferenceURIandPerformTransforms(null);
+            return output.getBytes();
+        } catch (IOException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } catch (CanonicalizationException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        }
+    }
 
 
-   /**
-    * Method calculateDigest
-    *
-    * @param validating true if validating the reference
-    * @return reference Calculate the digest of this reference.
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSignatureException
-    */
-   private byte[] calculateDigest(boolean validating)
-           throws ReferenceNotInitializedException, XMLSignatureException {
+    /**
+     * Method calculateDigest
+     *
+     * @param validating true if validating the reference
+     * @return reference Calculate the digest of this reference.
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSignatureException
+     */
+    private byte[] calculateDigest(boolean validating)
+        throws ReferenceNotInitializedException, XMLSignatureException {
+        OutputStream os = null;
+        try {
+            MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
 
-      try {
+            mda.reset();
+            DigesterOutputStream diOs = new DigesterOutputStream(mda);
+            os = new UnsyncBufferedOutputStream(diOs);
+            XMLSignatureInput output = this.dereferenceURIandPerformTransforms(os);
+            // if signing and c14n11 property == true explicitly add
+            // C14N11 transform if needed
+            if (Reference.useC14N11 && !validating && !output.isOutputStreamSet()
+                && !output.isOctetStream()) {
+                if (transforms == null) {
+                    transforms = new Transforms(this.doc);
+                    transforms.setSecureValidation(secureValidation);
+                    this.constructionElement.insertBefore(transforms.getElement(), digestMethodElem);
+                }
+                transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
+                output.updateOutputStream(os, true);
+            } else {
+                output.updateOutputStream(os);
+            }
+            os.flush();
 
-         MessageDigestAlgorithm mda = this.getMessageDigestAlgorithm();
+            if (output.getOctetStreamReal() != null) {
+                output.getOctetStreamReal().close();
+            }
 
-         mda.reset();
-         DigesterOutputStream diOs=new DigesterOutputStream(mda);
-         OutputStream os=new UnsyncBufferedOutputStream(diOs);
-         XMLSignatureInput output=this.dereferenceURIandPerformTransforms(os);
-         // if signing and c14n11 property == true explicitly add
-         // C14N11 transform if needed
-         if (Reference.useC14N11 && !validating &&
-             !output.isOutputStreamSet() && !output.isOctetStream()) {
-             if (transforms == null) {
-                 transforms = new Transforms(this._doc);
-                 this._constructionElement.insertBefore
-                     (transforms.getElement(), digestMethodElem);
-             }
-             transforms.addTransform(Transforms.TRANSFORM_C14N11_OMIT_COMMENTS);
-             output.updateOutputStream(os, true);
-         } else {
-             output.updateOutputStream(os);
-         }
-         os.flush();
-         //this.getReferencedBytes(diOs);
-         //mda.update(data);
+            //this.getReferencedBytes(diOs);
+            //mda.update(data);
 
-         return diOs.getDigestValue();
-      } catch (XMLSecurityException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      } catch (IOException ex) {
-         throw new ReferenceNotInitializedException("empty", ex);
-      }
-   }
+            return diOs.getDigestValue();
+        } catch (XMLSecurityException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } catch (IOException ex) {
+            throw new ReferenceNotInitializedException("empty", ex);
+        } finally {
+            if (os != null) {
+                try {
+                    os.close();
+                } catch (IOException ex) {
+                    throw new ReferenceNotInitializedException("empty", ex);
+                }
+            }
+        }
+    }
 
-   /**
-    * Returns the digest value.
-    *
-    * @return the digest value.
-    * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
-    * @throws XMLSecurityException if the Reference does not contain a DigestValue element
-    */
-   public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
-      if (digestValueElement == null) {
-                  // The required element is not in the XML!
-                  Object[] exArgs ={ Constants._TAG_DIGESTVALUE,
-                                                         Constants.SignatureSpecNS };
-                  throw new XMLSecurityException(
-                                        "signature.Verification.NoSignatureElement",
-                                        exArgs);
-          }
-      byte[] elemDig = Base64.decode(digestValueElement);
-      return elemDig;
-   }
+    /**
+     * Returns the digest value.
+     *
+     * @return the digest value.
+     * @throws Base64DecodingException if Reference contains no proper base64 encoded data.
+     * @throws XMLSecurityException if the Reference does not contain a DigestValue element
+     */
+    public byte[] getDigestValue() throws Base64DecodingException, XMLSecurityException {
+        if (digestValueElement == null) {
+            // The required element is not in the XML!
+            Object[] exArgs ={ Constants._TAG_DIGESTVALUE, Constants.SignatureSpecNS };
+            throw new XMLSecurityException(
+                "signature.Verification.NoSignatureElement", exArgs
+            );
+        }
+        return Base64.decode(digestValueElement);
+    }
 
 
-   /**
-    * Tests reference valdiation is success or false
-    *
-    * @return true if reference valdiation is success, otherwise false
-    * @throws ReferenceNotInitializedException
-    * @throws XMLSecurityException
-    */
-   public boolean verify()
-           throws ReferenceNotInitializedException, XMLSecurityException {
+    /**
+     * Tests reference validation is success or false
+     *
+     * @return true if reference validation is success, otherwise false
+     * @throws ReferenceNotInitializedException
+     * @throws XMLSecurityException
+     */
+    public boolean verify()
+        throws ReferenceNotInitializedException, XMLSecurityException {
+        byte[] elemDig = this.getDigestValue();
+        byte[] calcDig = this.calculateDigest(true);
+        boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
 
-      byte[] elemDig = this.getDigestValue();
-      byte[] calcDig = this.calculateDigest(true);
-      boolean equal = MessageDigestAlgorithm.isEqual(elemDig, calcDig);
+        if (!equal) {
+            log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
+            log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
+            log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
+        } else {
+            if (log.isLoggable(java.util.logging.Level.FINE)) {
+                log.log(java.util.logging.Level.FINE, "Verification successful for URI \"" + this.getURI() + "\"");
+            }
+        }
 
-      if (!equal) {
-         log.log(java.util.logging.Level.WARNING, "Verification failed for URI \"" + this.getURI() + "\"");
-         log.log(java.util.logging.Level.WARNING, "Expected Digest: " + Base64.encode(elemDig));
-         log.log(java.util.logging.Level.WARNING, "Actual Digest: " + Base64.encode(calcDig));
-      } else {
-         log.log(java.util.logging.Level.INFO, "Verification successful for URI \"" + this.getURI() + "\"");
-      }
+        return equal;
+    }
 
-      return equal;
-   }
-
-   /**
-    * Method getBaseLocalName
-    * @inheritDoc
-    *
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_REFERENCE;
-   }
+    /**
+     * Method getBaseLocalName
+     * @inheritDoc
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_REFERENCE;
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
index 98dd0a2ee52..95da73e68b8 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/ReferenceNotInitializedException.java
@@ -2,28 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
-
-
 /**
  * Raised if verifying a {@link com.sun.org.apache.xml.internal.security.signature.Reference} fails
  * because of an uninitialized {@link com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput}
@@ -32,58 +30,56 @@ package com.sun.org.apache.xml.internal.security.signature;
  */
 public class ReferenceNotInitializedException extends XMLSignatureException {
 
-   /**
-         *
-         */
-        private static final long serialVersionUID = 1L;
+    /**
+     *
+     */
+    private static final long serialVersionUID = 1L;
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    */
-   public ReferenceNotInitializedException() {
-      super();
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     */
+    public ReferenceNotInitializedException() {
+        super();
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    */
-   public ReferenceNotInitializedException(String _msgID) {
-      super(_msgID);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     */
+    public ReferenceNotInitializedException(String msgID) {
+        super(msgID);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param exArgs
-    */
-   public ReferenceNotInitializedException(String _msgID, Object exArgs[]) {
-      super(_msgID, exArgs);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param exArgs
+     */
+    public ReferenceNotInitializedException(String msgID, Object exArgs[]) {
+        super(msgID, exArgs);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param _originalException
-    */
-   public ReferenceNotInitializedException(String _msgID,
-                                           Exception _originalException) {
-      super(_msgID, _originalException);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param originalException
+     */
+    public ReferenceNotInitializedException(String msgID, Exception originalException) {
+        super(msgID, originalException);
+    }
 
-   /**
-    * Constructor ReferenceNotInitializedException
-    *
-    * @param _msgID
-    * @param exArgs
-    * @param _originalException
-    */
-   public ReferenceNotInitializedException(String _msgID, Object exArgs[],
-                                           Exception _originalException) {
-      super(_msgID, exArgs, _originalException);
-   }
+    /**
+     * Constructor ReferenceNotInitializedException
+     *
+     * @param msgID
+     * @param exArgs
+     * @param originalException
+     */
+    public ReferenceNotInitializedException(String msgID, Object exArgs[], Exception originalException) {
+        super(msgID, exArgs, originalException);
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
index e81875aa0ce..2dcbb3c28d0 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperties.java
@@ -2,34 +2,34 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.XMLUtils;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
 
-
 /**
  * Handles <ds:SignatureProperties> elements
  * This Element holds {@link SignatureProperty} that contian additional information items
@@ -37,120 +37,112 @@ import org.w3c.dom.Element;
  * for example, data-time stamp, serial number of cryptographic hardware.
  *
  * @author Christian Geuer-Pollmann
- *
  */
 public class SignatureProperties extends SignatureElementProxy {
 
-   /**
-    * Constructor SignatureProperties
-    *
-    * @param doc
-    */
-   public SignatureProperties(Document doc) {
+    /**
+     * Constructor SignatureProperties
+     *
+     * @param doc
+     */
+    public SignatureProperties(Document doc) {
+        super(doc);
 
-      super(doc);
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
+    /**
+     * Constructs {@link SignatureProperties} from {@link Element}
+     * @param element SignatureProperties element
+     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @throws XMLSecurityException
+     */
+    public SignatureProperties(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
 
-   /**
-    * Constructs {@link SignatureProperties} from {@link Element}
-    * @param element SignatureProperties elementt
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @throws XMLSecurityException
-    */
-   public SignatureProperties(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
+        Attr attr = element.getAttributeNodeNS(null, "Id");
+        if (attr != null) {
+            element.setIdAttributeNode(attr, true);
+        }
 
-      Attr attr = element.getAttributeNodeNS(null, "Id");
-      if (attr != null) {
-          element.setIdAttributeNode(attr, true);
-      }
+        int length = getLength();
+        for (int i = 0; i < length; i++) {
+            Element propertyElem =
+                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
+            Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
+            if (propertyAttr != null) {
+                propertyElem.setIdAttributeNode(propertyAttr, true);
+            }
+        }
+    }
 
-      int length = getLength();
-      for (int i = 0; i < length; i++) {
-          Element propertyElem =
-              XMLUtils.selectDsNode(getElement(), Constants._TAG_SIGNATUREPROPERTY, i);
-          Attr propertyAttr = propertyElem.getAttributeNodeNS(null, "Id");
-          if (propertyAttr != null) {
-              propertyElem.setIdAttributeNode(propertyAttr, true);
-          }
-      }
-   }
+    /**
+     * Return the nonnegative number of added SignatureProperty elements.
+     *
+     * @return the number of SignatureProperty elements
+     */
+    public int getLength() {
+        Element[] propertyElems =
+            XMLUtils.selectDsNodes(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY);
 
-   /**
-    * Return the nonnegative number of added SignatureProperty elements.
-    *
-    * @return the number of SignatureProperty elements
-    */
-   public int getLength() {
+        return propertyElems.length;
+    }
 
-         Element[] propertyElems =
-            XMLUtils.selectDsNodes(this._constructionElement,
-                                     Constants._TAG_SIGNATUREPROPERTY
-                                    );
+    /**
+     * Return the ith SignatureProperty. Valid i
+     * values are 0 to {link@ getSize}-1.
+     *
+     * @param i Index of the requested {@link SignatureProperty}
+     * @return the ith SignatureProperty
+     * @throws XMLSignatureException
+     */
+    public SignatureProperty item(int i) throws XMLSignatureException {
+        try {
+            Element propertyElem =
+                XMLUtils.selectDsNode(this.constructionElement, Constants._TAG_SIGNATUREPROPERTY, i);
 
-         return propertyElems.length;
-   }
+            if (propertyElem == null) {
+                return null;
+            }
+            return new SignatureProperty(propertyElem, this.baseURI);
+        } catch (XMLSecurityException ex) {
+            throw new XMLSignatureException("empty", ex);
+        }
+    }
 
-   /**
-    * Return the ith SignatureProperty.  Valid i
-    * values are 0 to {link@ getSize}-1.
-    *
-    * @param i Index of the requested {@link SignatureProperty}
-    * @return the ith SignatureProperty
-    * @throws XMLSignatureException
-    */
-   public SignatureProperty item(int i) throws XMLSignatureException {
-          try {
-         Element propertyElem =
-            XMLUtils.selectDsNode(this._constructionElement,
-                                 Constants._TAG_SIGNATUREPROPERTY,
-                                 i );
+    /**
+     * Sets the Id attribute
+     *
+     * @param Id the Id attribute
+     */
+    public void setId(String Id) {
+        if (Id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, Id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-         if (propertyElem == null) {
-            return null;
-         }
-         return new SignatureProperty(propertyElem, this._baseURI);
-      } catch (XMLSecurityException ex) {
-         throw new XMLSignatureException("empty", ex);
-      }
-   }
+    /**
+     * Returns the Id attribute
+     *
+     * @return the Id attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-   /**
-    * Sets the Id attribute
-    *
-    * @param Id the Id attribute
-    */
-   public void setId(String Id) {
+    /**
+     * Method addSignatureProperty
+     *
+     * @param sp
+     */
+    public void addSignatureProperty(SignatureProperty sp) {
+        this.constructionElement.appendChild(sp.getElement());
+        XMLUtils.addReturnToElement(this.constructionElement);
+    }
 
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
-
-   /**
-    * Returns the Id attribute
-    *
-    * @return the Id attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
-
-   /**
-    * Method addSignatureProperty
-    *
-    * @param sp
-    */
-   public void addSignatureProperty(SignatureProperty sp) {
-      this._constructionElement.appendChild(sp.getElement());
-      XMLUtils.addReturnToElement(this._constructionElement);
-   }
-
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNATUREPROPERTIES;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNATUREPROPERTIES;
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
index 969ee922e1b..3229a0487cc 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignatureProperty.java
@@ -2,27 +2,28 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
 import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import org.w3c.dom.Document;
 import org.w3c.dom.Element;
@@ -37,96 +38,96 @@ import org.w3c.dom.Node;
  */
 public class SignatureProperty extends SignatureElementProxy {
 
-   /**
-    * Constructs{@link SignatureProperty} using specified Target attribute
-    *
-    * @param doc the {@link Document} in which XMLsignature is placed
-    * @param Target the Target attribute references the Signature element to which the property applies SignatureProperty
-    */
-   public SignatureProperty(Document doc, String Target) {
-      this(doc, Target, null);
-   }
+    /**
+     * Constructs{@link SignatureProperty} using specified target attribute
+     *
+     * @param doc the {@link Document} in which XMLsignature is placed
+     * @param target the target attribute references the Signature
+     * element to which the property applies SignatureProperty
+     */
+    public SignatureProperty(Document doc, String target) {
+        this(doc, target, null);
+    }
 
-   /**
-    * Constructs {@link SignatureProperty} using sepcified Target attribute and Id attribute
-    *
-    * @param doc the {@link Document} in which XMLsignature is placed
-    * @param Target the Target attribute references the Signature element to which the property applies
-    * @param Id the Id will be specified by {@link Reference#getURI} in validation
-    */
-   public SignatureProperty(Document doc, String Target, String Id) {
+    /**
+     * Constructs {@link SignatureProperty} using sepcified target attribute and
+     * id attribute
+     *
+     * @param doc the {@link Document} in which XMLsignature is placed
+     * @param target the target attribute references the Signature
+     *  element to which the property applies
+     * @param id the id will be specified by {@link Reference#getURI} in validation
+     */
+    public SignatureProperty(Document doc, String target, String id) {
+        super(doc);
 
-      super(doc);
+        this.setTarget(target);
+        this.setId(id);
+    }
 
-      this.setTarget(Target);
-      this.setId(Id);
-   }
+    /**
+     * Constructs a {@link SignatureProperty} from an {@link Element}
+     * @param element SignatureProperty element
+     * @param BaseURI the URI of the resource where the XML instance was stored
+     * @throws XMLSecurityException
+     */
+    public SignatureProperty(Element element, String BaseURI) throws XMLSecurityException {
+        super(element, BaseURI);
+    }
 
-   /**
-    * Constructs a {@link SignatureProperty} from an {@link Element}
-    * @param element SignatureProperty element
-    * @param BaseURI the URI of the resource where the XML instance was stored
-    * @throws XMLSecurityException
-    */
-   public SignatureProperty(Element element, String BaseURI)
-           throws XMLSecurityException {
-      super(element, BaseURI);
-   }
+    /**
+     *   Sets the id attribute
+     *
+     *   @param id the id attribute
+     */
+    public void setId(String id) {
+        if (id != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id);
+            this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true);
+        }
+    }
 
-   /**
-    *   Sets the Id attribute
-    *
-    *   @param Id the Id attribute
-    */
-   public void setId(String Id) {
+    /**
+     * Returns the id attribute
+     *
+     * @return the id attribute
+     */
+    public String getId() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_ID);
+    }
 
-      if (Id != null) {
-          setLocalIdAttribute(Constants._ATT_ID, Id);
-      }
-   }
+    /**
+     * Sets the target attribute
+     *
+     * @param target the target attribute
+     */
+    public void setTarget(String target) {
+        if (target != null) {
+            this.constructionElement.setAttributeNS(null, Constants._ATT_TARGET, target);
+        }
+    }
 
-   /**
-    * Returns the Id attribute
-    *
-    * @return the Id attribute
-    */
-   public String getId() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_ID);
-   }
+    /**
+     * Returns the target attribute
+     *
+     * @return the target attribute
+     */
+    public String getTarget() {
+        return this.constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
+    }
 
-   /**
-    * Sets the Target attribute
-    *
-    * @param Target the Target attribute
-    */
-   public void setTarget(String Target) {
+    /**
+     * Method appendChild
+     *
+     * @param node
+     * @return the node in this element.
+     */
+    public Node appendChild(Node node) {
+        return this.constructionElement.appendChild(node);
+    }
 
-      if ((Target != null)) {
-         this._constructionElement.setAttributeNS(null, Constants._ATT_TARGET, Target);
-      }
-   }
-
-   /**
-    * Returns the Target attribute
-    *
-    * @return the Target attribute
-    */
-   public String getTarget() {
-      return this._constructionElement.getAttributeNS(null, Constants._ATT_TARGET);
-   }
-
-   /**
-    * Method appendChild
-    *
-    * @param node
-    * @return the node in this element.
-    */
-   public Node appendChild(Node node) {
-      return this._constructionElement.appendChild(node);
-   }
-
-   /** @inheritDoc */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNATUREPROPERTY;
-   }
+    /** @inheritDoc */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNATUREPROPERTY;
+    }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
index f2e04602984..98bfca4a9b2 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/SignedInfo.java
@@ -2,21 +2,23 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
@@ -50,11 +52,11 @@ import org.xml.sax.SAXException;
  */
 public class SignedInfo extends Manifest {
 
-    /** Field _signatureAlgorithm */
-    private SignatureAlgorithm _signatureAlgorithm = null;
+    /** Field signatureAlgorithm */
+    private SignatureAlgorithm signatureAlgorithm = null;
 
-    /** Field _c14nizedBytes           */
-    private byte[] _c14nizedBytes = null;
+    /** Field c14nizedBytes           */
+    private byte[] c14nizedBytes = null;
 
     private Element c14nMethod;
     private Element signatureMethod;
@@ -83,9 +85,9 @@ public class SignedInfo extends Manifest {
      *    Canonicalization method
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, String signatureMethodURI,
-        String canonicalizationMethodURI)
-              throws XMLSecurityException {
+    public SignedInfo(
+        Document doc, String signatureMethodURI, String canonicalizationMethodURI
+    ) throws XMLSecurityException {
         this(doc, signatureMethodURI, 0, canonicalizationMethodURI);
     }
 
@@ -100,31 +102,29 @@ public class SignedInfo extends Manifest {
      *    Canonicalization method
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, String signatureMethodURI,
-        int hMACOutputLength, String canonicalizationMethodURI)
-              throws XMLSecurityException {
-
+    public SignedInfo(
+        Document doc, String signatureMethodURI,
+        int hMACOutputLength, String canonicalizationMethodURI
+    ) throws XMLSecurityException {
         super(doc);
 
-        c14nMethod = XMLUtils.createElementInSignatureSpace(this._doc,
-                                Constants._TAG_CANONICALIZATIONMETHOD);
+        c14nMethod =
+            XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_CANONICALIZATIONMETHOD);
 
-        c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM,
-                                  canonicalizationMethodURI);
-        this._constructionElement.appendChild(c14nMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        c14nMethod.setAttributeNS(null, Constants._ATT_ALGORITHM, canonicalizationMethodURI);
+        this.constructionElement.appendChild(c14nMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
         if (hMACOutputLength > 0) {
-            this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
-                    signatureMethodURI, hMACOutputLength);
+            this.signatureAlgorithm =
+                new SignatureAlgorithm(this.doc, signatureMethodURI, hMACOutputLength);
         } else {
-            this._signatureAlgorithm = new SignatureAlgorithm(this._doc,
-                    signatureMethodURI);
+            this.signatureAlgorithm = new SignatureAlgorithm(this.doc, signatureMethodURI);
         }
 
-        signatureMethod = this._signatureAlgorithm.getElement();
-        this._constructionElement.appendChild(signatureMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        signatureMethod = this.signatureAlgorithm.getElement();
+        this.constructionElement.appendChild(signatureMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -133,22 +133,22 @@ public class SignedInfo extends Manifest {
      * @param canonicalizationMethodElem
      * @throws XMLSecurityException
      */
-    public SignedInfo(Document doc, Element signatureMethodElem,
-        Element canonicalizationMethodElem) throws XMLSecurityException {
-
+    public SignedInfo(
+        Document doc, Element signatureMethodElem, Element canonicalizationMethodElem
+    ) throws XMLSecurityException {
         super(doc);
         // Check this?
         this.c14nMethod = canonicalizationMethodElem;
-        this._constructionElement.appendChild(c14nMethod);
-        XMLUtils.addReturnToElement(this._constructionElement);
+        this.constructionElement.appendChild(c14nMethod);
+        XMLUtils.addReturnToElement(this.constructionElement);
 
-        this._signatureAlgorithm =
+        this.signatureAlgorithm =
             new SignatureAlgorithm(signatureMethodElem, null);
 
-        signatureMethod = this._signatureAlgorithm.getElement();
-        this._constructionElement.appendChild(signatureMethod);
+        signatureMethod = this.signatureAlgorithm.getElement();
+        this.constructionElement.appendChild(signatureMethod);
 
-        XMLUtils.addReturnToElement(this._constructionElement);
+        XMLUtils.addReturnToElement(this.constructionElement);
     }
 
     /**
@@ -157,48 +157,76 @@ public class SignedInfo extends Manifest {
      * @param element SignedInfo
      * @param baseURI the URI of the resource where the XML instance was stored
      * @throws XMLSecurityException
-     * @see Question
-     * @see Answer
+     * @see 
+     * Question
+     * @see 
+     * Answer
      */
-    public SignedInfo(Element element, String baseURI)
-           throws XMLSecurityException {
+    public SignedInfo(Element element, String baseURI) throws XMLSecurityException {
+        this(element, baseURI, false);
+    }
 
+    /**
+     * Build a {@link SignedInfo} from an {@link Element}
+     *
+     * @param element SignedInfo
+     * @param baseURI the URI of the resource where the XML instance was stored
+     * @param secureValidation whether secure validation is enabled or not
+     * @throws XMLSecurityException
+     * @see 
+     * Question
+     * @see 
+     * Answer
+     */
+    public SignedInfo(
+        Element element, String baseURI, boolean secureValidation
+    ) throws XMLSecurityException {
         // Parse the Reference children and Id attribute in the Manifest
-        super(element, baseURI);
+        super(reparseSignedInfoElem(element), baseURI, secureValidation);
 
-        /* canonicalize ds:SignedInfo, reparse it into a new document
+        c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
+        signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
+        this.signatureAlgorithm =
+            new SignatureAlgorithm(signatureMethod, this.getBaseURI(), secureValidation);
+    }
+
+    private static Element reparseSignedInfoElem(Element element)
+        throws XMLSecurityException {
+        /*
+         * If a custom canonicalizationMethod is used, canonicalize
+         * ds:SignedInfo, reparse it into a new document
          * and replace the original not-canonicalized ds:SignedInfo by
          * the re-parsed canonicalized one.
          */
-        c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
-        String c14nMethodURI = this.getCanonicalizationMethodURI();
+        Element c14nMethod = XMLUtils.getNextElement(element.getFirstChild());
+        String c14nMethodURI =
+            c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
         if (!(c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) ||
-              c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS))) {
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS) ||
+            c14nMethodURI.equals(Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS))) {
             // the c14n is not a secure one and can rewrite the URIs or like
-            // that reparse the SignedInfo to be sure
+            // so reparse the SignedInfo to be sure
             try {
                 Canonicalizer c14nizer =
-                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+                    Canonicalizer.getInstance(c14nMethodURI);
 
-                this._c14nizedBytes =
-                    c14nizer.canonicalizeSubtree(this._constructionElement);
+                byte[] c14nizedBytes = c14nizer.canonicalizeSubtree(element);
                 javax.xml.parsers.DocumentBuilderFactory dbf =
                     javax.xml.parsers.DocumentBuilderFactory.newInstance();
                 dbf.setNamespaceAware(true);
-                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,
-                               Boolean.TRUE);
+                dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
                 javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
                 Document newdoc =
-                    db.parse(new ByteArrayInputStream(this._c14nizedBytes));
+                    db.parse(new ByteArrayInputStream(c14nizedBytes));
                 Node imported =
-                    this._doc.importNode(newdoc.getDocumentElement(), true);
+                    element.getOwnerDocument().importNode(newdoc.getDocumentElement(), true);
 
-                this._constructionElement.getParentNode().replaceChild(imported,
-                    this._constructionElement);
+                element.getParentNode().replaceChild(imported, element);
 
-                this._constructionElement = (Element) imported;
+                return (Element) imported;
             } catch (ParserConfigurationException ex) {
                 throw new XMLSecurityException("empty", ex);
             } catch (IOException ex) {
@@ -207,184 +235,163 @@ public class SignedInfo extends Manifest {
                 throw new XMLSecurityException("empty", ex);
             }
         }
-        signatureMethod = XMLUtils.getNextElement(c14nMethod.getNextSibling());
-        this._signatureAlgorithm =
-            new SignatureAlgorithm(signatureMethod, this.getBaseURI());
+        return element;
     }
 
-   /**
-    * Tests core validation process
-    *
-    * @return true if verification was successful
-    * @throws MissingResourceFailureException
-    * @throws XMLSecurityException
-    */
-   public boolean verify()
-           throws MissingResourceFailureException, XMLSecurityException {
-      return super.verifyReferences(false);
-   }
-
-   /**
-    * Tests core validation process
-    *
-    * @param followManifests defines whether the verification process has to verify referenced ds:Manifests, too
-    * @return true if verification was successful
-    * @throws MissingResourceFailureException
-    * @throws XMLSecurityException
-    */
-   public boolean verify(boolean followManifests)
-           throws MissingResourceFailureException, XMLSecurityException {
-      return super.verifyReferences(followManifests);
-   }
-
-   /**
-    * Returns getCanonicalizedOctetStream
-    *
-    * @return the canonicalization result octedt stream of SignedInfo element
-    * @throws CanonicalizationException
-    * @throws InvalidCanonicalizerException
-    * @throws XMLSecurityException
-    */
-   public byte[] getCanonicalizedOctetStream()
-           throws CanonicalizationException, InvalidCanonicalizerException,
-                 XMLSecurityException {
-
-      if ((this._c14nizedBytes == null)
-              /*&& (this._state == ElementProxy.MODE_SIGN)*/) {
-         Canonicalizer c14nizer =
-            Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
-
-         this._c14nizedBytes =
-            c14nizer.canonicalizeSubtree(this._constructionElement);
-      }
-
-      // make defensive copy
-      byte[] output = new byte[this._c14nizedBytes.length];
-
-      System.arraycopy(this._c14nizedBytes, 0, output, 0, output.length);
-
-      return output;
-   }
-
-   /**
-    *  Output the C14n stream to the give outputstream.
-    * @param os
-    * @throws CanonicalizationException
-    * @throws InvalidCanonicalizerException
-    * @throws XMLSecurityException
-    */
-   public void signInOctectStream(OutputStream os)
-       throws CanonicalizationException, InvalidCanonicalizerException,
-           XMLSecurityException {
-
-        if ((this._c14nizedBytes == null)) {
-       Canonicalizer c14nizer =
-          Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
-       c14nizer.setWriter(os);
-       String inclusiveNamespaces = this.getInclusiveNamespaces();
-
-       if(inclusiveNamespaces == null)
-        c14nizer.canonicalizeSubtree(this._constructionElement);
-       else
-        c14nizer.canonicalizeSubtree(this._constructionElement, inclusiveNamespaces);
-    } else {
-        try {
-                        os.write(this._c14nizedBytes);
-                } catch (IOException e) {
-                        throw new RuntimeException(""+e);
-                }
+    /**
+     * Tests core validation process
+     *
+     * @return true if verification was successful
+     * @throws MissingResourceFailureException
+     * @throws XMLSecurityException
+     */
+    public boolean verify()
+        throws MissingResourceFailureException, XMLSecurityException {
+        return super.verifyReferences(false);
     }
-   }
 
-   /**
-    * Returns the Canonicalization method URI
-    *
-    * @return the Canonicalization method URI
-    */
-   public String getCanonicalizationMethodURI() {
+    /**
+     * Tests core validation process
+     *
+     * @param followManifests defines whether the verification process has to verify referenced ds:Manifests, too
+     * @return true if verification was successful
+     * @throws MissingResourceFailureException
+     * @throws XMLSecurityException
+     */
+    public boolean verify(boolean followManifests)
+        throws MissingResourceFailureException, XMLSecurityException {
+        return super.verifyReferences(followManifests);
+    }
 
+    /**
+     * Returns getCanonicalizedOctetStream
+     *
+     * @return the canonicalization result octet stream of SignedInfo element
+     * @throws CanonicalizationException
+     * @throws InvalidCanonicalizerException
+     * @throws XMLSecurityException
+     */
+    public byte[] getCanonicalizedOctetStream()
+        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
+        if (this.c14nizedBytes == null) {
+            Canonicalizer c14nizer =
+                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
 
-     return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
-   }
+            this.c14nizedBytes =
+                c14nizer.canonicalizeSubtree(this.constructionElement);
+        }
 
-   /**
-    * Returns the Signature method URI
-    *
-    * @return the Signature method URI
-    */
-   public String getSignatureMethodURI() {
+        // make defensive copy
+        return this.c14nizedBytes.clone();
+    }
 
-      Element signatureElement = this.getSignatureMethodElement();
+    /**
+     * Output the C14n stream to the given OutputStream.
+     * @param os
+     * @throws CanonicalizationException
+     * @throws InvalidCanonicalizerException
+     * @throws XMLSecurityException
+     */
+    public void signInOctetStream(OutputStream os)
+        throws CanonicalizationException, InvalidCanonicalizerException, XMLSecurityException {
+        if (this.c14nizedBytes == null) {
+            Canonicalizer c14nizer =
+                Canonicalizer.getInstance(this.getCanonicalizationMethodURI());
+            c14nizer.setWriter(os);
+            String inclusiveNamespaces = this.getInclusiveNamespaces();
 
-      if (signatureElement != null) {
-         return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
-      }
+            if (inclusiveNamespaces == null) {
+                c14nizer.canonicalizeSubtree(this.constructionElement);
+            } else {
+                c14nizer.canonicalizeSubtree(this.constructionElement, inclusiveNamespaces);
+            }
+        } else {
+            try {
+                os.write(this.c14nizedBytes);
+            } catch (IOException e) {
+                throw new RuntimeException(e);
+            }
+        }
+    }
 
-      return null;
-   }
+    /**
+     * Returns the Canonicalization method URI
+     *
+     * @return the Canonicalization method URI
+     */
+    public String getCanonicalizationMethodURI() {
+        return c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+    }
 
-   /**
-    * Method getSignatureMethodElement
-    * @return gets The SignatureMethod Node.
-    *
-    */
-   public Element getSignatureMethodElement() {
-           return signatureMethod;
-   }
+    /**
+     * Returns the Signature method URI
+     *
+     * @return the Signature method URI
+     */
+    public String getSignatureMethodURI() {
+        Element signatureElement = this.getSignatureMethodElement();
 
-   /**
-    * Creates a SecretKey for the appropriate Mac algorithm based on a
-    * byte[] array password.
-    *
-    * @param secretKeyBytes
-    * @return the secret key for the SignedInfo element.
-    */
-   public SecretKey createSecretKey(byte[] secretKeyBytes)
-   {
+        if (signatureElement != null) {
+            return signatureElement.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        }
 
-      return new SecretKeySpec(secretKeyBytes,
-                               this._signatureAlgorithm
-                                  .getJCEAlgorithmString());
-   }
+        return null;
+    }
 
-   protected SignatureAlgorithm getSignatureAlgorithm() {
-           return _signatureAlgorithm;
-   }
-   /**
-    * Method getBaseLocalName
-    * @inheritDoc
-    *
-    */
-   public String getBaseLocalName() {
-      return Constants._TAG_SIGNEDINFO;
-   }
+    /**
+     * Method getSignatureMethodElement
+     * @return returns the SignatureMethod Element
+     *
+     */
+    public Element getSignatureMethodElement() {
+        return signatureMethod;
+    }
 
-   public String getInclusiveNamespaces() {
+    /**
+     * Creates a SecretKey for the appropriate Mac algorithm based on a
+     * byte[] array password.
+     *
+     * @param secretKeyBytes
+     * @return the secret key for the SignedInfo element.
+     */
+    public SecretKey createSecretKey(byte[] secretKeyBytes) {
+        return new SecretKeySpec(secretKeyBytes, this.signatureAlgorithm.getJCEAlgorithmString());
+    }
 
+    protected SignatureAlgorithm getSignatureAlgorithm() {
+        return signatureAlgorithm;
+    }
 
+    /**
+     * Method getBaseLocalName
+     * @inheritDoc
+     *
+     */
+    public String getBaseLocalName() {
+        return Constants._TAG_SIGNEDINFO;
+    }
 
-     String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
-     if(!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
-                        c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
+    public String getInclusiveNamespaces() {
+        String c14nMethodURI = c14nMethod.getAttributeNS(null, Constants._ATT_ALGORITHM);
+        if (!(c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#") ||
+            c14nMethodURI.equals("http://www.w3.org/2001/10/xml-exc-c14n#WithComments"))) {
+            return null;
+        }
+
+        Element inclusiveElement = XMLUtils.getNextElement(c14nMethod.getFirstChild());
+
+        if (inclusiveElement != null) {
+            try {
+                String inclusiveNamespaces =
+                    new InclusiveNamespaces(
+                        inclusiveElement,
+                        InclusiveNamespaces.ExclusiveCanonicalizationNamespace
+                    ).getInclusiveNamespaces();
+                return inclusiveNamespaces;
+            } catch (XMLSecurityException e) {
                 return null;
             }
-
-     Element inclusiveElement = XMLUtils.getNextElement(
-                 c14nMethod.getFirstChild());
-
-     if(inclusiveElement != null)
-     {
-         try
-         {
-             String inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement,
-                         InclusiveNamespaces.ExclusiveCanonicalizationNamespace).getInclusiveNamespaces();
-             return inclusiveNamespaces;
-         }
-         catch (XMLSecurityException e)
-         {
-             return null;
-         }
-     }
-     return null;
+        }
+        return null;
     }
 }
diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
index a1a69ddb1d4..490f184c57f 100644
--- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
+++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignature.java
@@ -2,26 +2,26 @@
  * reserved comment block
  * DO NOT REMOVE OR ALTER!
  */
-/*
- * Copyright  1999-2004 The Apache Software Foundation.
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
  *
- *  Licensed under the Apache License, Version 2.0 (the "License");
- *  you may not use this file except in compliance with the License.
- *  You may obtain a copy of the License at
- *
- *      http://www.apache.org/licenses/LICENSE-2.0
- *
- *  Unless required by applicable law or agreed to in writing, software
- *  distributed under the License is distributed on an "AS IS" BASIS,
- *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- *  See the License for the specific language governing permissions and
- *  limitations under the License.
+ * http://www.apache.org/licenses/LICENSE-2.0
  *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
  */
 package com.sun.org.apache.xml.internal.security.signature;
 
-
-
 import java.io.IOException;
 import java.io.OutputStream;
 import java.security.Key;
@@ -42,7 +42,6 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms;
 import com.sun.org.apache.xml.internal.security.utils.Base64;
 import com.sun.org.apache.xml.internal.security.utils.Constants;
 import com.sun.org.apache.xml.internal.security.utils.I18n;
-import com.sun.org.apache.xml.internal.security.utils.IdResolver;
 import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy;
 import com.sun.org.apache.xml.internal.security.utils.SignerOutputStream;
 import com.sun.org.apache.xml.internal.security.utils.UnsyncBufferedOutputStream;
@@ -56,7 +55,6 @@ import org.w3c.dom.Node;
 import org.w3c.dom.NodeList;
 import org.w3c.dom.Text;
 
-
 /**
  * Handles <ds:Signature> elements.
  * This is the main class that deals with creating and verifying signatures.
@@ -64,7 +62,7 @@ import org.w3c.dom.Text;
  * 

There are 2 types of constructors for this class. The ones that take a * document, baseURI and 1 or more Java Objects. This is mostly used for * signing purposes. - * The other constructor is the one that takes a DOM Element and a BaseURI. + * The other constructor is the one that takes a DOM Element and a baseURI. * This is used mostly with for verifying, when you have a SignatureElement. * * There are a few different types of methods: @@ -76,329 +74,391 @@ import org.w3c.dom.Text; * ObjectContainer during signing. *

  • sign and checkSignatureValue methods are used to sign and validate the * signature.
  • - * - * @author $Author: mullan $ */ public final class XMLSignature extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** MAC - Required HMAC-SHA1 */ + public static final String ALGO_ID_MAC_HMAC_SHA1 = + Constants.SignatureSpecNS + "hmac-sha1"; + + /** Signature - Required DSAwithSHA1 (DSS) */ + public static final String ALGO_ID_SIGNATURE_DSA = + Constants.SignatureSpecNS + "dsa-sha1"; + + /** Signature - Recommended RSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_RSA = + Constants.SignatureSpecNS + "rsa-sha1"; + + /** Signature - Recommended RSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA1 = + Constants.SignatureSpecNS + "rsa-sha1"; + + /** Signature - NOT Recommended RSAwithMD5 */ + public static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = + Constants.MoreAlgorithmsSpecNS + "rsa-md5"; + + /** Signature - Optional RSAwithRIPEMD160 */ + public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 = + Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160"; + + /** Signature - Optional RSAwithSHA256 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA256 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha256"; + + /** Signature - Optional RSAwithSHA384 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA384 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha384"; + + /** Signature - Optional RSAwithSHA512 */ + public static final String ALGO_ID_SIGNATURE_RSA_SHA512 = + Constants.MoreAlgorithmsSpecNS + "rsa-sha512"; + + /** HMAC - NOT Recommended HMAC-MD5 */ + public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = + Constants.MoreAlgorithmsSpecNS + "hmac-md5"; + + /** HMAC - Optional HMAC-RIPEMD160 */ + public static final String ALGO_ID_MAC_HMAC_RIPEMD160 = + Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160"; + + /** HMAC - Optional HMAC-SHA256 */ + public static final String ALGO_ID_MAC_HMAC_SHA256 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha256"; + + /** HMAC - Optional HMAC-SHA284 */ + public static final String ALGO_ID_MAC_HMAC_SHA384 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha384"; + + /** HMAC - Optional HMAC-SHA512 */ + public static final String ALGO_ID_MAC_HMAC_SHA512 = + Constants.MoreAlgorithmsSpecNS + "hmac-sha512"; + + /**Signature - Optional ECDSAwithSHA1 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; + + /**Signature - Optional ECDSAwithSHA256 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA256 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha256"; + + /**Signature - Optional ECDSAwithSHA384 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA384 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha384"; + + /**Signature - Optional ECDSAwithSHA512 */ + public static final String ALGO_ID_SIGNATURE_ECDSA_SHA512 = + "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha512"; + + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(XMLSignature.class.getName()); - //J- - /** MAC - Required HMAC-SHA1 */ - public static final String ALGO_ID_MAC_HMAC_SHA1 = Constants.SignatureSpecNS + "hmac-sha1"; + /** ds:Signature.ds:SignedInfo element */ + private SignedInfo signedInfo; - /** Signature - Required DSAwithSHA1 (DSS) */ - public static final String ALGO_ID_SIGNATURE_DSA = Constants.SignatureSpecNS + "dsa-sha1"; + /** ds:Signature.ds:KeyInfo */ + private KeyInfo keyInfo; - /** Signature - Recommended RSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_RSA = Constants.SignatureSpecNS + "rsa-sha1"; - /** Signature - Recommended RSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA1 = Constants.SignatureSpecNS + "rsa-sha1"; - /** Signature - NOT Recommended RSAwithMD5 */ - public static final String ALGO_ID_SIGNATURE_NOT_RECOMMENDED_RSA_MD5 = Constants.MoreAlgorithmsSpecNS + "rsa-md5"; - /** Signature - Optional RSAwithRIPEMD160 */ - public static final String ALGO_ID_SIGNATURE_RSA_RIPEMD160 = Constants.MoreAlgorithmsSpecNS + "rsa-ripemd160"; - /** Signature - Optional RSAwithSHA256 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA256 = Constants.MoreAlgorithmsSpecNS + "rsa-sha256"; - /** Signature - Optional RSAwithSHA384 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA384 = Constants.MoreAlgorithmsSpecNS + "rsa-sha384"; - /** Signature - Optional RSAwithSHA512 */ - public static final String ALGO_ID_SIGNATURE_RSA_SHA512 = Constants.MoreAlgorithmsSpecNS + "rsa-sha512"; + /** + * Checking the digests in References in a Signature are mandatory, but for + * References inside a Manifest it is application specific. This boolean is + * to indicate that the References inside Manifests should be validated. + */ + private boolean followManifestsDuringValidation = false; - /** HMAC - NOT Recommended HMAC-MD5 */ - public static final String ALGO_ID_MAC_HMAC_NOT_RECOMMENDED_MD5 = Constants.MoreAlgorithmsSpecNS + "hmac-md5"; - /** HMAC - Optional HMAC-RIPEMD160 */ - public static final String ALGO_ID_MAC_HMAC_RIPEMD160 = Constants.MoreAlgorithmsSpecNS + "hmac-ripemd160"; - /** HMAC - Optional HMAC-SHA256 */ - public static final String ALGO_ID_MAC_HMAC_SHA256 = Constants.MoreAlgorithmsSpecNS + "hmac-sha256"; - /** HMAC - Optional HMAC-SHA284 */ - public static final String ALGO_ID_MAC_HMAC_SHA384 = Constants.MoreAlgorithmsSpecNS + "hmac-sha384"; - /** HMAC - Optional HMAC-SHA512 */ - public static final String ALGO_ID_MAC_HMAC_SHA512 = Constants.MoreAlgorithmsSpecNS + "hmac-sha512"; - /**Signature - Optional ECDSAwithSHA1 */ - public static final String ALGO_ID_SIGNATURE_ECDSA_SHA1 = "http://www.w3.org/2001/04/xmldsig-more#ecdsa-sha1"; + private Element signatureValueElement; + private static final int MODE_SIGN = 0; + private static final int MODE_VERIFY = 1; + private int state = MODE_SIGN; - //J+ + /** + * This creates a new ds:Signature Element and adds an empty + * ds:SignedInfo. + * The ds:SignedInfo is initialized with the specified Signature + * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED + * by the spec. This method's main use is for creating a new signature. + * + * @param doc Document in which the signature will be appended after creation. + * @param baseURI URI to be used as context for all relative URIs. + * @param signatureMethodURI signature algorithm to use. + * @throws XMLSecurityException + */ + public XMLSignature(Document doc, String baseURI, String signatureMethodURI) + throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, 0, Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); + } - /** ds:Signature.ds:SignedInfo element */ - private SignedInfo _signedInfo = null; + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @param signatureMethodURI the Signature method to be used. + * @param hmacOutputLength + * @throws XMLSecurityException + */ + public XMLSignature(Document doc, String baseURI, String signatureMethodURI, + int hmacOutputLength) throws XMLSecurityException { + this( + doc, baseURI, signatureMethodURI, hmacOutputLength, + Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS + ); + } - /** ds:Signature.ds:KeyInfo */ - private KeyInfo _keyInfo = null; + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @param signatureMethodURI the Signature method to be used. + * @param canonicalizationMethodURI the canonicalization algorithm to be + * used to c14nize the SignedInfo element. + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + String signatureMethodURI, + String canonicalizationMethodURI + ) throws XMLSecurityException { + this(doc, baseURI, signatureMethodURI, 0, canonicalizationMethodURI); + } - /** - * Checking the digests in References in a Signature are mandatory, but for - * References inside a Manifest it is application specific. This boolean is - * to indicate that the References inside Manifests should be validated. - */ - private boolean _followManifestsDuringValidation = false; + /** + * Constructor XMLSignature + * + * @param doc + * @param baseURI + * @param signatureMethodURI + * @param hmacOutputLength + * @param canonicalizationMethodURI + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + String signatureMethodURI, + int hmacOutputLength, + String canonicalizationMethodURI + ) throws XMLSecurityException { + super(doc); -private Element signatureValueElement; + String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); + if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS + ); + } else { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS + ); + } + XMLUtils.addReturnToElement(this.constructionElement); - /** - * This creates a new ds:Signature Element and adds an empty - * ds:SignedInfo. - * The ds:SignedInfo is initialized with the specified Signature - * algorithm and Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS which is REQUIRED - * by the spec. This method's main use is for creating a new signature. - * - * @param doc Document in which the signature will be appended after creation. - * @param BaseURI URI to be used as context for all relative URIs. - * @param SignatureMethodURI signature algorithm to use. - * @throws XMLSecurityException - */ - public XMLSignature(Document doc, String BaseURI, String SignatureMethodURI) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, 0, - Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); - } + this.baseURI = baseURI; + this.signedInfo = + new SignedInfo( + this.doc, signatureMethodURI, hmacOutputLength, canonicalizationMethodURI + ); - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @param SignatureMethodURI the Signature method to be used. - * @param HMACOutputLength - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, HMACOutputLength, - Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS); - } + this.constructionElement.appendChild(this.signedInfo.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @param SignatureMethodURI the Signature method to be used. - * @param CanonicalizationMethodURI the canonicalization algorithm to be used to c14nize the SignedInfo element. - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, String SignatureMethodURI, String CanonicalizationMethodURI) - throws XMLSecurityException { - this(doc, BaseURI, SignatureMethodURI, 0, CanonicalizationMethodURI); - } + // create an empty SignatureValue; this is filled by setSignatureValueElement + signatureValueElement = + XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE); - /** - * Constructor XMLSignature - * - * @param doc - * @param BaseURI - * @param SignatureMethodURI - * @param HMACOutputLength - * @param CanonicalizationMethodURI - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, String SignatureMethodURI, int HMACOutputLength, String CanonicalizationMethodURI) - throws XMLSecurityException { + this.constructionElement.appendChild(signatureValueElement); + XMLUtils.addReturnToElement(this.constructionElement); + } - super(doc); + /** + * Creates a XMLSignature in a Document + * @param doc + * @param baseURI + * @param SignatureMethodElem + * @param CanonicalizationMethodElem + * @throws XMLSecurityException + */ + public XMLSignature( + Document doc, + String baseURI, + Element SignatureMethodElem, + Element CanonicalizationMethodElem + ) throws XMLSecurityException { + super(doc); - String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); - if (xmlnsDsPrefix == null) { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS); - } else { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS); - } - XMLUtils.addReturnToElement(this._constructionElement); + String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); + if (xmlnsDsPrefix == null || xmlnsDsPrefix.length() == 0) { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS + ); + } else { + this.constructionElement.setAttributeNS( + Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS + ); + } + XMLUtils.addReturnToElement(this.constructionElement); - this._baseURI = BaseURI; - this._signedInfo = new SignedInfo(this._doc, SignatureMethodURI, - HMACOutputLength, - CanonicalizationMethodURI); + this.baseURI = baseURI; + this.signedInfo = + new SignedInfo(this.doc, SignatureMethodElem, CanonicalizationMethodElem); - this._constructionElement.appendChild(this._signedInfo.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(this.signedInfo.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); - // create an empty SignatureValue; this is filled by setSignatureValueElement - signatureValueElement = - XMLUtils.createElementInSignatureSpace(this._doc, - Constants._TAG_SIGNATUREVALUE); + // create an empty SignatureValue; this is filled by setSignatureValueElement + signatureValueElement = + XMLUtils.createElementInSignatureSpace(this.doc, Constants._TAG_SIGNATUREVALUE); - this._constructionElement.appendChild(signatureValueElement); - XMLUtils.addReturnToElement(this._constructionElement); - } - /** - * Creates a XMLSignature in a Document - * @param doc - * @param BaseURI - * @param SignatureMethodElem - * @param CanonicalizationMethodElem - * @throws XMLSecurityException - */ - public XMLSignature( - Document doc, String BaseURI, Element SignatureMethodElem, Element CanonicalizationMethodElem) - throws XMLSecurityException { + this.constructionElement.appendChild(signatureValueElement); + XMLUtils.addReturnToElement(this.constructionElement); + } - super(doc); + /** + * This will parse the element and construct the Java Objects. + * That will allow a user to validate the signature. + * + * @param element ds:Signature element that contains the whole signature + * @param baseURI URI to be prepended to all relative URIs + * @throws XMLSecurityException + * @throws XMLSignatureException if the signature is badly formatted + */ + public XMLSignature(Element element, String baseURI) + throws XMLSignatureException, XMLSecurityException { + this(element, baseURI, false); + } - String xmlnsDsPrefix = getDefaultPrefix(Constants.SignatureSpecNS); - if (xmlnsDsPrefix == null) { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns", Constants.SignatureSpecNS); - } else { - this._constructionElement.setAttributeNS - (Constants.NamespaceSpecNS, "xmlns:" + xmlnsDsPrefix, Constants.SignatureSpecNS); - } - XMLUtils.addReturnToElement(this._constructionElement); + /** + * This will parse the element and construct the Java Objects. + * That will allow a user to validate the signature. + * + * @param element ds:Signature element that contains the whole signature + * @param baseURI URI to be prepended to all relative URIs + * @param secureValidation whether secure secureValidation is enabled or not + * @throws XMLSecurityException + * @throws XMLSignatureException if the signature is badly formatted + */ + public XMLSignature(Element element, String baseURI, boolean secureValidation) + throws XMLSignatureException, XMLSecurityException { + super(element, baseURI); - this._baseURI = BaseURI; - this._signedInfo = new SignedInfo(this._doc, SignatureMethodElem, CanonicalizationMethodElem); + // check out SignedInfo child + Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); - this._constructionElement.appendChild(this._signedInfo.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); + // check to see if it is there + if (signedInfoElem == null) { + Object exArgs[] = { Constants._TAG_SIGNEDINFO, Constants._TAG_SIGNATURE }; + throw new XMLSignatureException("xml.WrongContent", exArgs); + } - // create an empty SignatureValue; this is filled by setSignatureValueElement - signatureValueElement = - XMLUtils.createElementInSignatureSpace(this._doc, - Constants._TAG_SIGNATUREVALUE); + // create a SignedInfo object from that element + this.signedInfo = new SignedInfo(signedInfoElem, baseURI, secureValidation); + // get signedInfoElem again in case it has changed + signedInfoElem = XMLUtils.getNextElement(element.getFirstChild()); - this._constructionElement.appendChild(signatureValueElement); - XMLUtils.addReturnToElement(this._constructionElement); - } + // check out SignatureValue child + this.signatureValueElement = + XMLUtils.getNextElement(signedInfoElem.getNextSibling()); - /** - * This will parse the element and construct the Java Objects. - * That will allow a user to validate the signature. - * - * @param element ds:Signature element that contains the whole signature - * @param BaseURI URI to be prepended to all relative URIs - * @throws XMLSecurityException - * @throws XMLSignatureException if the signature is badly formatted - */ - public XMLSignature(Element element, String BaseURI) - throws XMLSignatureException, XMLSecurityException { + // check to see if it exists + if (signatureValueElement == null) { + Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, Constants._TAG_SIGNATURE }; + throw new XMLSignatureException("xml.WrongContent", exArgs); + } + Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id"); + if (signatureValueAttr != null) { + signatureValueElement.setIdAttributeNode(signatureValueAttr, true); + } - super(element, BaseURI); + // + Element keyInfoElem = + XMLUtils.getNextElement(signatureValueElement.getNextSibling()); - // check out SignedInfo child - Element signedInfoElem = XMLUtils.getNextElement(element.getFirstChild());// XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - //Constants._TAG_SIGNEDINFO,0); + // If it exists use it, but it's not mandatory + if (keyInfoElem != null + && keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) + && keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) { + this.keyInfo = new KeyInfo(keyInfoElem, baseURI); + this.keyInfo.setSecureValidation(secureValidation); + } - // check to see if it is there - if (signedInfoElem == null) { - Object exArgs[] = { Constants._TAG_SIGNEDINFO, - Constants._TAG_SIGNATURE }; + // + Element objectElem = + XMLUtils.getNextElement(signatureValueElement.getNextSibling()); + while (objectElem != null) { + Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id"); + if (objectAttr != null) { + objectElem.setIdAttributeNode(objectAttr, true); + } - throw new XMLSignatureException("xml.WrongContent", exArgs); - } + NodeList nodes = objectElem.getChildNodes(); + int length = nodes.getLength(); + // Register Ids of the Object child elements + for (int i = 0; i < length; i++) { + Node child = nodes.item(i); + if (child.getNodeType() == Node.ELEMENT_NODE) { + Element childElem = (Element)child; + String tag = childElem.getLocalName(); + if (tag.equals("Manifest")) { + new Manifest(childElem, baseURI); + } else if (tag.equals("SignatureProperties")) { + new SignatureProperties(childElem, baseURI); + } + } + } - // create a SignedInfo object from that element - this._signedInfo = new SignedInfo(signedInfoElem, BaseURI); + objectElem = XMLUtils.getNextElement(objectElem.getNextSibling()); + } - // check out SignatureValue child - this.signatureValueElement =XMLUtils.getNextElement(signedInfoElem.getNextSibling()); //XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - // Constants._TAG_SIGNATUREVALUE,0); + this.state = MODE_VERIFY; + } - // check to see if it exists - if (signatureValueElement == null) { - Object exArgs[] = { Constants._TAG_SIGNATUREVALUE, - Constants._TAG_SIGNATURE }; + /** + * Sets the Id attribute + * + * @param id Id value for the id attribute on the Signature Element + */ + public void setId(String id) { + if (id != null) { + this.constructionElement.setAttributeNS(null, Constants._ATT_ID, id); + this.constructionElement.setIdAttributeNS(null, Constants._ATT_ID, true); + } + } - throw new XMLSignatureException("xml.WrongContent", exArgs); - } - Attr signatureValueAttr = signatureValueElement.getAttributeNodeNS(null, "Id"); - if (signatureValueAttr != null) { - signatureValueElement.setIdAttributeNode(signatureValueAttr, true); - } + /** + * Returns the Id attribute + * + * @return the Id attribute + */ + public String getId() { + return this.constructionElement.getAttributeNS(null, Constants._ATT_ID); + } - // - Element keyInfoElem = XMLUtils.getNextElement(signatureValueElement.getNextSibling());//XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - // Constants._TAG_KEYINFO,0); + /** + * Returns the completely parsed SignedInfo object. + * + * @return the completely parsed SignedInfo object. + */ + public SignedInfo getSignedInfo() { + return this.signedInfo; + } - // If it exists use it, but it's not mandatory - if ((keyInfoElem != null) && (keyInfoElem.getNamespaceURI().equals(Constants.SignatureSpecNS) && - keyInfoElem.getLocalName().equals(Constants._TAG_KEYINFO)) ) { - this._keyInfo = new KeyInfo(keyInfoElem, BaseURI); - } - - // - Element objectElem = - XMLUtils.getNextElement(signatureValueElement.getNextSibling()); - while (objectElem != null) { - Attr objectAttr = objectElem.getAttributeNodeNS(null, "Id"); - if (objectAttr != null) { - objectElem.setIdAttributeNode(objectAttr, true); - } - - NodeList nodes = objectElem.getChildNodes(); - int length = nodes.getLength(); - // Register Ids of the Object child elements - for (int i = 0; i < length; i++) { - Node child = nodes.item(i); - if (child.getNodeType() == Node.ELEMENT_NODE) { - Element childElem = (Element)child; - String tag = childElem.getLocalName(); - if (tag.equals("Manifest")) { - new Manifest(childElem, BaseURI); - } else if (tag.equals("SignatureProperties")) { - new SignatureProperties(childElem, BaseURI); - } - } - } - - objectElem = XMLUtils.getNextElement(objectElem.getNextSibling()); - } - } - - /** - * Sets the Id attribute - * - * @param Id Id value to be used by the id attribute on the Signature Element - */ - public void setId(String Id) { - - if (Id != null) { - setLocalIdAttribute(Constants._ATT_ID, Id); - } - } - - /** - * Returns the Id attribute - * - * @return the Id attribute - */ - public String getId() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ID); - } - - /** - * Returns the completely parsed SignedInfo object. - * - * @return the completely parsed SignedInfo object. - */ - public SignedInfo getSignedInfo() { - return this._signedInfo; - } - - /** - * Returns the octet value of the SignatureValue element. - * Throws an XMLSignatureException if it has no or wrong content. - * - * @return the value of the SignatureValue element. - * @throws XMLSignatureException If there is no content - */ - public byte[] getSignatureValue() throws XMLSignatureException { - - try { - byte[] signatureValue = Base64.decode(signatureValueElement); - - return signatureValue; - } catch (Base64DecodingException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Returns the octet value of the SignatureValue element. + * Throws an XMLSignatureException if it has no or wrong content. + * + * @return the value of the SignatureValue element. + * @throws XMLSignatureException If there is no content + */ + public byte[] getSignatureValue() throws XMLSignatureException { + try { + return Base64.decode(signatureValueElement); + } catch (Base64DecodingException ex) { + throw new XMLSignatureException("empty", ex); + } + } /** * Base64 encodes and sets the bytes as the content of the SignatureValue @@ -409,8 +469,7 @@ private Element signatureValueElement; private void setSignatureValueElement(byte[] bytes) { while (signatureValueElement.hasChildNodes()) { - signatureValueElement.removeChild - (signatureValueElement.getFirstChild()); + signatureValueElement.removeChild(signatureValueElement.getFirstChild()); } String base64codedValue = Base64.encode(bytes); @@ -419,373 +478,393 @@ private Element signatureValueElement; base64codedValue = "\n" + base64codedValue + "\n"; } - Text t = this._doc.createTextNode(base64codedValue); + Text t = this.doc.createTextNode(base64codedValue); signatureValueElement.appendChild(t); } - /** - * Returns the KeyInfo child. If we are in signing mode and the KeyInfo - * does not exist yet, it is created on demand and added to the Signature. - *
    - * This allows to add arbitrary content to the KeyInfo during signing. - * - * @return the KeyInfo object - */ - public KeyInfo getKeyInfo() { + /** + * Returns the KeyInfo child. If we are in signing mode and the KeyInfo + * does not exist yet, it is created on demand and added to the Signature. + *
    + * This allows to add arbitrary content to the KeyInfo during signing. + * + * @return the KeyInfo object + */ + public KeyInfo getKeyInfo() { + // check to see if we are signing and if we have to create a keyinfo + if (this.state == MODE_SIGN && this.keyInfo == null) { - // check to see if we are signing and if we have to create a keyinfo - if ( (this._keyInfo == null)) { + // create the KeyInfo + this.keyInfo = new KeyInfo(this.doc); - // create the KeyInfo - this._keyInfo = new KeyInfo(this._doc); - - // get the Element from KeyInfo - Element keyInfoElement = this._keyInfo.getElement(); - Element firstObject=null; - Node sibling= this._constructionElement.getFirstChild(); - firstObject = XMLUtils.selectDsNode(sibling,Constants._TAG_OBJECT,0); + // get the Element from KeyInfo + Element keyInfoElement = this.keyInfo.getElement(); + Element firstObject = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, 0 + ); if (firstObject != null) { - - // add it before the object - this._constructionElement.insertBefore(keyInfoElement, - firstObject); - XMLUtils.addReturnBeforeChild(this._constructionElement, firstObject); + // add it before the object + this.constructionElement.insertBefore(keyInfoElement, firstObject); + XMLUtils.addReturnBeforeChild(this.constructionElement, firstObject); } else { - - // add it as the last element to the signature - this._constructionElement.appendChild(keyInfoElement); - XMLUtils.addReturnToElement(this._constructionElement); + // add it as the last element to the signature + this.constructionElement.appendChild(keyInfoElement); + XMLUtils.addReturnToElement(this.constructionElement); } - } + } - return this._keyInfo; - } + return this.keyInfo; + } - /** - * Appends an Object (not a java.lang.Object but an Object - * element) to the Signature. Please note that this is only possible - * when signing. - * - * @param object ds:Object to be appended. - * @throws XMLSignatureException When this object is used to verify. - */ - public void appendObject(ObjectContainer object) - throws XMLSignatureException { + /** + * Appends an Object (not a java.lang.Object but an Object + * element) to the Signature. Please note that this is only possible + * when signing. + * + * @param object ds:Object to be appended. + * @throws XMLSignatureException When this object is used to verify. + */ + public void appendObject(ObjectContainer object) throws XMLSignatureException { + //try { + //if (this.state != MODE_SIGN) { + // throw new XMLSignatureException( + // "signature.operationOnlyBeforeSign"); + //} - //try { - //if (this._state != MODE_SIGN) { - // throw new XMLSignatureException( - // "signature.operationOnlyBeforeSign"); - //} - - this._constructionElement.appendChild(object.getElement()); - XMLUtils.addReturnToElement(this._constructionElement); - //} catch (XMLSecurityException ex) { + this.constructionElement.appendChild(object.getElement()); + XMLUtils.addReturnToElement(this.constructionElement); + //} catch (XMLSecurityException ex) { // throw new XMLSignatureException("empty", ex); - //} - } + //} + } - /** - * Returns the ith ds:Object child of the signature - * or null if no such ds:Object element exists. - * - * @param i - * @return the ith ds:Object child of the signature or null if no such ds:Object element exists. - */ - public ObjectContainer getObjectItem(int i) { + /** + * Returns the ith ds:Object child of the signature + * or null if no such ds:Object element exists. + * + * @param i + * @return the ith ds:Object child of the signature + * or null if no such ds:Object element exists. + */ + public ObjectContainer getObjectItem(int i) { + Element objElem = + XMLUtils.selectDsNode( + this.constructionElement.getFirstChild(), Constants._TAG_OBJECT, i + ); - Element objElem = XMLUtils.selectDsNode(this._constructionElement.getFirstChild(), - Constants._TAG_OBJECT,i); + try { + return new ObjectContainer(objElem, this.baseURI); + } catch (XMLSecurityException ex) { + return null; + } + } - try { - return new ObjectContainer(objElem, this._baseURI); - } catch (XMLSecurityException ex) { - return null; - } - } + /** + * Returns the number of all ds:Object elements. + * + * @return the number of all ds:Object elements. + */ + public int getObjectLength() { + return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT); + } - /** - * Returns the number of all ds:Object elements. - * - * @return the number of all ds:Object elements. - */ - public int getObjectLength() { - return this.length(Constants.SignatureSpecNS, Constants._TAG_OBJECT); - } + /** + * Digests all References in the SignedInfo, calculates the signature value + * and sets it in the SignatureValue Element. + * + * @param signingKey the {@link java.security.PrivateKey} or + * {@link javax.crypto.SecretKey} that is used to sign. + * @throws XMLSignatureException + */ + public void sign(Key signingKey) throws XMLSignatureException { - /** - * Digests all References in the SignedInfo, calculates the signature value and - * sets it in the SignatureValue Element. - * - * @param signingKey the {@link java.security.PrivateKey} or {@link javax.crypto.SecretKey} that is used to sign. - * @throws XMLSignatureException - */ - public void sign(Key signingKey) throws XMLSignatureException { + if (signingKey instanceof PublicKey) { + throw new IllegalArgumentException( + I18n.translate("algorithms.operationOnlyVerification") + ); + } - if (signingKey instanceof PublicKey) { - throw new IllegalArgumentException(I18n - .translate("algorithms.operationOnlyVerification")); - } - - try { - // if (this._state == MODE_SIGN) { + try { //Create a SignatureAlgorithm object - SignedInfo si = this.getSignedInfo(); + SignedInfo si = this.getSignedInfo(); SignatureAlgorithm sa = si.getSignatureAlgorithm(); - // initialize SignatureAlgorithm for signing - sa.initSign(signingKey); - - // generate digest values for all References in this SignedInfo - si.generateDigestValues(); - OutputStream so=new UnsyncBufferedOutputStream(new SignerOutputStream(sa)); + OutputStream so = null; try { - so.close(); - } catch (IOException e) { - //Imposible + // initialize SignatureAlgorithm for signing + sa.initSign(signingKey); + + // generate digest values for all References in this SignedInfo + si.generateDigestValues(); + so = new UnsyncBufferedOutputStream(new SignerOutputStream(sa)); + // get the canonicalized bytes from SignedInfo + si.signInOctetStream(so); + } catch (XMLSecurityException ex) { + throw ex; + } finally { + if (so != null) { + try { + so.close(); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + } } - // get the canonicalized bytes from SignedInfo - si.signInOctectStream(so); - byte jcebytes[] = sa.sign(); + // set them on the SignatureValue element + this.setSignatureValueElement(sa.sign()); + } catch (XMLSignatureException ex) { + throw ex; + } catch (CanonicalizationException ex) { + throw new XMLSignatureException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new XMLSignatureException("empty", ex); + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } - // set them on the SignateValue element - this.setSignatureValueElement(jcebytes); - //} - } catch (CanonicalizationException ex) { - throw new XMLSignatureException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new XMLSignatureException("empty", ex); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Adds a {@link ResourceResolver} to enable the retrieval of resources. + * + * @param resolver + */ + public void addResourceResolver(ResourceResolver resolver) { + this.getSignedInfo().addResourceResolver(resolver); + } - /** - * Adds a {@link ResourceResolver} to enable the retrieval of resources. - * - * @param resolver - */ - public void addResourceResolver(ResourceResolver resolver) { - this.getSignedInfo().addResourceResolver(resolver); - } + /** + * Adds a {@link ResourceResolverSpi} to enable the retrieval of resources. + * + * @param resolver + */ + public void addResourceResolver(ResourceResolverSpi resolver) { + this.getSignedInfo().addResourceResolver(resolver); + } - /** - * Adds a {@link ResourceResolverSpi} to enable the retrieval of resources. - * - * @param resolver - */ - public void addResourceResolver(ResourceResolverSpi resolver) { - this.getSignedInfo().addResourceResolver(resolver); - } + /** + * Extracts the public key from the certificate and verifies if the signature + * is valid by re-digesting all References, comparing those against the + * stored DigestValues and then checking to see if the Signatures match on + * the SignedInfo. + * + * @param cert Certificate that contains the public key part of the keypair + * that was used to sign. + * @return true if the signature is valid, false otherwise + * @throws XMLSignatureException + */ + public boolean checkSignatureValue(X509Certificate cert) + throws XMLSignatureException { + // see if cert is null + if (cert != null) { + // check the values with the public key from the cert + return this.checkSignatureValue(cert.getPublicKey()); + } - /** - * Extracts the public key from the certificate and verifies if the signature - * is valid by re-digesting all References, comparing those against the - * stored DigestValues and then checking to see if the Signatures match on - * the SignedInfo. - * - * @param cert Certificate that contains the public key part of the keypair that was used to sign. - * @return true if the signature is valid, false otherwise - * @throws XMLSignatureException - */ - public boolean checkSignatureValue(X509Certificate cert) - throws XMLSignatureException { + Object exArgs[] = { "Didn't get a certificate" }; + throw new XMLSignatureException("empty", exArgs); + } - // see if cert is null - if (cert != null) { - - //check the values with the public key from the cert - return this.checkSignatureValue(cert.getPublicKey()); - } - - Object exArgs[] = { "Didn't get a certificate" }; - throw new XMLSignatureException("empty", exArgs); - - } - - /** - * Verifies if the signature is valid by redigesting all References, - * comparing those against the stored DigestValues and then checking to see - * if the Signatures match on the SignedInfo. - * - * @param pk {@link java.security.PublicKey} part of the keypair or {@link javax.crypto.SecretKey} that was used to sign - * @return true if the signature is valid, false otherwise - * @throws XMLSignatureException - */ - public boolean checkSignatureValue(Key pk) throws XMLSignatureException { - - //COMMENT: pk suggests it can only be a public key? - //check to see if the key is not null - if (pk == null) { - Object exArgs[] = { "Didn't get a key" }; - - throw new XMLSignatureException("empty", exArgs); - } - // all references inside the signedinfo need to be dereferenced and - // digested again to see if the outcome matches the stored value in the - // SignedInfo. - // If _followManifestsDuringValidation is true it will do the same for - // References inside a Manifest. - try { - SignedInfo si=this.getSignedInfo(); - //create a SignatureAlgorithms from the SignatureMethod inside - //SignedInfo. This is used to validate the signature. - SignatureAlgorithm sa =si.getSignatureAlgorithm(); - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "SignatureMethodURI = " + sa.getAlgorithmURI()); + /** + * Verifies if the signature is valid by redigesting all References, + * comparing those against the stored DigestValues and then checking to see + * if the Signatures match on the SignedInfo. + * + * @param pk {@link java.security.PublicKey} part of the keypair or + * {@link javax.crypto.SecretKey} that was used to sign + * @return true if the signature is valid, false otherwise + * @throws XMLSignatureException + */ + public boolean checkSignatureValue(Key pk) throws XMLSignatureException { + //COMMENT: pk suggests it can only be a public key? + //check to see if the key is not null + if (pk == null) { + Object exArgs[] = { "Didn't get a key" }; + throw new XMLSignatureException("empty", exArgs); + } + // all references inside the signedinfo need to be dereferenced and + // digested again to see if the outcome matches the stored value in the + // SignedInfo. + // If followManifestsDuringValidation is true it will do the same for + // References inside a Manifest. + try { + SignedInfo si = this.getSignedInfo(); + //create a SignatureAlgorithms from the SignatureMethod inside + //SignedInfo. This is used to validate the signature. + SignatureAlgorithm sa = si.getSignatureAlgorithm(); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "signatureMethodURI = " + sa.getAlgorithmURI()); log.log(java.util.logging.Level.FINE, "jceSigAlgorithm = " + sa.getJCEAlgorithmString()); log.log(java.util.logging.Level.FINE, "jceSigProvider = " + sa.getJCEProviderName()); log.log(java.util.logging.Level.FINE, "PublicKey = " + pk); - } - sa.initVerify(pk); + } + byte sigBytes[] = null; + try { + sa.initVerify(pk); - // Get the canonicalized (normalized) SignedInfo - SignerOutputStream so=new SignerOutputStream(sa); - OutputStream bos=new UnsyncBufferedOutputStream(so); - si.signInOctectStream(bos); - try { + // Get the canonicalized (normalized) SignedInfo + SignerOutputStream so = new SignerOutputStream(sa); + OutputStream bos = new UnsyncBufferedOutputStream(so); + + si.signInOctetStream(bos); bos.close(); - } catch (IOException e) { - //Imposible - } + // retrieve the byte[] from the stored signature + sigBytes = this.getSignatureValue(); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // Impossible... + } catch (XMLSecurityException ex) { + throw ex; + } - //retrieve the byte[] from the stored signature - byte sigBytes[] = this.getSignatureValue(); + // have SignatureAlgorithm sign the input bytes and compare them to + // the bytes that were stored in the signature. + if (!sa.verify(sigBytes)) { + log.log(java.util.logging.Level.WARNING, "Signature verification failed."); + return false; + } - //Have SignatureAlgorithm sign the input bytes and compare them to the - //bytes that were stored in the signature. - if (!sa.verify(sigBytes)) { - log.log(java.util.logging.Level.WARNING, "Signature verification failed."); - return false; - } + return si.verify(this.followManifestsDuringValidation); + } catch (XMLSignatureException ex) { + throw ex; + } catch (XMLSecurityException ex) { + throw new XMLSignatureException("empty", ex); + } + } - return si.verify(this._followManifestsDuringValidation); - } catch (XMLSecurityException ex) { - throw new XMLSignatureException("empty", ex); - } - } + /** + * Add a Reference with full parameters to this Signature + * + * @param referenceURI URI of the resource to be signed. Can be null in + * which case the dereferencing is application specific. Can be "" in which + * it's the parent node (or parent document?). There can only be one "" in + * each signature. + * @param trans Optional list of transformations to be done before digesting + * @param digestURI Mandatory URI of the digesting algorithm to use. + * @param referenceId Optional id attribute for this Reference + * @param referenceType Optional mimetype for the URI + * @throws XMLSignatureException + */ + public void addDocument( + String referenceURI, + Transforms trans, + String digestURI, + String referenceId, + String referenceType + ) throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, trans, digestURI, referenceId, referenceType + ); + } - /** - * Add a Reference with full parameters to this Signature - * - * @param referenceURI URI of the resource to be signed. Can be null in which - * case the dereferencing is application specific. Can be "" in which it's - * the parent node (or parent document?). There can only be one "" in each - * signature. - * @param trans Optional list of transformations to be done before digesting - * @param digestURI Mandatory URI of the digesting algorithm to use. - * @param ReferenceId Optional id attribute for this Reference - * @param ReferenceType Optional mimetype for the URI - * @throws XMLSignatureException - */ - public void addDocument( - String referenceURI, Transforms trans, String digestURI, String ReferenceId, String ReferenceType) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - digestURI, ReferenceId, ReferenceType); - } + /** + * This method is a proxy method for the {@link Manifest#addDocument} method. + * + * @param referenceURI URI according to the XML Signature specification. + * @param trans List of transformations to be applied. + * @param digestURI URI of the digest algorithm to be used. + * @see Manifest#addDocument + * @throws XMLSignatureException + */ + public void addDocument( + String referenceURI, + Transforms trans, + String digestURI + ) throws XMLSignatureException { + this.signedInfo.addDocument(this.baseURI, referenceURI, trans, digestURI, null, null); + } - /** - * This method is a proxy method for the {@link Manifest#addDocument} method. - * - * @param referenceURI URI according to the XML Signature specification. - * @param trans List of transformations to be applied. - * @param digestURI URI of the digest algorithm to be used. - * @see Manifest#addDocument - * @throws XMLSignatureException - */ - public void addDocument( - String referenceURI, Transforms trans, String digestURI) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - digestURI, null, null); - } + /** + * Adds a Reference with just the URI and the transforms. This used the + * SHA1 algorithm as a default digest algorithm. + * + * @param referenceURI URI according to the XML Signature specification. + * @param trans List of transformations to be applied. + * @throws XMLSignatureException + */ + public void addDocument(String referenceURI, Transforms trans) + throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, trans, Constants.ALGO_ID_DIGEST_SHA1, null, null + ); + } - /** - * Adds a Reference with just the URI and the transforms. This used the - * SHA1 algorithm as a default digest algorithm. - * - * @param referenceURI URI according to the XML Signature specification. - * @param trans List of transformations to be applied. - * @throws XMLSignatureException - */ - public void addDocument(String referenceURI, Transforms trans) - throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, trans, - Constants.ALGO_ID_DIGEST_SHA1, null, null); - } + /** + * Add a Reference with just this URI. It uses SHA1 by default as the digest + * algorithm + * + * @param referenceURI URI according to the XML Signature specification. + * @throws XMLSignatureException + */ + public void addDocument(String referenceURI) throws XMLSignatureException { + this.signedInfo.addDocument( + this.baseURI, referenceURI, null, Constants.ALGO_ID_DIGEST_SHA1, null, null + ); + } - /** - * Add a Reference with just this URI. It uses SHA1 by default as the digest - * algorithm - * - * @param referenceURI URI according to the XML Signature specification. - * @throws XMLSignatureException - */ - public void addDocument(String referenceURI) throws XMLSignatureException { - this._signedInfo.addDocument(this._baseURI, referenceURI, null, - Constants.ALGO_ID_DIGEST_SHA1, null, null); - } + /** + * Add an X509 Certificate to the KeyInfo. This will include the whole cert + * inside X509Data/X509Certificate tags. + * + * @param cert Certificate to be included. This should be the certificate of + * the key that was used to sign. + * @throws XMLSecurityException + */ + public void addKeyInfo(X509Certificate cert) throws XMLSecurityException { + X509Data x509data = new X509Data(this.doc); - /** - * Add an X509 Certificate to the KeyInfo. This will include the whole cert - * inside X509Data/X509Certificate tags. - * - * @param cert Certificate to be included. This should be the certificate of the key that was used to sign. - * @throws XMLSecurityException - */ - public void addKeyInfo(X509Certificate cert) throws XMLSecurityException { + x509data.addCertificate(cert); + this.getKeyInfo().add(x509data); + } - X509Data x509data = new X509Data(this._doc); + /** + * Add this public key to the KeyInfo. This will include the complete key in + * the KeyInfo structure. + * + * @param pk + */ + public void addKeyInfo(PublicKey pk) { + this.getKeyInfo().add(pk); + } - x509data.addCertificate(cert); - this.getKeyInfo().add(x509data); - } + /** + * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want + * to create a MAC, this method helps you to obtain the + * {@link javax.crypto.SecretKey} from octets. + * + * @param secretKeyBytes + * @return the secret key created. + * @see SignedInfo#createSecretKey(byte[]) + */ + public SecretKey createSecretKey(byte[] secretKeyBytes) { + return this.getSignedInfo().createSecretKey(secretKeyBytes); + } - /** - * Add this public key to the KeyInfo. This will include the complete key in - * the KeyInfo structure. - * - * @param pk - */ - public void addKeyInfo(PublicKey pk) { - this.getKeyInfo().add(pk); - } + /** + * Signal wether Manifest should be automatically validated. + * Checking the digests in References in a Signature are mandatory, but for + * References inside a Manifest it is application specific. This boolean is + * to indicate that the References inside Manifests should be validated. + * + * @param followManifests + * @see + * Core validation section in the XML Signature Rec. + */ + public void setFollowNestedManifests(boolean followManifests) { + this.followManifestsDuringValidation = followManifests; + } - /** - * Proxy method for {@link SignedInfo#createSecretKey(byte[])}. If you want to - * create a MAC, this method helps you to obtain the {@link javax.crypto.SecretKey} - * from octets. - * - * @param secretKeyBytes - * @return the secret key created. - * @see SignedInfo#createSecretKey(byte[]) - */ - public SecretKey createSecretKey(byte[] secretKeyBytes) - { - return this.getSignedInfo().createSecretKey(secretKeyBytes); - } - - /** - * Signal wether Manifest should be automatically validated. - * Checking the digests in References in a Signature are mandatory, but for - * References inside a Manifest it is application specific. This boolean is - * to indicate that the References inside Manifests should be validated. - * - * @param followManifests - * @see Core validation section in the XML Signature Rec. - */ - public void setFollowNestedManifests(boolean followManifests) { - this._followManifestsDuringValidation = followManifests; - } - - /** - * Get the local name of this element - * - * @return Constant._TAG_SIGNATURE - */ - public String getBaseLocalName() { - return Constants._TAG_SIGNATURE; - } + /** + * Get the local name of this element + * + * @return Constants._TAG_SIGNATURE + */ + public String getBaseLocalName() { + return Constants._TAG_SIGNATURE; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java index 744f62dc461..863ddbbedca 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureException.java @@ -2,29 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * All XML Signature related exceptions inherit herefrom. * @@ -33,57 +32,56 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; */ public class XMLSignatureException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor XMLSignatureException - * - */ - public XMLSignatureException() { - super(); - } + /** + * Constructor XMLSignatureException + * + */ + public XMLSignatureException() { + super(); + } - /** - * Constructor XMLSignatureException - * - * @param _msgID - */ - public XMLSignatureException(String _msgID) { - super(_msgID); - } + /** + * Constructor XMLSignatureException + * + * @param msgID + */ + public XMLSignatureException(String msgID) { + super(msgID); + } - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param exArgs - */ - public XMLSignatureException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param exArgs + */ + public XMLSignatureException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param _originalException - */ - public XMLSignatureException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param originalException + */ + public XMLSignatureException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor XMLSignatureException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public XMLSignatureException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor XMLSignatureException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public XMLSignatureException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java index 89990a10ac4..6451642cb70 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInput.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; @@ -25,7 +27,6 @@ import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; -import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; @@ -53,17 +54,13 @@ import org.xml.sax.SAXException; * @author Christian Geuer-Pollmann * $todo$ check whether an XMLSignatureInput can be _both_, octet stream _and_ node set? */ -public class XMLSignatureInput implements Cloneable { - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (XMLSignatureInput.class.getName()); - +public class XMLSignatureInput { /* * The XMLSignature Input can be either: * A byteArray like with/or without InputStream. * Or a nodeSet like defined either: * * as a collection of nodes - * * or as subnode excluding or not commets and excluding or + * * or as subnode excluding or not comments and excluding or * not other nodes. */ @@ -71,63 +68,55 @@ public class XMLSignatureInput implements Cloneable { * Some InputStreams do not support the {@link java.io.InputStream#reset} * method, so we read it in completely and work on our Proxy. */ - InputStream _inputOctetStreamProxy = null; + private InputStream inputOctetStreamProxy = null; /** * The original NodeSet for this XMLSignatureInput */ - Set _inputNodeSet = null; + private Set inputNodeSet = null; /** * The original Element */ - Node _subNode=null; + private Node subNode = null; /** * Exclude Node *for enveloped transformations* */ - Node excludeNode=null; + private Node excludeNode = null; /** * */ - boolean excludeComments=false; + private boolean excludeComments = false; - boolean isNodeSet=false; + private boolean isNodeSet = false; /** * A cached bytes */ - byte []bytes=null; + private byte[] bytes = null; /** - * Some Transforms may require explicit MIME type, charset (IANA registered "character set"), or other such information concerning the data they are receiving from an earlier Transform or the source data, although no Transform algorithm specified in this document needs such explicit information. Such data characteristics are provided as parameters to the Transform algorithm and should be described in the specification for the algorithm. + * Some Transforms may require explicit MIME type, charset (IANA registered + * "character set"), or other such information concerning the data they are + * receiving from an earlier Transform or the source data, although no + * Transform algorithm specified in this document needs such explicit + * information. Such data characteristics are provided as parameters to the + * Transform algorithm and should be described in the specification for the + * algorithm. */ - private String _MIMEType = null; + private String mimeType = null; /** - * Field _SourceURI + * Field sourceURI */ - private String _SourceURI = null; + private String sourceURI = null; /** * Node Filter list. */ - List nodeFilters=new ArrayList(); + private List nodeFilters = new ArrayList(); - boolean needsToBeExpanded=false; - OutputStream outputStream=null; + private boolean needsToBeExpanded = false; + private OutputStream outputStream = null; - /** - * Check if the structured is needed to be circumbented. - * @return true if so. - */ - public boolean isNeedsToBeExpanded() { - return needsToBeExpanded; - } - - /** - * Set if the structured is needed to be circumbented. - * @param needsToBeExpanded true if so. - */ - public void setNeedsToBeExpanded(boolean needsToBeExpanded) { - this.needsToBeExpanded = needsToBeExpanded; - } + private DocumentBuilderFactory dfactory; /** * Construct a XMLSignatureInput from an octet array. @@ -138,11 +127,8 @@ public class XMLSignatureInput implements Cloneable { * @param inputOctets an octet array which including XML document or node */ public XMLSignatureInput(byte[] inputOctets) { - - // NO defensive copy - - //this._inputOctetStreamProxy = new ByteArrayInputStream(inputOctets); - this.bytes=inputOctets; + // NO defensive copy + this.bytes = inputOctets; } /** @@ -152,39 +138,7 @@ public class XMLSignatureInput implements Cloneable { * @param inputOctetStream */ public XMLSignatureInput(InputStream inputOctetStream) { - this._inputOctetStreamProxy=inputOctetStream; - - //this(JavaUtils.getBytesFromStream(inputOctetStream)); - } - - /** - * Construct a XMLSignatureInput from a String. - *

    - * This is a comfort method, which internally converts the String into a byte - * [] array using the {@link java.lang.String#getBytes()} method. - * @deprecated - * @param inputStr the input String which including XML document or node - */ - @Deprecated - public XMLSignatureInput(String inputStr) { - this(inputStr.getBytes()); - } - - /** - * Construct a XMLSignatureInput from a String with a given encoding. - *

    - * This is a comfort method, which internally converts the String into a byte - * [] array using the {@link java.lang.String#getBytes()} method. - * - * @deprecated - * @param inputStr the input String with encoding encoding - * @param encoding the encoding of inputStr - * @throws UnsupportedEncodingException - */ - @Deprecated - public XMLSignatureInput(String inputStr, String encoding) - throws UnsupportedEncodingException { - this(inputStr.getBytes(encoding)); + this.inputOctetStreamProxy = inputOctetStream; } /** @@ -193,19 +147,33 @@ public class XMLSignatureInput implements Cloneable { * * @param rootNode */ - public XMLSignatureInput(Node rootNode) - { - this._subNode = rootNode; + public XMLSignatureInput(Node rootNode) { + this.subNode = rootNode; } /** * Constructor XMLSignatureInput * * @param inputNodeSet - * @param usedXPathAPI */ public XMLSignatureInput(Set inputNodeSet) { - this._inputNodeSet = inputNodeSet; + this.inputNodeSet = inputNodeSet; + } + + /** + * Check if the structure needs to be expanded. + * @return true if so. + */ + public boolean isNeedsToBeExpanded() { + return needsToBeExpanded; + } + + /** + * Set if the structure needs to be expanded. + * @param needsToBeExpanded true if so. + */ + public void setNeedsToBeExpanded(boolean needsToBeExpanded) { + this.needsToBeExpanded = needsToBeExpanded; } /** @@ -218,11 +186,19 @@ public class XMLSignatureInput implements Cloneable { * @throws ParserConfigurationException * @throws CanonicalizationException */ - public Set getNodeSet() throws CanonicalizationException, - ParserConfigurationException, IOException, SAXException { + public Set getNodeSet() throws CanonicalizationException, ParserConfigurationException, + IOException, SAXException { return getNodeSet(false); } + /** + * Get the Input NodeSet. + * @return the Input NodeSet. + */ + public Set getInputNodeSet() { + return inputNodeSet; + } + /** * Returns the node set from input which was specified as the parameter of * {@link XMLSignatureInput} constructor @@ -234,51 +210,54 @@ public class XMLSignatureInput implements Cloneable { * @throws ParserConfigurationException * @throws CanonicalizationException */ - public Set getNodeSet(boolean circumvent) - throws ParserConfigurationException, IOException, SAXException, - CanonicalizationException { - if (this._inputNodeSet!=null) { - return this._inputNodeSet; + public Set getNodeSet(boolean circumvent) throws ParserConfigurationException, + IOException, SAXException, CanonicalizationException { + if (inputNodeSet != null) { + return inputNodeSet; } - if ((this._inputOctetStreamProxy==null)&& (this._subNode!=null) ) { - + if (inputOctetStreamProxy == null && subNode != null) { if (circumvent) { - XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(_subNode)); + XMLUtils.circumventBug2650(XMLUtils.getOwnerDocument(subNode)); } - this._inputNodeSet = new LinkedHashSet(); - XMLUtils.getSet(_subNode,this._inputNodeSet, excludeNode, this.excludeComments); - - return this._inputNodeSet; - } else if (this.isOctetStream()) { + inputNodeSet = new LinkedHashSet(); + XMLUtils.getSet(subNode, inputNodeSet, excludeNode, excludeComments); + return inputNodeSet; + } else if (isOctetStream()) { convertToNodes(); - LinkedHashSet result = new LinkedHashSet(); - XMLUtils.getSet(_subNode, result,null,false); - //this._inputNodeSet=result; + Set result = new LinkedHashSet(); + XMLUtils.getSet(subNode, result, null, false); return result; } - throw new RuntimeException( - "getNodeSet() called but no input data present"); + throw new RuntimeException("getNodeSet() called but no input data present"); } /** - * Returns the Octect stream(byte Stream) from input which was specified as + * Returns the Octet stream(byte Stream) from input which was specified as * the parameter of {@link XMLSignatureInput} constructor * - * @return the Octect stream(byte Stream) from input which was specified as + * @return the Octet stream(byte Stream) from input which was specified as * the parameter of {@link XMLSignatureInput} constructor * @throws IOException */ public InputStream getOctetStream() throws IOException { + if (inputOctetStreamProxy != null) { + return inputOctetStreamProxy; + } - return getResetableInputStream(); + if (bytes != null) { + inputOctetStreamProxy = new ByteArrayInputStream(bytes); + return inputOctetStreamProxy; + } + + return null; } /** - * @return real octect stream + * @return real octet stream */ - public InputStream getOctetStreamReal () { - return this._inputOctetStreamProxy; + public InputStream getOctetStreamReal() { + return inputOctetStreamProxy; } /** @@ -292,21 +271,12 @@ public class XMLSignatureInput implements Cloneable { * @throws IOException */ public byte[] getBytes() throws IOException, CanonicalizationException { - if (bytes!=null) { - return bytes; + byte[] inputBytes = getBytesFromInputStream(); + if (inputBytes != null) { + return inputBytes; } - InputStream is = getResetableInputStream(); - if (is!=null) { - //resetable can read again bytes. - if (bytes==null) { - is.reset(); - bytes=JavaUtils.getBytesFromStream(is); - } - return bytes; - } - Canonicalizer20010315OmitComments c14nizer = - new Canonicalizer20010315OmitComments(); - bytes=c14nizer.engineCanonicalize(this); + Canonicalizer20010315OmitComments c14nizer = new Canonicalizer20010315OmitComments(); + bytes = c14nizer.engineCanonicalize(this); return bytes; } @@ -316,18 +286,18 @@ public class XMLSignatureInput implements Cloneable { * @return true if the object has been set up with a Node set */ public boolean isNodeSet() { - return (( (this._inputOctetStreamProxy == null) - && (this._inputNodeSet != null) ) || isNodeSet); + return ((inputOctetStreamProxy == null + && inputNodeSet != null) || isNodeSet); } /** * Determines if the object has been set up with an Element * - * @return true if the object has been set up with a Node set + * @return true if the object has been set up with an Element */ public boolean isElement() { - return ((this._inputOctetStreamProxy==null)&& (this._subNode!=null) - && (this._inputNodeSet==null) && !isNodeSet); + return (inputOctetStreamProxy == null && subNode != null + && inputNodeSet == null && !isNodeSet); } /** @@ -336,8 +306,8 @@ public class XMLSignatureInput implements Cloneable { * @return true if the object has been set up with an octet stream */ public boolean isOctetStream() { - return ( ((this._inputOctetStreamProxy != null) || bytes!=null) - && ((this._inputNodeSet == null) && _subNode ==null)); + return ((inputOctetStreamProxy != null || bytes != null) + && (inputNodeSet == null && subNode == null)); } /** @@ -357,8 +327,7 @@ public class XMLSignatureInput implements Cloneable { * @return true is the object has been set up with an octet stream */ public boolean isByteArray() { - return ( (bytes!=null) - && ((this._inputNodeSet == null) && _subNode ==null)); + return (bytes != null && (this.inputNodeSet == null && subNode == null)); } /** @@ -367,25 +336,25 @@ public class XMLSignatureInput implements Cloneable { * @return true if the object has been set up correctly */ public boolean isInitialized() { - return (this.isOctetStream() || this.isNodeSet()); + return isOctetStream() || isNodeSet(); } /** - * Returns MIMEType + * Returns mimeType * - * @return MIMEType + * @return mimeType */ public String getMIMEType() { - return this._MIMEType; + return mimeType; } /** - * Sets MIMEType + * Sets mimeType * - * @param MIMEType + * @param mimeType */ - public void setMIMEType(String MIMEType) { - this._MIMEType = MIMEType; + public void setMIMEType(String mimeType) { + this.mimeType = mimeType; } /** @@ -394,16 +363,16 @@ public class XMLSignatureInput implements Cloneable { * @return SourceURI */ public String getSourceURI() { - return this._SourceURI; + return sourceURI; } /** * Sets SourceURI * - * @param SourceURI + * @param sourceURI */ - public void setSourceURI(String SourceURI) { - this._SourceURI = SourceURI; + public void setSourceURI(String sourceURI) { + this.sourceURI = sourceURI; } /** @@ -411,22 +380,22 @@ public class XMLSignatureInput implements Cloneable { * @inheritDoc */ public String toString() { - if (this.isNodeSet()) { - return "XMLSignatureInput/NodeSet/" + this._inputNodeSet.size() - + " nodes/" + this.getSourceURI(); + if (isNodeSet()) { + return "XMLSignatureInput/NodeSet/" + inputNodeSet.size() + + " nodes/" + getSourceURI(); } - if (this.isElement()) { - return "XMLSignatureInput/Element/" + this._subNode - + " exclude "+ this.excludeNode + " comments:" + - this.excludeComments +"/" + this.getSourceURI(); + if (isElement()) { + return "XMLSignatureInput/Element/" + subNode + + " exclude "+ excludeNode + " comments:" + + excludeComments +"/" + getSourceURI(); } try { - return "XMLSignatureInput/OctetStream/" + this.getBytes().length - + " octets/" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream/" + getBytes().length + + " octets/" + getSourceURI(); } catch (IOException iex) { - return "XMLSignatureInput/OctetStream//" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream//" + getSourceURI(); } catch (CanonicalizationException cex) { - return "XMLSignatureInput/OctetStream//" + this.getSourceURI(); + return "XMLSignatureInput/OctetStream//" + getSourceURI(); } } @@ -437,9 +406,7 @@ public class XMLSignatureInput implements Cloneable { * @return The HTML representation for this XMLSignature */ public String getHTMLRepresentation() throws XMLSignatureException { - XMLSignatureInputDebugger db = new XMLSignatureInputDebugger(this); - return db.getHTMLRepresentation(); } @@ -451,11 +418,9 @@ public class XMLSignatureInput implements Cloneable { * @return The HTML representation for this XMLSignature */ public String getHTMLRepresentation(Set inclusiveNamespaces) - throws XMLSignatureException { - - XMLSignatureInputDebugger db = new XMLSignatureInputDebugger( this, - inclusiveNamespaces); - + throws XMLSignatureException { + XMLSignatureInputDebugger db = + new XMLSignatureInputDebugger(this, inclusiveNamespaces); return db.getHTMLRepresentation(); } @@ -480,7 +445,7 @@ public class XMLSignatureInput implements Cloneable { * @return The excludeNode set. */ public Node getSubNode() { - return _subNode; + return subNode; } /** @@ -503,19 +468,18 @@ public class XMLSignatureInput implements Cloneable { * @throws CanonicalizationException */ public void updateOutputStream(OutputStream diOs) - throws CanonicalizationException, IOException { + throws CanonicalizationException, IOException { updateOutputStream(diOs, false); } public void updateOutputStream(OutputStream diOs, boolean c14n11) - throws CanonicalizationException, IOException { - if (diOs==outputStream) { + throws CanonicalizationException, IOException { + if (diOs == outputStream) { return; } - if (bytes!=null) { + if (bytes != null) { diOs.write(bytes); - return; - } else if (_inputOctetStreamProxy==null) { + } else if (inputOctetStreamProxy == null) { CanonicalizerBase c14nizer = null; if (c14n11) { c14nizer = new Canonicalizer11_OmitComments(); @@ -524,19 +488,16 @@ public class XMLSignatureInput implements Cloneable { } c14nizer.setWriter(diOs); c14nizer.engineCanonicalize(this); - return; } else { - InputStream is = getResetableInputStream(); - if (bytes!=null) { - //already read write it, can be rea. - diOs.write(bytes,0,bytes.length); - return; - } - is.reset(); - int num; - byte[] bytesT = new byte[1024]; - while ((num=is.read(bytesT))>0) { - diOs.write(bytesT,0,num); + byte[] buffer = new byte[4 * 1024]; + int bytesread = 0; + try { + while ((bytesread = inputOctetStreamProxy.read(buffer)) != -1) { + diOs.write(buffer, 0, bytesread); + } + } catch (IOException ex) { + inputOctetStreamProxy.close(); + throw ex; } } } @@ -545,29 +506,22 @@ public class XMLSignatureInput implements Cloneable { * @param os */ public void setOutputStream(OutputStream os) { - outputStream=os; + outputStream = os; } - protected InputStream getResetableInputStream() throws IOException{ - if ((_inputOctetStreamProxy instanceof ByteArrayInputStream) ) { - if (!_inputOctetStreamProxy.markSupported()) { - throw new RuntimeException("Accepted as Markable but not truly been"+_inputOctetStreamProxy); - } - return _inputOctetStreamProxy; + private byte[] getBytesFromInputStream() throws IOException { + if (bytes != null) { + return bytes; } - if (bytes!=null) { - _inputOctetStreamProxy=new ByteArrayInputStream(bytes); - return _inputOctetStreamProxy; - } - if (_inputOctetStreamProxy ==null) + if (inputOctetStreamProxy == null) { return null; - if (_inputOctetStreamProxy.markSupported()) { - log.log(java.util.logging.Level.INFO, "Mark Suported but not used as reset"); } - bytes=JavaUtils.getBytesFromStream(_inputOctetStreamProxy); - _inputOctetStreamProxy.close(); - _inputOctetStreamProxy=new ByteArrayInputStream(bytes); - return _inputOctetStreamProxy; + try { + bytes = JavaUtils.getBytesFromStream(inputOctetStreamProxy); + } finally { + inputOctetStreamProxy.close(); + } + return bytes; } /** @@ -578,7 +532,9 @@ public class XMLSignatureInput implements Cloneable { try { convertToNodes(); } catch (Exception e) { - throw new XMLSecurityRuntimeException("signature.XMLSignatureInput.nodesetReference",e); + throw new XMLSecurityRuntimeException( + "signature.XMLSignatureInput.nodesetReference", e + ); } } nodeFilters.add(filter); @@ -588,7 +544,6 @@ public class XMLSignatureInput implements Cloneable { * @return the node filters */ public List getNodeFilters() { - // TODO Auto-generated method stub return nodeFilters; } @@ -596,39 +551,42 @@ public class XMLSignatureInput implements Cloneable { * @param b */ public void setNodeSet(boolean b) { - isNodeSet=b; + isNodeSet = b; } void convertToNodes() throws CanonicalizationException, ParserConfigurationException, IOException, SAXException { - DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance(); - dfactory.setValidating(false); - dfactory.setNamespaceAware(true); - dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); + if (dfactory == null) { + dfactory = DocumentBuilderFactory.newInstance(); + dfactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + dfactory.setValidating(false); + dfactory.setNamespaceAware(true); + } DocumentBuilder db = dfactory.newDocumentBuilder(); // select all nodes, also the comments. try { - db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils - .IgnoreAllErrorHandler()); + db.setErrorHandler(new com.sun.org.apache.xml.internal.security.utils.IgnoreAllErrorHandler()); Document doc = db.parse(this.getOctetStream()); - - this._subNode=doc.getDocumentElement(); + this.subNode = doc; } catch (SAXException ex) { - // if a not-wellformed nodeset exists, put a container around it... ByteArrayOutputStream baos = new ByteArrayOutputStream(); - baos.write("".getBytes()); + baos.write("".getBytes("UTF-8")); baos.write(this.getBytes()); - baos.write("".getBytes()); + baos.write("".getBytes("UTF-8")); byte result[] = baos.toByteArray(); Document document = db.parse(new ByteArrayInputStream(result)); - this._subNode=document.getDocumentElement().getFirstChild().getFirstChild(); + this.subNode = document.getDocumentElement().getFirstChild().getFirstChild(); + } finally { + if (this.inputOctetStreamProxy != null) { + this.inputOctetStreamProxy.close(); + } + this.inputOctetStreamProxy = null; + this.bytes = null; } - this._inputOctetStreamProxy=null; - this.bytes=null; } + } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java index 3186ef4d6a8..e565b22aeee 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/XMLSignatureInputDebugger.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.signature; @@ -38,681 +40,591 @@ import org.w3c.dom.ProcessingInstruction; /** * Class XMLSignatureInputDebugger - * - * @author $Author: mullan $ - * @version $Revision: 1.3 $ */ public class XMLSignatureInputDebugger { + /** Field _xmlSignatureInput */ + private Set xpathNodeSet; + private Set inclusiveNamespaces; - /** Field _xmlSignatureInput */ - private Set _xpathNodeSet; + /** Field doc */ + private Document doc = null; - private Set _inclusiveNamespaces; + /** Field writer */ + private Writer writer = null; - /** Field _doc */ - private Document _doc = null; + /** The HTML Prefix* */ + static final String HTMLPrefix = + "\n" + + "\n" + + "\n" + + "Caninical XML node set\n" + + " \n" + + "\n" + + "\n" + + "

    Explanation of the output

    \n" + + "

    The following text contains the nodeset of the given Reference before it is canonicalized. There exist four different styles to indicate how a given node is treated.

    \n" + + "
      \n" + + "
    • A node which is in the node set is labeled using the INCLUDED style.
    • \n" + + "
    • A node which is NOT in the node set is labeled EXCLUDED style.
    • \n" + + "
    • A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" + + "
    • A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" + + "
    \n" + "

    Output

    \n" + "
    \n";
     
    -        /** Field _writer */
    -        private Writer _writer = null;
    +    /** HTML Suffix * */
    +    static final String HTMLSuffix = "
    "; - // J- - // public static final String HTMLPrefix = "
    ";
    -        /** The HTML Prefix* */
    -        static final String HTMLPrefix = "\n"
    -                        + "\n"
    -                        + "\n"
    -                        + "Caninical XML node set\n"
    -                        + " \n"
    -                        + "\n"
    -                        + "\n"
    -                        + "

    Explanation of the output

    \n" - + "

    The following text contains the nodeset of the given Reference before it is canonicalized. There exist four different styles to indicate how a given node is treated.

    \n" - + "
      \n" - + "
    • A node which is in the node set is labeled using the INCLUDED style.
    • \n" - + "
    • A node which is NOT in the node set is labeled EXCLUDED style.
    • \n" - + "
    • A namespace which is in the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" - + "
    • A namespace which is in NOT the node set AND in the InclusiveNamespaces PrefixList is labeled using the INCLUDEDINCLUSIVENAMESPACE style.
    • \n" - + "
    \n" + "

    Output

    \n" + "
    \n";
    +    static final String HTMLExcludePrefix = "";
     
    -        /** HTML Suffix * */
    -        static final String HTMLSuffix = "
    "; + static final String HTMLIncludePrefix = ""; - static final String HTMLExcludePrefix = ""; + static final String HTMLIncludeOrExcludeSuffix = ""; - static final String HTMLExcludeSuffix = ""; + static final String HTMLIncludedInclusiveNamespacePrefix = ""; - static final String HTMLIncludePrefix = ""; + static final String HTMLExcludedInclusiveNamespacePrefix = ""; - static final String HTMLIncludeSuffix = ""; + private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; - static final String HTMLIncludedInclusiveNamespacePrefix = ""; + private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - static final String HTMLIncludedInclusiveNamespaceSuffix = ""; + private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - static final String HTMLExcludedInclusiveNamespacePrefix = ""; + static final AttrCompare ATTR_COMPARE = new AttrCompare(); - static final String HTMLExcludedInclusiveNamespaceSuffix = ""; + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signature to pretty print + */ + public XMLSignatureInputDebugger(XMLSignatureInput xmlSignatureInput) { + if (!xmlSignatureInput.isNodeSet()) { + this.xpathNodeSet = null; + } else { + this.xpathNodeSet = xmlSignatureInput.getInputNodeSet(); + } + } - private static final int NODE_BEFORE_DOCUMENT_ELEMENT = -1; + /** + * Constructor XMLSignatureInputDebugger + * + * @param xmlSignatureInput the signatur to pretty print + * @param inclusiveNamespace + */ + public XMLSignatureInputDebugger( + XMLSignatureInput xmlSignatureInput, + Set inclusiveNamespace + ) { + this(xmlSignatureInput); + this.inclusiveNamespaces = inclusiveNamespace; + } - private static final int NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT = 0; - - private static final int NODE_AFTER_DOCUMENT_ELEMENT = 1; - - static final AttrCompare ATTR_COMPARE = new AttrCompare(); - - // J+ - private XMLSignatureInputDebugger() { - // do nothing + /** + * Method getHTMLRepresentation + * + * @return The HTML Representation. + * @throws XMLSignatureException + */ + public String getHTMLRepresentation() throws XMLSignatureException { + if ((this.xpathNodeSet == null) || (this.xpathNodeSet.size() == 0)) { + return HTMLPrefix + "no node set, sorry" + HTMLSuffix; } - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput) { + // get only a single node as anchor to fetch the owner document + Node n = this.xpathNodeSet.iterator().next(); - if (!xmlSignatureInput.isNodeSet()) { - this._xpathNodeSet = null; + this.doc = XMLUtils.getOwnerDocument(n); + + try { + this.writer = new StringWriter(); + + this.canonicalizeXPathNodeSet(this.doc); + this.writer.close(); + + return this.writer.toString(); + } catch (IOException ex) { + throw new XMLSignatureException("empty", ex); + } finally { + this.xpathNodeSet = null; + this.doc = null; + this.writer = null; + } + } + + /** + * Method canonicalizeXPathNodeSet + * + * @param currentNode + * @throws XMLSignatureException + * @throws IOException + */ + private void canonicalizeXPathNodeSet(Node currentNode) + throws XMLSignatureException, IOException { + + int currentNodeType = currentNode.getNodeType(); + switch (currentNodeType) { + + + case Node.ENTITY_NODE: + case Node.NOTATION_NODE: + case Node.DOCUMENT_FRAGMENT_NODE: + case Node.ATTRIBUTE_NODE: + throw new XMLSignatureException("empty"); + case Node.DOCUMENT_NODE: + this.writer.write(HTMLPrefix); + + for (Node currentChild = currentNode.getFirstChild(); + currentChild != null; currentChild = currentChild.getNextSibling()) { + this.canonicalizeXPathNodeSet(currentChild); + } + + this.writer.write(HTMLSuffix); + break; + + case Node.COMMENT_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + int position = getPositionRelativeToDocumentElement(currentNode); + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.outputCommentToWriter((Comment) currentNode); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.PROCESSING_INSTRUCTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + position = getPositionRelativeToDocumentElement(currentNode); + + if (position == NODE_AFTER_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.outputPItoWriter((ProcessingInstruction) currentNode); + + if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { + this.writer.write("\n"); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.TEXT_NODE: + case Node.CDATA_SECTION_NODE: + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + outputTextToWriter(currentNode.getNodeValue()); + + for (Node nextSibling = currentNode.getNextSibling(); + (nextSibling != null) + && ((nextSibling.getNodeType() == Node.TEXT_NODE) + || (nextSibling.getNodeType() == Node.CDATA_SECTION_NODE)); + nextSibling = nextSibling.getNextSibling()) { + /* + * The XPath data model allows to select only the first of a + * sequence of mixed text and CDATA nodes. But we must output + * them all, so we must search: + * + * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 + */ + this.outputTextToWriter(nextSibling.getNodeValue()); + } + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.ELEMENT_NODE: + Element currentElement = (Element) currentNode; + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("<"); + this.writer.write(currentElement.getTagName()); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // we output all Attrs which are available + NamedNodeMap attrs = currentElement.getAttributes(); + int attrsLength = attrs.getLength(); + Attr attrs2[] = new Attr[attrsLength]; + + for (int i = 0; i < attrsLength; i++) { + attrs2[i] = (Attr)attrs.item(i); + } + + Arrays.sort(attrs2, ATTR_COMPARE); + Object attrs3[] = attrs2; + + for (int i = 0; i < attrsLength; i++) { + Attr a = (Attr) attrs3[i]; + boolean included = this.xpathNodeSet.contains(a); + boolean inclusive = this.inclusiveNamespaces.contains(a.getName()); + + if (included) { + if (inclusive) { + // included and inclusive + this.writer.write(HTMLIncludedInclusiveNamespacePrefix); + } else { + // included and not inclusive + this.writer.write(HTMLIncludePrefix); + } } else { - this._xpathNodeSet = xmlSignatureInput._inputNodeSet; - } - } - - /** - * Constructor XMLSignatureInputDebugger - * - * @param xmlSignatureInput the signatur to pretty print - * @param inclusiveNamespace - */ - public XMLSignatureInputDebugger( - XMLSignatureInput xmlSignatureInput, Set inclusiveNamespace) { - - this(xmlSignatureInput); - - this._inclusiveNamespaces = inclusiveNamespace; - } - - /** - * Method getHTMLRepresentation - * - * @return The HTML Representation. - * @throws XMLSignatureException - */ - public String getHTMLRepresentation() throws XMLSignatureException { - - if ((this._xpathNodeSet == null) || (this._xpathNodeSet.size() == 0)) { - return HTMLPrefix + "no node set, sorry" - + HTMLSuffix; - } - - { - - // get only a single node as anchor to fetch the owner document - Node n = this._xpathNodeSet.iterator().next(); - - this._doc = XMLUtils.getOwnerDocument(n); - } - - try { - this._writer = new StringWriter(); - - this.canonicalizeXPathNodeSet(this._doc); - this._writer.close(); - - return this._writer.toString(); - } catch (IOException ex) { - throw new XMLSignatureException("empty", ex); - } finally { - this._xpathNodeSet = null; - this._doc = null; - this._writer = null; - } - } - - /** - * Method canonicalizeXPathNodeSet - * - * @param currentNode - * @throws XMLSignatureException - * @throws IOException - */ - private void canonicalizeXPathNodeSet(Node currentNode) - throws XMLSignatureException, IOException { - - int currentNodeType = currentNode.getNodeType(); - switch (currentNodeType) { - - case Node.DOCUMENT_TYPE_NODE: - default: - break; - - case Node.ENTITY_NODE: - case Node.NOTATION_NODE: - case Node.DOCUMENT_FRAGMENT_NODE: - case Node.ATTRIBUTE_NODE: - throw new XMLSignatureException("empty"); - case Node.DOCUMENT_NODE: - this._writer.write(HTMLPrefix); - - for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild - .getNextSibling()) { - this.canonicalizeXPathNodeSet(currentChild); - } - - this._writer.write(HTMLSuffix); - break; - - case Node.COMMENT_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - int position = getPositionRelativeToDocumentElement(currentNode); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - this.outputCommentToWriter((Comment) currentNode); - - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.PROCESSING_INSTRUCTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - position = getPositionRelativeToDocumentElement(currentNode); - - if (position == NODE_AFTER_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - this.outputPItoWriter((ProcessingInstruction) currentNode); - - if (position == NODE_BEFORE_DOCUMENT_ELEMENT) { - this._writer.write("\n"); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.TEXT_NODE: - case Node.CDATA_SECTION_NODE: - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - outputTextToWriter(currentNode.getNodeValue()); - - for (Node nextSibling = currentNode.getNextSibling(); (nextSibling != null) - && ((nextSibling.getNodeType() == Node.TEXT_NODE) || (nextSibling - .getNodeType() == Node.CDATA_SECTION_NODE)); nextSibling = nextSibling - .getNextSibling()) { - - /* - * The XPath data model allows to select only the first of a - * sequence of mixed text and CDATA nodes. But we must output - * them all, so we must search: - * - * @see http://nagoya.apache.org/bugzilla/show_bug.cgi?id=6329 - */ - this.outputTextToWriter(nextSibling.getNodeValue()); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - - case Node.ELEMENT_NODE: - Element currentElement = (Element) currentNode; - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("<"); - this._writer.write(currentElement.getTagName()); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // we output all Attrs which are available - NamedNodeMap attrs = currentElement.getAttributes(); - int attrsLength = attrs.getLength(); - Attr attrs2[] = new Attr[attrsLength]; - - for (int i = 0; i < attrsLength; i++) { - attrs2[i] = (Attr)attrs.item(i); - } - - Arrays.sort(attrs2, ATTR_COMPARE); - Object attrs3[] = attrs2; - - for (int i = 0; i < attrsLength; i++) { - Attr a = (Attr) attrs3[i]; - boolean included = this._xpathNodeSet.contains(a); - boolean inclusive = this._inclusiveNamespaces.contains(a - .getName()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespacePrefix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludePrefix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespacePrefix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludePrefix); - } - } - - this.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); - - if (included) { - if (inclusive) { - - // included and inclusive - this._writer - .write(HTMLIncludedInclusiveNamespaceSuffix); - } else { - - // included and not inclusive - this._writer.write(HTMLIncludeSuffix); - } - } else { - if (inclusive) { - - // excluded and inclusive - this._writer - .write(HTMLExcludedInclusiveNamespaceSuffix); - } else { - - // excluded and not inclusive - this._writer.write(HTMLExcludeSuffix); - } - } - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - - // traversal - for (Node currentChild = currentNode.getFirstChild(); currentChild != null; currentChild = currentChild - .getNextSibling()) { - this.canonicalizeXPathNodeSet(currentChild); - } - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludePrefix); - } else { - this._writer.write(HTMLExcludePrefix); - } - - this._writer.write("</"); - this._writer.write(currentElement.getTagName()); - this._writer.write(">"); - - if (this._xpathNodeSet.contains(currentNode)) { - this._writer.write(HTMLIncludeSuffix); - } else { - this._writer.write(HTMLExcludeSuffix); - } - break; - } - } - - /** - * Checks whether a Comment or ProcessingInstruction is before or after the - * document element. This is needed for prepending or appending "\n"s. - * - * @param currentNode - * comment or pi to check - * @return NODE_BEFORE_DOCUMENT_ELEMENT, - * NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or - * NODE_AFTER_DOCUMENT_ELEMENT - * @see #NODE_BEFORE_DOCUMENT_ELEMENT - * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT - * @see #NODE_AFTER_DOCUMENT_ELEMENT - */ - private int getPositionRelativeToDocumentElement(Node currentNode) { - - if (currentNode == null) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - Document doc = currentNode.getOwnerDocument(); - - if (currentNode.getParentNode() != doc) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - Element documentElement = doc.getDocumentElement(); - - if (documentElement == null) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - if (documentElement == currentNode) { - return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; - } - - for (Node x = currentNode; x != null; x = x.getNextSibling()) { - if (x == documentElement) { - return NODE_BEFORE_DOCUMENT_ELEMENT; - } - } - - return NODE_AFTER_DOCUMENT_ELEMENT; - } - - /** - * Normalizes an {@link Attr}ibute value - * - * The string value of the node is modified by replacing - *
      - *
    • all ampersands (&) with &amp;
    • - *
    • all open angle brackets (<) with &lt;
    • - *
    • all quotation mark characters with &quot;
    • - *
    • and the whitespace characters #x9, #xA, and #xD, - * with character references. The character references are written in - * uppercase hexadecimal with no leading zeroes (for example, #xD - * is represented by the character reference &#xD;)
    • - *
    - * - * @param name - * @param value - * @throws IOException - */ - private void outputAttrToWriter(String name, String value) - throws IOException { - - this._writer.write(" "); - this._writer.write(name); - this._writer.write("=\""); - - int length = value.length(); - - for (int i = 0; i < length; i++) { - char c = value.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '"': - this._writer.write("&quot;"); - break; - - case 0x09: // '\t' - this._writer.write("&#x9;"); - break; - - case 0x0A: // '\n' - this._writer.write("&#xA;"); - break; - - case 0x0D: // '\r' - this._writer.write("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } - } - - this._writer.write("\""); - } - - /** - * Normalizes a {@link org.w3c.dom.Comment} value - * - * @param currentPI - * @throws IOException - */ - private void outputPItoWriter(ProcessingInstruction currentPI) - throws IOException { - - if (currentPI == null) { - return; - } - - this._writer.write("<?"); - - String target = currentPI.getTarget(); - int length = target.length(); - - for (int i = 0; i < length; i++) { - char c = target.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } - - String data = currentPI.getData(); - - length = data.length(); - - if (length > 0) { - this._writer.write(" "); - - for (int i = 0; i < length; i++) { - char c = data.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - default: - this._writer.write(c); - break; - } + if (inclusive) { + // excluded and inclusive + this.writer.write(HTMLExcludedInclusiveNamespacePrefix); + } else { + // excluded and not inclusive + this.writer.write(HTMLExcludePrefix); } } - this._writer.write("?>"); + this.outputAttrToWriter(a.getNodeName(), a.getNodeValue()); + this.writer.write(HTMLIncludeOrExcludeSuffix); + } + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write(">"); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + + // traversal + for (Node currentChild = currentNode.getFirstChild(); + currentChild != null; + currentChild = currentChild.getNextSibling()) { + this.canonicalizeXPathNodeSet(currentChild); + } + + if (this.xpathNodeSet.contains(currentNode)) { + this.writer.write(HTMLIncludePrefix); + } else { + this.writer.write(HTMLExcludePrefix); + } + + this.writer.write("</"); + this.writer.write(currentElement.getTagName()); + this.writer.write(">"); + + this.writer.write(HTMLIncludeOrExcludeSuffix); + break; + + case Node.DOCUMENT_TYPE_NODE: + default: + break; + } + } + + /** + * Checks whether a Comment or ProcessingInstruction is before or after the + * document element. This is needed for prepending or appending "\n"s. + * + * @param currentNode + * comment or pi to check + * @return NODE_BEFORE_DOCUMENT_ELEMENT, + * NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT or + * NODE_AFTER_DOCUMENT_ELEMENT + * @see #NODE_BEFORE_DOCUMENT_ELEMENT + * @see #NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT + * @see #NODE_AFTER_DOCUMENT_ELEMENT + */ + private int getPositionRelativeToDocumentElement(Node currentNode) { + if (currentNode == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - /** - * Method outputCommentToWriter - * - * @param currentComment - * @throws IOException - */ - private void outputCommentToWriter(Comment currentComment) - throws IOException { + Document doc = currentNode.getOwnerDocument(); - if (currentComment == null) { - return; - } - - this._writer.write("<!--"); - - String data = currentComment.getData(); - int length = data.length(); - - for (int i = 0; i < length; i++) { - char c = data.charAt(i); - - switch (c) { - - case 0x0D: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } - - this._writer.write("-->"); + if (currentNode.getParentNode() != doc) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } - /** - * Method outputTextToWriter - * - * @param text - * @throws IOException - */ - private void outputTextToWriter(String text) throws IOException { + Element documentElement = doc.getDocumentElement(); - if (text == null) { - return; - } - - int length = text.length(); - - for (int i = 0; i < length; i++) { - char c = text.charAt(i); - - switch (c) { - - case '&': - this._writer.write("&amp;"); - break; - - case '<': - this._writer.write("&lt;"); - break; - - case '>': - this._writer.write("&gt;"); - break; - - case 0xD: - this._writer.write("&#xD;"); - break; - - case ' ': - this._writer.write("·"); - break; - - case '\n': - this._writer.write("¶\n"); - break; - - default: - this._writer.write(c); - break; - } - } + if (documentElement == null) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; } + + if (documentElement == currentNode) { + return NODE_NOT_BEFORE_OR_AFTER_DOCUMENT_ELEMENT; + } + + for (Node x = currentNode; x != null; x = x.getNextSibling()) { + if (x == documentElement) { + return NODE_BEFORE_DOCUMENT_ELEMENT; + } + } + + return NODE_AFTER_DOCUMENT_ELEMENT; + } + + /** + * Normalizes an {@link Attr}ibute value + * + * The string value of the node is modified by replacing + *
      + *
    • all ampersands (&) with &amp;
    • + *
    • all open angle brackets (<) with &lt;
    • + *
    • all quotation mark characters with &quot;
    • + *
    • and the whitespace characters #x9, #xA, and #xD, + * with character references. The character references are written in + * uppercase hexadecimal with no leading zeroes (for example, #xD + * is represented by the character reference &#xD;)
    • + *
    + * + * @param name + * @param value + * @throws IOException + */ + private void outputAttrToWriter(String name, String value) throws IOException { + this.writer.write(" "); + this.writer.write(name); + this.writer.write("=\""); + + int length = value.length(); + + for (int i = 0; i < length; i++) { + char c = value.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '"': + this.writer.write("&quot;"); + break; + + case 0x09: // '\t' + this.writer.write("&#x9;"); + break; + + case 0x0A: // '\n' + this.writer.write("&#xA;"); + break; + + case 0x0D: // '\r' + this.writer.write("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } + } + + this.writer.write("\""); + } + + /** + * Normalizes a {@link org.w3c.dom.Comment} value + * + * @param currentPI + * @throws IOException + */ + private void outputPItoWriter(ProcessingInstruction currentPI) throws IOException { + + if (currentPI == null) { + return; + } + + this.writer.write("<?"); + + String target = currentPI.getTarget(); + int length = target.length(); + + for (int i = 0; i < length; i++) { + char c = target.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + + String data = currentPI.getData(); + + length = data.length(); + + if (length > 0) { + this.writer.write(" "); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + default: + this.writer.write(c); + break; + } + } + } + + this.writer.write("?>"); + } + + /** + * Method outputCommentToWriter + * + * @param currentComment + * @throws IOException + */ + private void outputCommentToWriter(Comment currentComment) throws IOException { + + if (currentComment == null) { + return; + } + + this.writer.write("<!--"); + + String data = currentComment.getData(); + int length = data.length(); + + for (int i = 0; i < length; i++) { + char c = data.charAt(i); + + switch (c) { + + case 0x0D: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + + this.writer.write("-->"); + } + + /** + * Method outputTextToWriter + * + * @param text + * @throws IOException + */ + private void outputTextToWriter(String text) throws IOException { + if (text == null) { + return; + } + + int length = text.length(); + + for (int i = 0; i < length; i++) { + char c = text.charAt(i); + + switch (c) { + + case '&': + this.writer.write("&amp;"); + break; + + case '<': + this.writer.write("&lt;"); + break; + + case '>': + this.writer.write("&gt;"); + break; + + case 0xD: + this.writer.write("&#xD;"); + break; + + case ' ': + this.writer.write("·"); + break; + + case '\n': + this.writer.write("¶\n"); + break; + + default: + this.writer.write(c); + break; + } + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java new file mode 100644 index 00000000000..81de122aead --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceData.java @@ -0,0 +1,34 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +/** + * An abstract representation of the result of dereferencing a ds:Reference URI. + */ +public interface ReferenceData { } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java new file mode 100644 index 00000000000..dc18c427eb7 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceNodeSetData.java @@ -0,0 +1,53 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.util.Iterator; + +import org.w3c.dom.Node; + +/** + * An abstract representation of a ReferenceData type containing a node-set. + */ +public interface ReferenceNodeSetData extends ReferenceData { + + /** + * Returns a read-only iterator over the nodes contained in this + * NodeSetData in + * + * document order. Attempts to modify the returned iterator + * via the remove method throw + * UnsupportedOperationException. + * + * @return an Iterator over the nodes in this + * NodeSetData in document order + */ + Iterator iterator(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java new file mode 100644 index 00000000000..0f59fb95bcf --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceOctetStreamData.java @@ -0,0 +1,105 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.io.InputStream; + +/** + * A representation of a ReferenceData type containing an OctetStream. + */ +public class ReferenceOctetStreamData implements ReferenceData { + private InputStream octetStream; + private String uri; + private String mimeType; + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + } + + /** + * Creates a new ReferenceOctetStreamData. + * + * @param octetStream the input stream containing the octets + * @param uri the URI String identifying the data object (may be + * null) + * @param mimeType the MIME type associated with the data object (may be + * null) + * @throws NullPointerException if octetStream is + * null + */ + public ReferenceOctetStreamData(InputStream octetStream, String uri, + String mimeType) { + if (octetStream == null) { + throw new NullPointerException("octetStream is null"); + } + this.octetStream = octetStream; + this.uri = uri; + this.mimeType = mimeType; + } + + /** + * Returns the input stream of this ReferenceOctetStreamData. + * + * @return the input stream of this ReferenceOctetStreamData. + */ + public InputStream getOctetStream() { + return octetStream; + } + + /** + * Returns the URI String identifying the data object represented by this + * ReferenceOctetStreamData. + * + * @return the URI String or null if not applicable + */ + public String getURI() { + return uri; + } + + /** + * Returns the MIME type associated with the data object represented by this + * ReferenceOctetStreamData. + * + * @return the MIME type or null if not applicable + */ + public String getMimeType() { + return mimeType; + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java new file mode 100644 index 00000000000..cfa45e0435a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/signature/reference/ReferenceSubTreeData.java @@ -0,0 +1,181 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +/* + * Copyright (c) 2005, 2008, Oracle and/or its affiliates. All rights reserved. + */ +/* + * $Id$ + */ +package com.sun.org.apache.xml.internal.security.signature.reference; + +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; +import java.util.ListIterator; +import java.util.NoSuchElementException; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + * A representation of a ReferenceNodeSetData type containing a node-set. + * This is a subtype of NodeSetData that represents a dereferenced + * same-document URI as the root of a subdocument. The main reason is + * for efficiency and performance, as some transforms can operate + * directly on the subdocument and there is no need to convert it + * first to an XPath node-set. + */ +public class ReferenceSubTreeData implements ReferenceNodeSetData { + + private boolean excludeComments; + private Node root; + + public ReferenceSubTreeData(Node root, boolean excludeComments) { + this.root = root; + this.excludeComments = excludeComments; + } + + public Iterator iterator() { + return new DelayedNodeIterator(root, excludeComments); + } + + public Node getRoot() { + return root; + } + + public boolean excludeComments() { + return excludeComments; + } + + /** + * This is an Iterator that contains a backing node-set that is + * not populated until the caller first attempts to advance the iterator. + */ + static class DelayedNodeIterator implements Iterator { + private Node root; + private List nodeSet; + private ListIterator li; + private boolean withComments; + + DelayedNodeIterator(Node root, boolean excludeComments) { + this.root = root; + this.withComments = !excludeComments; + } + + public boolean hasNext() { + if (nodeSet == null) { + nodeSet = dereferenceSameDocumentURI(root); + li = nodeSet.listIterator(); + } + return li.hasNext(); + } + + public Node next() { + if (nodeSet == null) { + nodeSet = dereferenceSameDocumentURI(root); + li = nodeSet.listIterator(); + } + if (li.hasNext()) { + return li.next(); + } else { + throw new NoSuchElementException(); + } + } + + public void remove() { + throw new UnsupportedOperationException(); + } + + /** + * Dereferences a same-document URI fragment. + * + * @param node the node (document or element) referenced by the + * URI fragment. If null, returns an empty set. + * @return a set of nodes (minus any comment nodes) + */ + private List dereferenceSameDocumentURI(Node node) { + List nodeSet = new ArrayList(); + if (node != null) { + nodeSetMinusCommentNodes(node, nodeSet, null); + } + return nodeSet; + } + + /** + * Recursively traverses the subtree, and returns an XPath-equivalent + * node-set of all nodes traversed, excluding any comment nodes, + * if specified. + * + * @param node the node to traverse + * @param nodeSet the set of nodes traversed so far + * @param the previous sibling node + */ + @SuppressWarnings("fallthrough") + private void nodeSetMinusCommentNodes(Node node, List nodeSet, + Node prevSibling) + { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE : + nodeSet.add(node); + NamedNodeMap attrs = node.getAttributes(); + if (attrs != null) { + for (int i = 0, len = attrs.getLength(); i < len; i++) { + nodeSet.add(attrs.item(i)); + } + } + Node pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; + case Node.DOCUMENT_NODE : + pSibling = null; + for (Node child = node.getFirstChild(); child != null; + child = child.getNextSibling()) { + nodeSetMinusCommentNodes(child, nodeSet, pSibling); + pSibling = child; + } + break; + case Node.TEXT_NODE : + case Node.CDATA_SECTION_NODE: + // emulate XPath which only returns the first node in + // contiguous text/cdata nodes + if (prevSibling != null && + (prevSibling.getNodeType() == Node.TEXT_NODE || + prevSibling.getNodeType() == Node.CDATA_SECTION_NODE)) { + return; + } + nodeSet.add(node); + break; + case Node.PROCESSING_INSTRUCTION_NODE : + nodeSet.add(node); + break; + case Node.COMMENT_NODE: + if (withComments) { + nodeSet.add(node); + } + } + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java index 2236e950853..68ceb3bf243 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/InvalidTransformException.java @@ -2,86 +2,84 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * * @author Christian Geuer-Pollmann */ public class InvalidTransformException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * Constructor InvalidTransformException - * - */ - public InvalidTransformException() { - super(); - } + /** + * Constructor InvalidTransformException + * + */ + public InvalidTransformException() { + super(); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - */ - public InvalidTransformException(String _msgId) { - super(_msgId); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + */ + public InvalidTransformException(String msgId) { + super(msgId); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param exArgs - */ - public InvalidTransformException(String _msgId, Object exArgs[]) { - super(_msgId, exArgs); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param exArgs + */ + public InvalidTransformException(String msgId, Object exArgs[]) { + super(msgId, exArgs); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param _originalException - */ - public InvalidTransformException(String _msgId, Exception _originalException) { - super(_msgId, _originalException); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param originalException + */ + public InvalidTransformException(String msgId, Exception originalException) { + super(msgId, originalException); + } - /** - * Constructor InvalidTransformException - * - * @param _msgId - * @param exArgs - * @param _originalException - */ - public InvalidTransformException(String _msgId, Object exArgs[], - Exception _originalException) { - super(_msgId, exArgs, _originalException); - } + /** + * Constructor InvalidTransformException + * + * @param msgId + * @param exArgs + * @param originalException + */ + public InvalidTransformException(String msgId, Object exArgs[], Exception originalException) { + super(msgId, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java index 3c910219bfd..37d67ba9f24 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transform.java @@ -263,7 +263,7 @@ public final class Transform extends SignatureElementProxy { * @return the URI representation of Transformation algorithm */ public String getURI() { - return this._constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); + return this.constructionElement.getAttributeNS(null, Constants._ATT_ALGORITHM); } /** @@ -329,7 +329,7 @@ public final class Transform extends SignatureElementProxy { private TransformSpi initializeTransform(String algorithmURI, NodeList contextNodes) throws InvalidTransformException { - this._constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); + this.constructionElement.setAttributeNS(null, Constants._ATT_ALGORITHM, algorithmURI); Class transformSpiClass = transformSpiHash.get(algorithmURI); if (transformSpiClass == null) { @@ -360,7 +360,7 @@ public final class Transform extends SignatureElementProxy { // give it to the current document if (contextNodes != null) { for (int i = 0; i < contextNodes.getLength(); i++) { - this._constructionElement.appendChild(contextNodes.item(i).cloneNode(true)); + this.constructionElement.appendChild(contextNodes.item(i).cloneNode(true)); } } return newTransformSpi; diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java index d6c16fa771e..0624c8c7759 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformParam.java @@ -2,29 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; -/** - * - * @author $Author: mullan $ - */ - public interface TransformParam { -} +} \ No newline at end of file diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java index 35aa9ff0f6e..7607d188be5 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformSpi.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; @@ -37,28 +39,13 @@ import org.xml.sax.SAXException; * @author Christian Geuer-Pollmann */ public abstract class TransformSpi { - /** - * For API compatibility not thread safe. - * @deprecated - */ - @Deprecated - protected Transform _transformObject = null; - /** - * Set the transform object. - * Depeprecated For API compatibility. - * @param transform the Transform - * @deprecated - */ - @Deprecated - protected void setTransform(Transform transform) { - this._transformObject = transform; - } + /** * The mega method which MUST be implemented by the Transformation Algorithm. * * @param input {@link XMLSignatureInput} as the input of transformation * @param os where to output this transformation. - * @param _transformObject the Transform + * @param transformObject the Transform object * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException * @throws IOException @@ -68,13 +55,12 @@ public abstract class TransformSpi { * @throws TransformationException */ protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input, OutputStream os, Transform _transformObject) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - return enginePerformTransform(input, _transformObject); + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + throw new UnsupportedOperationException(); } + /** * The mega method which MUST be implemented by the Transformation Algorithm. * In order to be compatible with preexisting Transform implementations, @@ -83,7 +69,7 @@ public abstract class TransformSpi { * implementation. * * @param input {@link XMLSignatureInput} as the input of transformation - * @param _transformObject the Transform + * @param transformObject the Transform object * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException * @throws IOException @@ -93,26 +79,14 @@ public abstract class TransformSpi { * @throws TransformationException */ protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input, Transform _transformObject) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - //Default implementation overide with a much better - try { - TransformSpi tmp = (TransformSpi) getClass().newInstance(); - tmp.setTransform(_transformObject); - return tmp.enginePerformTransform(input); - } catch (InstantiationException e) { - throw new TransformationException("",e); - } catch (IllegalAccessException e) { - throw new TransformationException("",e); - } + XMLSignatureInput input, Transform transformObject + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + return enginePerformTransform(input, null, transformObject); } /** * The mega method which MUST be implemented by the Transformation Algorithm. - * @deprecated * @param input {@link XMLSignatureInput} as the input of transformation * @return {@link XMLSignatureInput} as the result of transformation * @throws CanonicalizationException @@ -122,15 +96,13 @@ public abstract class TransformSpi { * @throws SAXException * @throws TransformationException */ - @Deprecated protected XMLSignatureInput enginePerformTransform( - XMLSignatureInput input) - throws IOException, - CanonicalizationException, InvalidCanonicalizerException, - TransformationException, ParserConfigurationException, - SAXException { - throw new UnsupportedOperationException(); + XMLSignatureInput input + ) throws IOException, CanonicalizationException, InvalidCanonicalizerException, + TransformationException, ParserConfigurationException, SAXException { + return enginePerformTransform(input, null); } + /** * Returns the URI representation of Transformation algorithm * diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java index 10e8723e238..1296475f6b1 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/TransformationException.java @@ -2,86 +2,83 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * * @author Christian Geuer-Pollmann */ public class TransformationException extends XMLSecurityException { + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * Constructor TransformationException + * + */ + public TransformationException() { + super(); + } - /** - * Constructor TransformationException - * - */ - public TransformationException() { - super(); - } + /** + * Constructor TransformationException + * + * @param msgID + */ + public TransformationException(String msgID) { + super(msgID); + } - /** - * Constructor TransformationException - * - * @param _msgID - */ - public TransformationException(String _msgID) { - super(_msgID); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param exArgs + */ + public TransformationException(String msgID, Object exArgs[]) { + super(msgID, exArgs); + } - /** - * Constructor TransformationException - * - * @param _msgID - * @param exArgs - */ - public TransformationException(String _msgID, Object exArgs[]) { - super(_msgID, exArgs); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param originalException + */ + public TransformationException(String msgID, Exception originalException) { + super(msgID, originalException); + } - /** - * Constructor TransformationException - * - * @param _msgID - * @param _originalException - */ - public TransformationException(String _msgID, Exception _originalException) { - super(_msgID, _originalException); - } - - /** - * Constructor TransformationException - * - * @param _msgID - * @param exArgs - * @param _originalException - */ - public TransformationException(String _msgID, Object exArgs[], - Exception _originalException) { - super(_msgID, exArgs, _originalException); - } + /** + * Constructor TransformationException + * + * @param msgID + * @param exArgs + * @param originalException + */ + public TransformationException(String msgID, Object exArgs[], Exception originalException) { + super(msgID, exArgs, originalException); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java index ce44e1713e4..7f29fd6a9f9 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/Transforms.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms; @@ -51,56 +53,64 @@ import org.w3c.dom.NodeList; */ public class Transforms extends SignatureElementProxy { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(Transforms.class.getName()); /** Canonicalization - Required Canonical XML (omits comments) */ public static final String TRANSFORM_C14N_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N_OMIT_COMMENTS; + /** Canonicalization - Recommended Canonical XML with Comments */ public static final String TRANSFORM_C14N_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS; + /** Canonicalization - Required Canonical XML 1.1 (omits comments) */ public static final String TRANSFORM_C14N11_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N11_OMIT_COMMENTS; + /** Canonicalization - Recommended Canonical XML 1.1 with Comments */ public static final String TRANSFORM_C14N11_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N11_WITH_COMMENTS; + /** Canonicalization - Required Exclusive Canonicalization (omits comments) */ public static final String TRANSFORM_C14N_EXCL_OMIT_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_OMIT_COMMENTS; + /** Canonicalization - Recommended Exclusive Canonicalization with Comments */ public static final String TRANSFORM_C14N_EXCL_WITH_COMMENTS = Canonicalizer.ALGO_ID_C14N_EXCL_WITH_COMMENTS; + /** Transform - Optional XSLT */ public static final String TRANSFORM_XSLT = "http://www.w3.org/TR/1999/REC-xslt-19991116"; + /** Transform - Required base64 decoding */ public static final String TRANSFORM_BASE64_DECODE = Constants.SignatureSpecNS + "base64"; + /** Transform - Recommended XPath */ public static final String TRANSFORM_XPATH = "http://www.w3.org/TR/1999/REC-xpath-19991116"; + /** Transform - Required Enveloped Signature */ public static final String TRANSFORM_ENVELOPED_SIGNATURE = Constants.SignatureSpecNS + "enveloped-signature"; + /** Transform - XPointer */ public static final String TRANSFORM_XPOINTER = "http://www.w3.org/TR/2001/WD-xptr-20010108"; - /** Transform - XPath Filter v2.0 */ - public static final String TRANSFORM_XPATH2FILTER04 - = "http://www.w3.org/2002/04/xmldsig-filter2"; + /** Transform - XPath Filter */ public static final String TRANSFORM_XPATH2FILTER = "http://www.w3.org/2002/06/xmldsig-filter2"; - /** Transform - XPath Filter CHGP private */ - public static final String TRANSFORM_XPATHFILTERCHGP - = "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; - Element []transforms; + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(Transforms.class.getName()); + + private Element[] transforms; protected Transforms() { }; + private boolean secureValidation; + /** * Constructs {@link Transforms}. * @@ -109,7 +119,7 @@ public class Transforms extends SignatureElementProxy { */ public Transforms(Document doc) { super(doc); - XMLUtils.addReturnToElement(this._constructionElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -125,24 +135,27 @@ public class Transforms extends SignatureElementProxy { * @throws XMLSignatureException */ public Transforms(Element element, String BaseURI) - throws DOMException, XMLSignatureException, - InvalidTransformException, TransformationException, - XMLSecurityException { - + throws DOMException, XMLSignatureException, InvalidTransformException, + TransformationException, XMLSecurityException { super(element, BaseURI); int numberOfTransformElems = this.getLength(); if (numberOfTransformElems == 0) { - // At least one Transform element must be present. Bad. - Object exArgs[] = { Constants._TAG_TRANSFORM, - Constants._TAG_TRANSFORMS }; + Object exArgs[] = { Constants._TAG_TRANSFORM, Constants._TAG_TRANSFORMS }; throw new TransformationException("xml.WrongContent", exArgs); } } + /** + * Set whether secure validation is enabled or not. The default is false. + */ + public void setSecureValidation(boolean secureValidation) { + this.secureValidation = secureValidation; + } + /** * Adds the Transform with the specified Transform * algorithm URI @@ -151,14 +164,13 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @throws TransformationException */ - public void addTransform(String transformURI) - throws TransformationException { - + public void addTransform(String transformURI) throws TransformationException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); + } - Transform transform = new Transform(this._doc, transformURI); + Transform transform = new Transform(this.doc, transformURI); this.addTransform(transform); } catch (InvalidTransformException ex) { @@ -174,16 +186,15 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @param contextElement * @throws TransformationException - * @see Transform#getInstance(Document doc, String algorithmURI, Element childElement) */ public void addTransform(String transformURI, Element contextElement) - throws TransformationException { - + throws TransformationException { try { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transformURI + ")"); + } - Transform transform = new Transform(this._doc, transformURI, contextElement); + Transform transform = new Transform(this.doc, transformURI, contextElement); this.addTransform(transform); } catch (InvalidTransformException ex) { @@ -199,13 +210,12 @@ public class Transforms extends SignatureElementProxy { * transformation is applied to data * @param contextNodes * @throws TransformationException - * @see Transform#getInstance(Document doc, String algorithmURI, NodeList contextNodes) */ public void addTransform(String transformURI, NodeList contextNodes) - throws TransformationException { + throws TransformationException { try { - Transform transform = new Transform(this._doc, transformURI, contextNodes); + Transform transform = new Transform(this.doc, transformURI, contextNodes); this.addTransform(transform); } catch (InvalidTransformException ex) { throw new TransformationException("empty", ex); @@ -218,13 +228,14 @@ public class Transforms extends SignatureElementProxy { * @param transform {@link Transform} object */ private void addTransform(Transform transform) { - if (log.isLoggable(java.util.logging.Level.FINE)) + if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Transforms.addTransform(" + transform.getURI() + ")"); + } Element transformElement = transform.getElement(); - this._constructionElement.appendChild(transformElement); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(transformElement); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -236,7 +247,8 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput) throws TransformationException { + XMLSignatureInput xmlSignatureInput + ) throws TransformationException { return performTransforms(xmlSignatureInput, null); } @@ -250,21 +262,22 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public XMLSignatureInput performTransforms( - XMLSignatureInput xmlSignatureInput, OutputStream os) - throws TransformationException { - + XMLSignatureInput xmlSignatureInput, OutputStream os + ) throws TransformationException { try { - int last=this.getLength()-1; + int last = this.getLength() - 1; for (int i = 0; i < last; i++) { Transform t = this.item(i); + String uri = t.getURI(); if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + t.getURI() - + " transform"); + log.log(java.util.logging.Level.FINE, "Perform the (" + i + ")th " + uri + " transform"); } + checkSecureValidation(t); xmlSignatureInput = t.performTransform(xmlSignatureInput); } - if (last>=0) { + if (last >= 0) { Transform t = this.item(last); + checkSecureValidation(t); xmlSignatureInput = t.performTransform(xmlSignatureInput, os); } @@ -278,16 +291,26 @@ public class Transforms extends SignatureElementProxy { } } + private void checkSecureValidation(Transform transform) throws TransformationException { + String uri = transform.getURI(); + if (secureValidation && Transforms.TRANSFORM_XSLT.equals(uri)) { + Object exArgs[] = { uri }; + + throw new TransformationException( + "signature.Transform.ForbiddenTransform", exArgs + ); + } + } + /** * Return the nonnegative number of transformations. * * @return the number of transformations */ - public int getLength() - { + public int getLength() { if (transforms == null) { - transforms = XMLUtils.selectDsNodes - (this._constructionElement.getFirstChild(), "Transform"); + transforms = + XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform"); } return transforms.length; } @@ -301,13 +324,12 @@ public class Transforms extends SignatureElementProxy { * @throws TransformationException */ public Transform item(int i) throws TransformationException { - try { if (transforms == null) { - transforms = XMLUtils.selectDsNodes - (this._constructionElement.getFirstChild(), "Transform"); + transforms = + XMLUtils.selectDsNodes(this.constructionElement.getFirstChild(), "Transform"); } - return new Transform(transforms[i], this._baseURI); + return new Transform(transforms[i], this.baseURI); } catch (XMLSecurityException ex) { throw new TransformationException("empty", ex); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java index 15c1b576df5..7d8cc74e1ef 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHere.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; - - import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.dtm.DTM; @@ -36,7 +36,6 @@ import com.sun.org.apache.xpath.internal.res.XPATHErrorResources; import org.w3c.dom.Document; import org.w3c.dom.Node; - /** * The 'here()' function returns a node-set containing the attribute or * processing instruction node or the parent element of the text node @@ -56,107 +55,98 @@ import org.w3c.dom.Node; */ public class FuncHere extends Function { - /** - * - */ - private static final long serialVersionUID = 1L; + /** + * + */ + private static final long serialVersionUID = 1L; - /** - * The here function returns a node-set containing the attribute or - * processing instruction node or the parent element of the text node - * that directly bears the XPath expression. This expression results - * in an error if the containing XPath expression does not appear in the - * same XML document against which the XPath expression is being evaluated. - * - * @param xctxt - * @return the xobject - * @throws javax.xml.transform.TransformerException - */ - public XObject execute(XPathContext xctxt) - throws javax.xml.transform.TransformerException { + /** + * The here function returns a node-set containing the attribute or + * processing instruction node or the parent element of the text node + * that directly bears the XPath expression. This expression results + * in an error if the containing XPath expression does not appear in the + * same XML document against which the XPath expression is being evaluated. + * + * @param xctxt + * @return the xobject + * @throws javax.xml.transform.TransformerException + */ + @Override + public XObject execute(XPathContext xctxt) + throws javax.xml.transform.TransformerException { - Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); + Node xpathOwnerNode = (Node) xctxt.getOwnerObject(); - if (xpathOwnerNode == null) { - return null; - } + if (xpathOwnerNode == null) { + return null; + } - int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); + int xpathOwnerNodeDTM = xctxt.getDTMHandleFromNode(xpathOwnerNode); - int currentNode = xctxt.getCurrentNode(); - DTM dtm = xctxt.getDTM(currentNode); - int docContext = dtm.getDocument(); + int currentNode = xctxt.getCurrentNode(); + DTM dtm = xctxt.getDTM(currentNode); + int docContext = dtm.getDocument(); - if (DTM.NULL == docContext) { - error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); - } + if (DTM.NULL == docContext) { + error(xctxt, XPATHErrorResources.ER_CONTEXT_HAS_NO_OWNERDOC, null); + } - { + { + // check whether currentNode and the node containing the XPath expression + // are in the same document + Document currentDoc = + XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); + Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); - // check whether currentNode and the node containing the XPath expression - // are in the same document - Document currentDoc = - XMLUtils.getOwnerDocument(dtm.getNode(currentNode)); - Document xpathOwnerDoc = XMLUtils.getOwnerDocument(xpathOwnerNode); + if (currentDoc != xpathOwnerDoc) { + throw new TransformerException(I18n.translate("xpath.funcHere.documentsDiffer")); + } + } - if (currentDoc != xpathOwnerDoc) { - throw new TransformerException(I18n - .translate("xpath.funcHere.documentsDiffer")); - } - } + XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); + NodeSetDTM nodeSet = nodes.mutableNodeset(); - XNodeSet nodes = new XNodeSet(xctxt.getDTMManager()); - NodeSetDTM nodeSet = nodes.mutableNodeset(); + { + int hereNode = DTM.NULL; - { - int hereNode = DTM.NULL; + switch (dtm.getNodeType(xpathOwnerNodeDTM)) { - switch (dtm.getNodeType(xpathOwnerNodeDTM)) { + case Node.ATTRIBUTE_NODE : + case Node.PROCESSING_INSTRUCTION_NODE : { + // returns a node-set containing the attribute / processing instruction node + hereNode = xpathOwnerNodeDTM; - case Node.ATTRIBUTE_NODE : { - // returns a node-set containing the attribute - hereNode = xpathOwnerNodeDTM; + nodeSet.addNode(hereNode); - nodeSet.addNode(hereNode); + break; + } + case Node.TEXT_NODE : { + // returns a node-set containing the parent element of the + // text node that directly bears the XPath expression + hereNode = dtm.getParent(xpathOwnerNodeDTM); - break; - } - case Node.PROCESSING_INSTRUCTION_NODE : { - // returns a node-set containing the processing instruction node - hereNode = xpathOwnerNodeDTM; + nodeSet.addNode(hereNode); - nodeSet.addNode(hereNode); + break; + } + default : + break; + } + } - break; - } - case Node.TEXT_NODE : { - // returns a node-set containing the parent element of the - // text node that directly bears the XPath expression - hereNode = dtm.getParent(xpathOwnerNodeDTM); + /** $todo$ Do I have to do this detach() call? */ + nodeSet.detach(); - nodeSet.addNode(hereNode); + return nodes; + } - break; - } - default : - break; - } - } - - /** $todo$ Do I have to do this detach() call? */ - nodeSet.detach(); - - return nodes; - } - - /** - * No arguments to process, so this does nothing. - * @param vars - * @param globalsSize - */ - @SuppressWarnings("rawtypes") - public void fixupVariables(java.util.Vector vars, int globalsSize) { - - // do nothing - } + /** + * No arguments to process, so this does nothing. + * @param vars + * @param globalsSize + */ + @SuppressWarnings("rawtypes") + public void fixupVariables(java.util.Vector vars, int globalsSize) { + // do nothing + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java deleted file mode 100644 index 6cc15ae3898..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/FuncHereContext.java +++ /dev/null @@ -1,143 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.sun.org.apache.xml.internal.security.transforms.implementations; - - - -import com.sun.org.apache.xml.internal.dtm.DTMManager; -import com.sun.org.apache.xml.internal.security.utils.I18n; -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import com.sun.org.apache.xpath.internal.XPathContext; -import org.w3c.dom.Node; - - -/** - * {@link FuncHereContext} extends {@link XPathContext} for supplying context - * for the here() function. The here() function needs to know - * where in an XML instance the XPath text string appeared. This can be - * in {@link org.w3c.dom.Text}, {@link org.w3c.dom.Attr}ibutes and {@ProcessingInstrinction} nodes. The - * correct node must be supplied to the constructor of {@link FuncHereContext}. - * The supplied Node MUST contain the XPath which is to be executed. - * - *
    - * From: Scott_Boag\@lotus.com
    - * To: Christian Geuer-Pollmann 
    - * CC: xalan-dev@xml.apache.org
    - * Subject: Re: Cleanup of XPathContext & definition of XSLTContext
    - * Date: Tue, 21 Aug 2001 18:36:24 -0400
    - *
    - * > My point is to say to get this baby to run, the XPath must have a
    - * > possibility to retrieve the information where itself occured in a
    - * > document.
    - *
    - * It sounds to me like you have to derive an XMLSigContext from the
    - * XPathContext?
    - *
    - * > and supplied the Node which contains the xpath string as "owner". Question:
    - * > Is this the correct use of the owner object? It works, but I don't know
    - * > whether this is correct from the xalan-philosophy...
    - *
    - * Philosophically it's fine.  The owner is the TransformerImpl if XPath is
    - * running under XSLT.  If it is not running under XSLT, it can be whatever
    - * you want.
    - *
    - * -scott
    - * 
    - * - * @author $Author: mullan $ - * @see com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere - * @see com.sun.org.apache.xml.internal.security.utils.XPathFuncHereAPI - * @see XML Signature - The here() function - */ -public class FuncHereContext extends XPathContext { - - /** - * This constuctor is disabled because if we use the here() function we - * always need to know in which node the XPath occured. - */ - private FuncHereContext() {} - - /** - * Constructor FuncHereContext - * - * @param owner - */ - public FuncHereContext(Node owner) { - super(owner); - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param xpathContext - */ - public FuncHereContext(Node owner, XPathContext xpathContext) { - - super(owner); - - try { - super.m_dtmManager = xpathContext.getDTMManager(); - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param previouslyUsed - */ - public FuncHereContext(Node owner, CachedXPathAPI previouslyUsed) { - - super(owner); - - try { - super.m_dtmManager = previouslyUsed.getXPathContext().getDTMManager(); - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } - - /** - * Constructor FuncHereContext - * - * @param owner - * @param dtmManager - */ - public FuncHereContext(Node owner, DTMManager dtmManager) { - - super(owner); - - try { - super.m_dtmManager = dtmManager; - } catch (IllegalAccessError iae) { - throw new IllegalAccessError(I18n.translate("endorsed.jdk1.4.0") - + " Original message was \"" - + iae.getMessage() + "\""); - } - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java index b1d3de8bce7..206d31016cd 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformBase64Decode.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; - - import java.io.BufferedInputStream; import java.io.IOException; import java.io.OutputStream; @@ -72,115 +72,106 @@ import org.xml.sax.SAXException; */ public class TransformBase64Decode extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_BASE64_DECODE; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_BASE64_DECODE; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return TransformBase64Decode.implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return TransformBase64Decode.implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return {@link XMLSignatureInput} as the result of transformation - * @inheritDoc - * @throws CanonicalizationException - * @throws IOException - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws IOException, CanonicalizationException, - TransformationException { - return enginePerformTransform(input, null, _transformObject); - } + /** + * Method enginePerformTransform + * + * @param input + * @return {@link XMLSignatureInput} as the result of transformation + * @inheritDoc + * @throws CanonicalizationException + * @throws IOException + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, Transform transformObject + ) throws IOException, CanonicalizationException, TransformationException { + return enginePerformTransform(input, null, transformObject); + } - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, - OutputStream os, Transform _transformObject) - throws IOException, CanonicalizationException, - TransformationException { - try { - if (input.isElement()) { - Node el=input.getSubNode(); - if (input.getSubNode().getNodeType()==Node.TEXT_NODE) { - el=el.getParentNode(); - } - StringBuffer sb=new StringBuffer(); - traverseElement((Element)el,sb); - if (os==null) { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws IOException, CanonicalizationException, TransformationException { + try { + if (input.isElement()) { + Node el = input.getSubNode(); + if (input.getSubNode().getNodeType() == Node.TEXT_NODE) { + el = el.getParentNode(); + } + StringBuilder sb = new StringBuilder(); + traverseElement((Element)el, sb); + if (os == null) { + byte[] decodedBytes = Base64.decode(sb.toString()); + return new XMLSignatureInput(decodedBytes); + } + Base64.decode(sb.toString(), os); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(os); + return output; + } + + if (input.isOctetStream() || input.isNodeSet()) { + if (os == null) { + byte[] base64Bytes = input.getBytes(); + byte[] decodedBytes = Base64.decode(base64Bytes); + return new XMLSignatureInput(decodedBytes); + } + if (input.isByteArray() || input.isNodeSet()) { + Base64.decode(input.getBytes(), os); + } else { + Base64.decode(new BufferedInputStream(input.getOctetStreamReal()), os); + } + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(os); + return output; + } + + try { + //Exceptional case there is current not text case testing this(Before it was a + //a common case). + DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); + dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + Document doc = + dbf.newDocumentBuilder().parse(input.getOctetStream()); + + Element rootNode = doc.getDocumentElement(); + StringBuilder sb = new StringBuilder(); + traverseElement(rootNode, sb); byte[] decodedBytes = Base64.decode(sb.toString()); return new XMLSignatureInput(decodedBytes); - } - Base64.decode(sb.toString(),os); - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(os); - return output; - - } - if (input.isOctetStream() || input.isNodeSet()) { - - - if (os==null) { - byte[] base64Bytes = input.getBytes(); - byte[] decodedBytes = Base64.decode(base64Bytes); - return new XMLSignatureInput(decodedBytes); - } - if (input.isByteArray() || input.isNodeSet()) { - Base64.decode(input.getBytes(),os); - } else { - Base64.decode(new BufferedInputStream(input.getOctetStreamReal()) - ,os); - } - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(os); - return output; - - - } - - try { - // Exceptional case there is current not text case testing this - // (before it was a a common case). - DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); - dbf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); - Document doc = - dbf.newDocumentBuilder().parse(input.getOctetStream()); - - Element rootNode = doc.getDocumentElement(); - StringBuffer sb = new StringBuffer(); - traverseElement(rootNode,sb); - byte[] decodedBytes = Base64.decode(sb.toString()); - - return new XMLSignatureInput(decodedBytes); - } catch (ParserConfigurationException e) { - throw new TransformationException("c14n.Canonicalizer.Exception",e); - } catch (SAXException e) { - throw new TransformationException("SAX exception", e); - } + } catch (ParserConfigurationException e) { + throw new TransformationException("c14n.Canonicalizer.Exception",e); + } catch (SAXException e) { + throw new TransformationException("SAX exception", e); + } } catch (Base64DecodingException e) { throw new TransformationException("Base64Decoding", e); } - } + } - void traverseElement(org.w3c.dom.Element node,StringBuffer sb) { - Node sibling=node.getFirstChild(); - while (sibling!=null) { - switch (sibling.getNodeType()) { - case Node.ELEMENT_NODE: - traverseElement((Element)sibling,sb); - break; - case Node.TEXT_NODE: - sb.append(((Text)sibling).getData()); + void traverseElement(org.w3c.dom.Element node, StringBuilder sb) { + Node sibling = node.getFirstChild(); + while (sibling != null) { + switch (sibling.getNodeType()) { + case Node.ELEMENT_NODE: + traverseElement((Element)sibling, sb); + break; + case Node.TEXT_NODE: + sb.append(((Text)sibling).getData()); } - sibling=sibling.getNextSibling(); + sibling = sibling.getNextSibling(); } - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java index 1b0c7fb6448..9c94199be05 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -37,39 +39,30 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformC14N extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_OMIT_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_OMIT_COMMENTS; + /** + * @inheritDoc + */ + protected String engineGetURI() { + return TransformC14N.implementedTransformURI; + } - /** - * @inheritDoc - */ - protected String engineGetURI() { - return TransformC14N.implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte[] result = null; - result=c14n.engineCanonicalize(input); - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + Canonicalizer20010315OmitComments c14n = new Canonicalizer20010315OmitComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = null; + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { output.setOutputStream(os); - } - return output; - } + } + return output; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java index a4f6e34025f..b3510fc06b5 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,15 +43,9 @@ public class TransformC14N11 extends TransformSpi { return Transforms.TRANSFORM_C14N11_OMIT_COMMENTS; } - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform transform) - throws CanonicalizationException { - return enginePerformTransform(input, null, transform); - } - - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, OutputStream os, Transform transform) - throws CanonicalizationException { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transform + ) throws CanonicalizationException { Canonicalizer11_OmitComments c14n = new Canonicalizer11_OmitComments(); if (os != null) { c14n.setWriter(os); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java index 1a7a213e718..e01f17312c7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14N11_WithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,15 +43,9 @@ public class TransformC14N11_WithComments extends TransformSpi { return Transforms.TRANSFORM_C14N11_WITH_COMMENTS; } - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform transform) - throws CanonicalizationException { - return enginePerformTransform(input, null, transform); - } - - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, OutputStream os, Transform transform) - throws CanonicalizationException { + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transform + ) throws CanonicalizationException { Canonicalizer11_WithComments c14n = new Canonicalizer11_WithComments(); if (os != null) { diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java index f4b2407055b..3b7bdd13691 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusive.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -36,71 +38,59 @@ import org.w3c.dom.Element; /** * Class TransformC14NExclusive * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ */ public class TransformC14NExclusive extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_OMIT_COMMENTS; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return the transformed of the input - * @throws CanonicalizationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + try { + String inclusiveNamespaces = null; - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - try { - String inclusiveNamespaces = null; + if (transformObject.length( + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1 + ) { + Element inclusiveElement = + XMLUtils.selectNode( + transformObject.getElement().getFirstChild(), + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, + 0 + ); - if (_transformObject - .length(InclusiveNamespaces - .ExclusiveCanonicalizationNamespace, InclusiveNamespaces - ._TAG_EC_INCLUSIVENAMESPACES) == 1) { - Element inclusiveElement = - XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - InclusiveNamespaces.ExclusiveCanonicalizationNamespace, - InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0); + inclusiveNamespaces = + new InclusiveNamespaces( + inclusiveElement, transformObject.getBaseURI()).getInclusiveNamespaces(); + } - inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, - _transformObject.getBaseURI()).getInclusiveNamespaces(); - } + Canonicalizer20010315ExclOmitComments c14n = + new Canonicalizer20010315ExclOmitComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces); - Canonicalizer20010315ExclOmitComments c14n = - new Canonicalizer20010315ExclOmitComments(); - if (os!=null) { - c14n.setWriter(os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { - output.setOutputStream(os); - } - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { + output.setOutputStream(os); + } + return output; + } catch (XMLSecurityException ex) { + throw new CanonicalizationException("empty", ex); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java index 2380750d052..d1456b30e00 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NExclusiveWithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -41,59 +43,54 @@ import org.w3c.dom.Element; */ public class TransformC14NExclusiveWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_EXCL_WITH_COMMENTS; - /** - * Method engineGetURI - *@inheritDoc - * - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + *@inheritDoc + * + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { + try { + String inclusiveNamespaces = null; - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { - try { - String inclusiveNamespaces = null; + if (transformObject.length( + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES) == 1 + ) { + Element inclusiveElement = + XMLUtils.selectNode( + transformObject.getElement().getFirstChild(), + InclusiveNamespaces.ExclusiveCanonicalizationNamespace, + InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES, + 0 + ); - if (_transformObject - .length(InclusiveNamespaces - .ExclusiveCanonicalizationNamespace, InclusiveNamespaces - ._TAG_EC_INCLUSIVENAMESPACES) == 1) { - Element inclusiveElement = - XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - InclusiveNamespaces.ExclusiveCanonicalizationNamespace, - InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES,0); + inclusiveNamespaces = + new InclusiveNamespaces( + inclusiveElement, transformObject.getBaseURI() + ).getInclusiveNamespaces(); + } - inclusiveNamespaces = new InclusiveNamespaces(inclusiveElement, - _transformObject.getBaseURI()).getInclusiveNamespaces(); + Canonicalizer20010315ExclWithComments c14n = + new Canonicalizer20010315ExclWithComments(); + if (os != null) { + c14n.setWriter(os); + } + byte[] result = c14n.engineCanonicalize(input, inclusiveNamespaces); + XMLSignatureInput output = new XMLSignatureInput(result); + + return output; + } catch (XMLSecurityException ex) { + throw new CanonicalizationException("empty", ex); } - - Canonicalizer20010315ExclWithComments c14n = - new Canonicalizer20010315ExclWithComments(); - if (os!=null) { - c14n.setWriter( os); - } - byte []result; - result =c14n.engineCanonicalize(input, inclusiveNamespaces); - XMLSignatureInput output=new XMLSignatureInput(result); - - return output; - } catch (XMLSecurityException ex) { - throw new CanonicalizationException("empty", ex); - } - } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java index b1087076d27..33aee9cd753 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformC14NWithComments.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -37,37 +39,31 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformC14NWithComments extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_C14N_WITH_COMMENTS; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_C14N_WITH_COMMENTS; - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws CanonicalizationException { - return enginePerformTransform(input, null, _transformObject); - } - - /** @inheritDoc */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream os, Transform _transformObject) - throws CanonicalizationException { + /** @inheritDoc */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws CanonicalizationException { Canonicalizer20010315WithComments c14n = new Canonicalizer20010315WithComments(); - if (os!=null) { - c14n.setWriter( os); + if (os != null) { + c14n.setWriter(os); } - byte[] result = null; - result=c14n.engineCanonicalize(input); - XMLSignatureInput output=new XMLSignatureInput(result); - if (os!=null) { - output.setOutputStream(os); - } - return output; - } + byte[] result = null; + result = c14n.engineCanonicalize(input); + XMLSignatureInput output = new XMLSignatureInput(result); + if (os != null) { + output.setOutputStream(os); + } + return output; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java index c447468bd63..9f108c1bb10 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformEnvelopedSignature.java @@ -2,24 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; +import java.io.OutputStream; + import com.sun.org.apache.xml.internal.security.signature.NodeFilter; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -39,99 +43,99 @@ import org.w3c.dom.Node; */ public class TransformEnvelopedSignature extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_ENVELOPED_SIGNATURE; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_ENVELOPED_SIGNATURE; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } - - /** - * @inheritDoc - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - - - - /** - * If the actual input is an octet stream, then the application MUST - * convert the octet stream to an XPath node-set suitable for use by - * Canonical XML with Comments. (A subsequent application of the - * REQUIRED Canonical XML algorithm would strip away these comments.) - * - * ... - * - * The evaluation of this expression includes all of the document's nodes - * (including comments) in the node-set representing the octet stream. - */ - - Node signatureElement = _transformObject.getElement(); - - - signatureElement = searchSignatureElement(signatureElement); - input.setExcludeNode(signatureElement); - input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); - return input; - - // - - - } - - /** - * @param signatureElement - * @return the node that is the signature - * @throws TransformationException - */ - private static Node searchSignatureElement(Node signatureElement) throws TransformationException { - boolean found=false; - - while (true) { - if ((signatureElement == null) - || (signatureElement.getNodeType() == Node.DOCUMENT_NODE)) { - break; - } - Element el=(Element)signatureElement; - if (el.getNamespaceURI().equals(Constants.SignatureSpecNS) - && - el.getLocalName().equals(Constants._TAG_SIGNATURE)) { - found = true; - break; - } - - signatureElement = signatureElement.getParentNode(); - } - - if (!found) { - throw new TransformationException( - "envelopedSignatureTransformNotInSignatureElement"); - } - return signatureElement; + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; } - static class EnvelopedNodeFilter implements NodeFilter { - Node exclude; - EnvelopedNodeFilter(Node n) { - exclude=n; + + /** + * @inheritDoc + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + /** + * If the actual input is an octet stream, then the application MUST + * convert the octet stream to an XPath node-set suitable for use by + * Canonical XML with Comments. (A subsequent application of the + * REQUIRED Canonical XML algorithm would strip away these comments.) + * + * ... + * + * The evaluation of this expression includes all of the document's nodes + * (including comments) in the node-set representing the octet stream. + */ + + Node signatureElement = transformObject.getElement(); + + signatureElement = searchSignatureElement(signatureElement); + input.setExcludeNode(signatureElement); + input.addNodeFilter(new EnvelopedNodeFilter(signatureElement)); + return input; + } + + /** + * @param signatureElement + * @return the node that is the signature + * @throws TransformationException + */ + private static Node searchSignatureElement(Node signatureElement) + throws TransformationException { + boolean found = false; + + while (true) { + if (signatureElement == null + || signatureElement.getNodeType() == Node.DOCUMENT_NODE) { + break; + } + Element el = (Element) signatureElement; + if (el.getNamespaceURI().equals(Constants.SignatureSpecNS) + && el.getLocalName().equals(Constants._TAG_SIGNATURE)) { + found = true; + break; + } + + signatureElement = signatureElement.getParentNode(); } - public int isNodeIncludeDO(Node n, int level) { - if ((n==exclude)) - return -1; - return 1; + + if (!found) { + throw new TransformationException( + "transform.envelopedSignatureTransformNotInSignatureElement"); + } + return signatureElement; } + + static class EnvelopedNodeFilter implements NodeFilter { + + Node exclude; + + EnvelopedNodeFilter(Node n) { + exclude = n; + } + + public int isNodeIncludeDO(Node n, int level) { + if (n == exclude) { + return -1; + } + return 1; + } + /** * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) */ public int isNodeInclude(Node n) { - if ((n==exclude) || XMLUtils.isDescendantOrSelf(exclude,n)) - return -1; - return 1; + if (n == exclude || XMLUtils.isDescendantOrSelf(exclude, n)) { + return -1; + } + return 1; //return !XMLUtils.isDescendantOrSelf(exclude,n); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java index f7411344f42..db958096963 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath.java @@ -2,24 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; +import java.io.OutputStream; + import javax.xml.transform.TransformerException; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityRuntimeException; @@ -29,12 +33,10 @@ import com.sun.org.apache.xml.internal.security.transforms.Transform; import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.objects.XObject; +import com.sun.org.apache.xml.internal.security.utils.XPathAPI; +import com.sun.org.apache.xml.internal.security.utils.XPathFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Element; import org.w3c.dom.Node; @@ -51,118 +53,112 @@ import org.w3c.dom.Node; */ public class TransformXPath extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = Transforms.TRANSFORM_XPATH; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + /** + * If the actual input is an octet stream, then the application MUST + * convert the octet stream to an XPath node-set suitable for use by + * Canonical XML with Comments. (A subsequent application of the + * REQUIRED Canonical XML algorithm would strip away these comments.) + * + * ... + * + * The evaluation of this expression includes all of the document's nodes + * (including comments) in the node-set representing the octet stream. + */ + Element xpathElement = + XMLUtils.selectDsNode( + transformObject.getElement().getFirstChild(), Constants._TAG_XPATH, 0); - try { + if (xpathElement == null) { + Object exArgs[] = { "ds:XPath", "Transform" }; - /** - * If the actual input is an octet stream, then the application MUST - * convert the octet stream to an XPath node-set suitable for use by - * Canonical XML with Comments. (A subsequent application of the - * REQUIRED Canonical XML algorithm would strip away these comments.) - * - * ... - * - * The evaluation of this expression includes all of the document's nodes - * (including comments) in the node-set representing the octet stream. - */ - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); + throw new TransformationException("xml.WrongContent", exArgs); + } + Node xpathnode = xpathElement.getChildNodes().item(0); + String str = XMLUtils.getStrFromNode(xpathnode); + input.setNeedsToBeExpanded(needsCircumvent(str)); + if (xpathnode == null) { + throw new DOMException( + DOMException.HIERARCHY_REQUEST_ERR, "Text must be in ds:Xpath" + ); + } + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + input.addNodeFilter(new XPathNodeFilter(xpathElement, xpathnode, str, xpathAPIInstance)); + input.setNodeSet(true); + return input; + } catch (DOMException ex) { + throw new TransformationException("empty", ex); + } + } - - Element xpathElement =XMLUtils.selectDsNode( - _transformObject.getElement().getFirstChild(), - Constants._TAG_XPATH,0); - - if (xpathElement == null) { - Object exArgs[] = { "ds:XPath", "Transform" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - Node xpathnode = xpathElement.getChildNodes().item(0); - String str=CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - input.setNeedsToBeExpanded(needsCircunvent(str)); - if (xpathnode == null) { - throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, - "Text must be in ds:Xpath"); - } - - - input.addNodeFilter(new XPathNodeFilter( xpathElement, xpathnode, str)); - input.setNodeSet(true); - return input; - } catch (DOMException ex) { - throw new TransformationException("empty", ex); - } - } - - /** - * @param str - * @return true if needs to be circunvent for bug. - */ - private boolean needsCircunvent(String str) { - //return true; - //return false; + /** + * @param str + * @return true if needs to be circumvent for bug. + */ + private boolean needsCircumvent(String str) { return (str.indexOf("namespace") != -1) || (str.indexOf("name()") != -1); } static class XPathNodeFilter implements NodeFilter { - PrefixResolverDefault prefixResolver; - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); + + XPathAPI xPathAPI; Node xpathnode; + Element xpathElement; String str; - XPathNodeFilter(Element xpathElement, - Node xpathnode, String str) { - this.xpathnode=xpathnode; - this.str=str; - prefixResolver =new PrefixResolverDefault(xpathElement); + + XPathNodeFilter(Element xpathElement, Node xpathnode, String str, XPathAPI xPathAPI) { + this.xpathnode = xpathnode; + this.str = str; + this.xpathElement = xpathElement; + this.xPathAPI = xPathAPI; } /** * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) */ public int isNodeInclude(Node currentNode) { - XObject includeInResult; try { - includeInResult = xPathFuncHereAPI.eval(currentNode, - xpathnode, str,prefixResolver); - if (includeInResult.bool()) - return 1; + boolean include = xPathAPI.evaluate(currentNode, xpathnode, str, xpathElement); + if (include) { + return 1; + } return 0; } catch (TransformerException e) { Object[] eArgs = {currentNode}; - throw new XMLSecurityRuntimeException - ("signature.Transform.node", eArgs, e); + throw new XMLSecurityRuntimeException("signature.Transform.node", eArgs, e); } catch (Exception e) { - Object[] eArgs = {currentNode, new Short(currentNode.getNodeType())}; - throw new XMLSecurityRuntimeException - ("signature.Transform.nodeAndType",eArgs, e); + Object[] eArgs = {currentNode, Short.valueOf(currentNode.getNodeType())}; + throw new XMLSecurityRuntimeException("signature.Transform.nodeAndType",eArgs, e); } } + public int isNodeIncludeDO(Node n, int level) { - return isNodeInclude(n); + return isNodeInclude(n); } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java index 2d805d13dd2..d35142222ae 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPath2Filter.java @@ -2,30 +2,30 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; - - import java.io.IOException; +import java.io.OutputStream; import java.util.ArrayList; import java.util.HashSet; -import java.util.Iterator; import java.util.List; import java.util.Set; @@ -42,9 +42,9 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.transforms.params.XPath2FilterContainer; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathAPIHolder; -import com.sun.org.apache.xml.internal.security.utils.CachedXPathFuncHereAPI; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.XPathAPI; +import com.sun.org.apache.xml.internal.security.utils.XPathFactory; import org.w3c.dom.DOMException; import org.w3c.dom.Document; import org.w3c.dom.Element; @@ -55,254 +55,241 @@ import org.xml.sax.SAXException; /** * Implements the XML Signature XPath Filter v2.0 * - * @author $Author: mullan $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ public class TransformXPath2Filter extends TransformSpi { - /** {@link java.util.logging} logging facility */ -// static java.util.logging.Logger log = -// java.util.logging.Logger.getLogger( -// TransformXPath2Filter.class.getName()); + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XPATH2FILTER; - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPATH2FILTER; - //J- - // contains the type of the filter + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - // contains the node set + /** + * Method enginePerformTransform + * @inheritDoc + * @param input + * + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { + try { + List unionNodes = new ArrayList(); + List subtractNodes = new ArrayList(); + List intersectNodes = new ArrayList(); - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + Element[] xpathElements = + XMLUtils.selectNodes( + transformObject.getElement().getFirstChild(), + XPath2FilterContainer.XPathFilter2NS, + XPath2FilterContainer._TAG_XPATH2 + ); + if (xpathElements.length == 0) { + Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; + throw new TransformationException("xml.WrongContent", exArgs); + } + Document inputDoc = null; + if (input.getSubNode() != null) { + inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); + } else { + inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); + } - /** - * Method enginePerformTransform - * @inheritDoc - * @param input - * - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { - CachedXPathAPIHolder.setDoc(_transformObject.getElement().getOwnerDocument()); - try { - List unionNodes=new ArrayList(); - List substractNodes=new ArrayList(); - List intersectNodes=new ArrayList(); + for (int i = 0; i < xpathElements.length; i++) { + Element xpathElement = xpathElements[i]; - CachedXPathFuncHereAPI xPathFuncHereAPI = - new CachedXPathFuncHereAPI(CachedXPathAPIHolder.getCachedXPathAPI()); + XPath2FilterContainer xpathContainer = + XPath2FilterContainer.newInstance(xpathElement, input.getSourceURI()); + String str = + XMLUtils.getStrFromNode(xpathContainer.getXPathFilterTextNode()); - Element []xpathElements =XMLUtils.selectNodes( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2); - int noOfSteps = xpathElements.length; + XPathFactory xpathFactory = XPathFactory.newInstance(); + XPathAPI xpathAPIInstance = xpathFactory.newXPathAPI(); + NodeList subtreeRoots = + xpathAPIInstance.selectNodeList( + inputDoc, + xpathContainer.getXPathFilterTextNode(), + str, + xpathContainer.getElement()); + if (xpathContainer.isIntersect()) { + intersectNodes.add(subtreeRoots); + } else if (xpathContainer.isSubtract()) { + subtractNodes.add(subtreeRoots); + } else if (xpathContainer.isUnion()) { + unionNodes.add(subtreeRoots); + } + } - if (noOfSteps == 0) { - Object exArgs[] = { Transforms.TRANSFORM_XPATH2FILTER, "XPath" }; - - throw new TransformationException("xml.WrongContent", exArgs); - } - - Document inputDoc = null; - if (input.getSubNode() != null) { - inputDoc = XMLUtils.getOwnerDocument(input.getSubNode()); - } else { - inputDoc = XMLUtils.getOwnerDocument(input.getNodeSet()); - } - - for (int i = 0; i < noOfSteps; i++) { - Element xpathElement =XMLUtils.selectNode( - _transformObject.getElement().getFirstChild(), - XPath2FilterContainer.XPathFilter2NS, - XPath2FilterContainer._TAG_XPATH2,i); - XPath2FilterContainer xpathContainer = - XPath2FilterContainer.newInstance(xpathElement, - input.getSourceURI()); - - - NodeList subtreeRoots = xPathFuncHereAPI.selectNodeList(inputDoc, - xpathContainer.getXPathFilterTextNode(), - CachedXPathFuncHereAPI.getStrFromNode(xpathContainer.getXPathFilterTextNode()), - xpathContainer.getElement()); - if (xpathContainer.isIntersect()) { - intersectNodes.add(subtreeRoots); - } else if (xpathContainer.isSubtract()) { - substractNodes.add(subtreeRoots); - } else if (xpathContainer.isUnion()) { - unionNodes.add(subtreeRoots); - } - } - - - input.addNodeFilter(new XPath2NodeFilter(unionNodes, substractNodes, - intersectNodes)); - input.setNodeSet(true); - return input; - } catch (TransformerException ex) { - throw new TransformationException("empty", ex); - } catch (DOMException ex) { - throw new TransformationException("empty", ex); - } catch (CanonicalizationException ex) { - throw new TransformationException("empty", ex); - } catch (InvalidCanonicalizerException ex) { - throw new TransformationException("empty", ex); - } catch (XMLSecurityException ex) { - throw new TransformationException("empty", ex); - } catch (SAXException ex) { - throw new TransformationException("empty", ex); - } catch (IOException ex) { - throw new TransformationException("empty", ex); - } catch (ParserConfigurationException ex) { - throw new TransformationException("empty", ex); - } - } + input.addNodeFilter( + new XPath2NodeFilter(unionNodes, subtractNodes, intersectNodes) + ); + input.setNodeSet(true); + return input; + } catch (TransformerException ex) { + throw new TransformationException("empty", ex); + } catch (DOMException ex) { + throw new TransformationException("empty", ex); + } catch (CanonicalizationException ex) { + throw new TransformationException("empty", ex); + } catch (InvalidCanonicalizerException ex) { + throw new TransformationException("empty", ex); + } catch (XMLSecurityException ex) { + throw new TransformationException("empty", ex); + } catch (SAXException ex) { + throw new TransformationException("empty", ex); + } catch (IOException ex) { + throw new TransformationException("empty", ex); + } catch (ParserConfigurationException ex) { + throw new TransformationException("empty", ex); + } + } } class XPath2NodeFilter implements NodeFilter { - boolean hasUnionFilter; - boolean hasSubstractFilter; - boolean hasIntersectFilter; - XPath2NodeFilter(List unionNodes, List substractNodes, - List intersectNodes) { - hasUnionFilter=!unionNodes.isEmpty(); - this.unionNodes=convertNodeListToSet(unionNodes); - hasSubstractFilter=!substractNodes.isEmpty(); - this.substractNodes=convertNodeListToSet(substractNodes); - hasIntersectFilter=!intersectNodes.isEmpty(); - this.intersectNodes=convertNodeListToSet(intersectNodes); + + boolean hasUnionFilter; + boolean hasSubtractFilter; + boolean hasIntersectFilter; + Set unionNodes; + Set subtractNodes; + Set intersectNodes; + int inSubtract = -1; + int inIntersect = -1; + int inUnion = -1; + + XPath2NodeFilter(List unionNodes, List subtractNodes, + List intersectNodes) { + hasUnionFilter = !unionNodes.isEmpty(); + this.unionNodes = convertNodeListToSet(unionNodes); + hasSubtractFilter = !subtractNodes.isEmpty(); + this.subtractNodes = convertNodeListToSet(subtractNodes); + hasIntersectFilter = !intersectNodes.isEmpty(); + this.intersectNodes = convertNodeListToSet(intersectNodes); + } + + /** + * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) + */ + public int isNodeInclude(Node currentNode) { + int result = 1; + + if (hasSubtractFilter && rooted(currentNode, subtractNodes)) { + result = -1; + } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { + result = 0; } - Set unionNodes; - Set substractNodes; - Set intersectNodes; + //TODO OPTIMIZE + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if (rooted(currentNode, unionNodes)) { + return 1; + } + result = 0; + } + return result; + } - /** - * @see com.sun.org.apache.xml.internal.security.signature.NodeFilter#isNodeInclude(org.w3c.dom.Node) - */ - public int isNodeInclude(Node currentNode) { - int result=1; + public int isNodeIncludeDO(Node n, int level) { + int result = 1; + if (hasSubtractFilter) { + if ((inSubtract == -1) || (level <= inSubtract)) { + if (inList(n, subtractNodes)) { + inSubtract = level; + } else { + inSubtract = -1; + } + } + if (inSubtract != -1){ + result = -1; + } + } + if (result != -1 && hasIntersectFilter + && ((inIntersect == -1) || (level <= inIntersect))) { + if (!inList(n, intersectNodes)) { + inIntersect = -1; + result = 0; + } else { + inIntersect = level; + } + } - if (hasSubstractFilter && rooted(currentNode, substractNodes)) { - result = -1; - } else if (hasIntersectFilter && !rooted(currentNode, intersectNodes)) { - result = 0; - } + if (level <= inUnion) { + inUnion = -1; + } + if (result == 1) { + return 1; + } + if (hasUnionFilter) { + if ((inUnion == -1) && inList(n, unionNodes)) { + inUnion = level; + } + if (inUnion != -1) { + return 1; + } + result=0; + } - //TODO OPTIMIZE - if (result==1) - return 1; - if (hasUnionFilter) { - if (rooted(currentNode, unionNodes)) { - return 1; - } - result=0; - } - return result; + return result; + } - } - int inSubstract=-1; - int inIntersect=-1; - int inUnion=-1; - public int isNodeIncludeDO(Node n, int level) { - int result=1; - if (hasSubstractFilter) { - if ((inSubstract==-1) || (level<=inSubstract)) { - if (inList(n, substractNodes)) { - inSubstract=level; - } else { - inSubstract=-1; - } - } - if (inSubstract!=-1){ - result=-1; - } - } - if (result!=-1){ - if (hasIntersectFilter) { - if ((inIntersect==-1) || (level<=inIntersect)) { - if (!inList(n, intersectNodes)) { - inIntersect=-1; - result=0; - } else { - inIntersect=level; - } - } - } - } + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean rooted(Node currentNode, Set nodeList) { + if (nodeList.isEmpty()) { + return false; + } + if (nodeList.contains(currentNode)) { + return true; + } + for (Node rootNode : nodeList) { + if (XMLUtils.isDescendantOrSelf(rootNode, currentNode)) { + return true; + } + } + return false; + } - if (level<=inUnion) - inUnion=-1; - if (result==1) - return 1; - if (hasUnionFilter) { - if ((inUnion==-1) && inList(n, unionNodes)) { - inUnion=level; - } - if (inUnion!=-1) - return 1; - result=0; - } - - return result; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean rooted(Node currentNode, Set nodeList ) { - if (nodeList.isEmpty()) { - return false; - } - if (nodeList.contains(currentNode)) { - return true; - } - - for(Node rootNode : nodeList) { - if (XMLUtils.isDescendantOrSelf(rootNode,currentNode)) { - return true; - } - } - return false; - } - - /** - * Method rooted - * @param currentNode - * @param nodeList - * - * @return if rooted bye the rootnodes - */ - static boolean inList(Node currentNode, Set nodeList ) { - return nodeList.contains(currentNode); - } - - private static Set convertNodeListToSet(List l){ - Set result=new HashSet(); + /** + * Method rooted + * @param currentNode + * @param nodeList + * + * @return if rooted bye the rootnodes + */ + static boolean inList(Node currentNode, Set nodeList) { + return nodeList.contains(currentNode); + } + private static Set convertNodeListToSet(List l) { + Set result = new HashSet(); for (NodeList rootNodes : l) { - int length = rootNodes.getLength(); - for (int i = 0; i < length; i++) { - Node rootNode = rootNodes.item(i); - result.add(rootNode); - } + int length = rootNodes.getLength(); + + for (int i = 0; i < length; i++) { + Node rootNode = rootNodes.item(i); + result.add(rootNode); + } } return result; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java index 71ba9604d1c..e2cae9b0237 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXPointer.java @@ -2,26 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; - - +import java.io.OutputStream; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.transforms.Transform; @@ -29,8 +30,6 @@ import com.sun.org.apache.xml.internal.security.transforms.TransformSpi; import com.sun.org.apache.xml.internal.security.transforms.TransformationException; import com.sun.org.apache.xml.internal.security.transforms.Transforms; - - /** * Class TransformXPointer * @@ -38,30 +37,29 @@ import com.sun.org.apache.xml.internal.security.transforms.Transforms; */ public class TransformXPointer extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XPOINTER; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XPOINTER; - /** @inheritDoc */ - protected String engineGetURI() { - return implementedTransformURI; - } + /** @inheritDoc */ + protected String engineGetURI() { + return implementedTransformURI; + } - /** - * Method enginePerformTransform - * - * @param input - * @return {@link XMLSignatureInput} as the result of transformation - * @throws TransformationException - * - */ - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input, Transform _transformObject) - throws TransformationException { + /** + * Method enginePerformTransform + * + * @param input + * @return {@link XMLSignatureInput} as the result of transformation + * @throws TransformationException + */ + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream os, Transform transformObject + ) throws TransformationException { - Object exArgs[] = { implementedTransformURI }; + Object exArgs[] = { implementedTransformURI }; - throw new TransformationException( - "signature.Transform.NotYetImplemented", exArgs); - } + throw new TransformationException("signature.Transform.NotYetImplemented", exArgs); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java index 12c8f636ca4..bf9adf5096e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/implementations/TransformXSLT.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2007 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.implementations; @@ -24,7 +26,6 @@ import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; -import java.lang.reflect.Method; import javax.xml.XMLConstants; import javax.xml.transform.Source; @@ -55,132 +56,112 @@ import org.w3c.dom.Element; */ public class TransformXSLT extends TransformSpi { - /** Field implementedTransformURI */ - public static final String implementedTransformURI = - Transforms.TRANSFORM_XSLT; - //J- - static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; - static final String defaultXSLTSpecNSprefix = "xslt"; - static final String XSLTSTYLESHEET = "stylesheet"; + /** Field implementedTransformURI */ + public static final String implementedTransformURI = + Transforms.TRANSFORM_XSLT; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - TransformXSLT.class.getName()); + static final String XSLTSpecNS = "http://www.w3.org/1999/XSL/Transform"; + static final String defaultXSLTSpecNSprefix = "xslt"; + static final String XSLTSTYLESHEET = "stylesheet"; - /** - * Method engineGetURI - * - * @inheritDoc - */ - protected String engineGetURI() { - return implementedTransformURI; - } + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(TransformXSLT.class.getName()); - /** - * Method enginePerformTransform - * - * @param input the input for this transform - * @return the result of this Transform - * @throws IOException - * @throws TransformationException - */ - protected XMLSignatureInput enginePerformTransform - (XMLSignatureInput input, Transform _transformObject) - throws IOException, - TransformationException { - return enginePerformTransform(input, null, _transformObject); - } + /** + * Method engineGetURI + * + * @inheritDoc + */ + protected String engineGetURI() { + return implementedTransformURI; + } - protected XMLSignatureInput enginePerformTransform(XMLSignatureInput input,OutputStream baos, Transform _transformObject) - throws IOException, - TransformationException { - try { - Element transformElement = _transformObject.getElement(); + protected XMLSignatureInput enginePerformTransform( + XMLSignatureInput input, OutputStream baos, Transform transformObject + ) throws IOException, TransformationException { + try { + Element transformElement = transformObject.getElement(); - Element _xsltElement = - XMLUtils.selectNode(transformElement.getFirstChild(), - XSLTSpecNS,"stylesheet", 0); + Element xsltElement = + XMLUtils.selectNode(transformElement.getFirstChild(), XSLTSpecNS, "stylesheet", 0); - if (_xsltElement == null) { - Object exArgs[] = { "xslt:stylesheet", "Transform" }; + if (xsltElement == null) { + Object exArgs[] = { "xslt:stylesheet", "Transform" }; - throw new TransformationException("xml.WrongContent", exArgs); - } + throw new TransformationException("xml.WrongContent", exArgs); + } - TransformerFactory tFactory = TransformerFactory.newInstance(); + TransformerFactory tFactory = TransformerFactory.newInstance(); + // Process XSLT stylesheets in a secure manner + tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); - // Process XSLT stylesheets in a secure manner - tFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, - Boolean.TRUE); - /* - * This transform requires an octet stream as input. If the actual - * input is an XPath node-set, then the signature application should - * attempt to convert it to octets (apply Canonical XML]) as described - * in the Reference Processing Model (section 4.3.3.2). - */ - Source xmlSource = - new StreamSource(new ByteArrayInputStream(input.getBytes())); - Source stylesheet; + /* + * This transform requires an octet stream as input. If the actual + * input is an XPath node-set, then the signature application should + * attempt to convert it to octets (apply Canonical XML]) as described + * in the Reference Processing Model (section 4.3.3.2). + */ + Source xmlSource = + new StreamSource(new ByteArrayInputStream(input.getBytes())); + Source stylesheet; - /* - * This complicated transformation of the stylesheet itself is necessary - * because of the need to get the pure style sheet. If we simply say - * Source stylesheet = new DOMSource(this._xsltElement); - * whereby this._xsltElement is not the rootElement of the Document, - * this causes problems; - * so we convert the stylesheet to byte[] and use this as input stream - */ - { - ByteArrayOutputStream os = new ByteArrayOutputStream(); - Transformer transformer = tFactory.newTransformer(); - DOMSource source = new DOMSource(_xsltElement); - StreamResult result = new StreamResult(os); + /* + * This complicated transformation of the stylesheet itself is necessary + * because of the need to get the pure style sheet. If we simply say + * Source stylesheet = new DOMSource(this.xsltElement); + * whereby this.xsltElement is not the rootElement of the Document, + * this causes problems; + * so we convert the stylesheet to byte[] and use this as input stream + */ + { + ByteArrayOutputStream os = new ByteArrayOutputStream(); + Transformer transformer = tFactory.newTransformer(); + DOMSource source = new DOMSource(xsltElement); + StreamResult result = new StreamResult(os); - transformer.transform(source, result); + transformer.transform(source, result); - stylesheet = - new StreamSource(new ByteArrayInputStream(os.toByteArray())); - } + stylesheet = + new StreamSource(new ByteArrayInputStream(os.toByteArray())); + } - Transformer transformer = tFactory.newTransformer(stylesheet); + Transformer transformer = tFactory.newTransformer(stylesheet); - // Force Xalan to use \n as line separator on all OSes. This - // avoids OS specific signature validation failures due to line - // separator differences in the transformed output. Unfortunately, - // this is not a standard JAXP property so will not work with non-Xalan - // implementations. - try { - transformer.setOutputProperty - ("{http://xml.apache.org/xalan}line-separator", "\n"); - } catch (Exception e) { - log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " - + e.getMessage()); - } + // Force Xalan to use \n as line separator on all OSes. This + // avoids OS specific signature validation failures due to line + // separator differences in the transformed output. Unfortunately, + // this is not a standard JAXP property so will not work with non-Xalan + // implementations. + try { + transformer.setOutputProperty("{http://xml.apache.org/xalan}line-separator", "\n"); + } catch (Exception e) { + log.log(java.util.logging.Level.WARNING, "Unable to set Xalan line-separator property: " + e.getMessage()); + } + + if (baos == null) { + ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); + StreamResult outputTarget = new StreamResult(baos1); + transformer.transform(xmlSource, outputTarget); + return new XMLSignatureInput(baos1.toByteArray()); + } + StreamResult outputTarget = new StreamResult(baos); - if (baos==null) { - ByteArrayOutputStream baos1 = new ByteArrayOutputStream(); - StreamResult outputTarget = new StreamResult(baos1); transformer.transform(xmlSource, outputTarget); - return new XMLSignatureInput(baos1.toByteArray()); - } - StreamResult outputTarget = new StreamResult(baos); + XMLSignatureInput output = new XMLSignatureInput((byte[])null); + output.setOutputStream(baos); + return output; + } catch (XMLSecurityException ex) { + Object exArgs[] = { ex.getMessage() }; - transformer.transform(xmlSource, outputTarget); - XMLSignatureInput output=new XMLSignatureInput((byte[])null); - output.setOutputStream(baos); - return output; - } catch (XMLSecurityException ex) { - Object exArgs[] = { ex.getMessage() }; + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } catch (TransformerConfigurationException ex) { + Object exArgs[] = { ex.getMessage() }; - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } catch (TransformerConfigurationException ex) { - Object exArgs[] = { ex.getMessage() }; + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } catch (TransformerException ex) { + Object exArgs[] = { ex.getMessage() }; - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } catch (TransformerException ex) { - Object exArgs[] = { ex.getMessage() }; - - throw new TransformationException("generic.EmptyMessage", exArgs, ex); - } - } + throw new TransformationException("generic.EmptyMessage", exArgs, ex); + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java index f615881bade..2b6f5da2f16 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/InclusiveNamespaces.java @@ -2,30 +2,28 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - - -import java.util.Iterator; import java.util.Set; import java.util.SortedSet; -import java.util.StringTokenizer; import java.util.TreeSet; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; @@ -34,7 +32,6 @@ import com.sun.org.apache.xml.internal.security.utils.ElementProxy; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * This Object serves as Content for the ds:Transforms for exclusive * Canonicalization. @@ -44,136 +41,130 @@ import org.w3c.dom.Element; * * @author Christian Geuer-Pollmann */ -public class InclusiveNamespaces extends ElementProxy - implements TransformParam { +public class InclusiveNamespaces extends ElementProxy implements TransformParam { - /** Field _TAG_EC_INCLUSIVENAMESPACES */ - public static final String _TAG_EC_INCLUSIVENAMESPACES = - "InclusiveNamespaces"; + /** Field _TAG_EC_INCLUSIVENAMESPACES */ + public static final String _TAG_EC_INCLUSIVENAMESPACES = + "InclusiveNamespaces"; - /** Field _ATT_EC_PREFIXLIST */ - public static final String _ATT_EC_PREFIXLIST = "PrefixList"; + /** Field _ATT_EC_PREFIXLIST */ + public static final String _ATT_EC_PREFIXLIST = "PrefixList"; - /** Field ExclusiveCanonicalizationNamespace */ - public static final String ExclusiveCanonicalizationNamespace = - "http://www.w3.org/2001/10/xml-exc-c14n#"; + /** Field ExclusiveCanonicalizationNamespace */ + public static final String ExclusiveCanonicalizationNamespace = + "http://www.w3.org/2001/10/xml-exc-c14n#"; - /** - * Constructor XPathContainer - * - * @param doc - * @param prefixList - */ - public InclusiveNamespaces(Document doc, String prefixList) { - this(doc, InclusiveNamespaces.prefixStr2Set(prefixList)); - } + /** + * Constructor XPathContainer + * + * @param doc + * @param prefixList + */ + public InclusiveNamespaces(Document doc, String prefixList) { + this(doc, InclusiveNamespaces.prefixStr2Set(prefixList)); + } - /** - * Constructor InclusiveNamespaces - * - * @param doc - * @param prefixes - */ - public InclusiveNamespaces(Document doc, Set prefixes) { + /** + * Constructor InclusiveNamespaces + * + * @param doc + * @param prefixes + */ + public InclusiveNamespaces(Document doc, Set prefixes) { + super(doc); - super(doc); + SortedSet prefixList = null; + if (prefixes instanceof SortedSet) { + prefixList = (SortedSet)prefixes; + } else { + prefixList = new TreeSet(prefixes); + } - StringBuffer sb = new StringBuffer(); - SortedSet prefixList = new TreeSet(prefixes); + StringBuilder sb = new StringBuilder(); + for (String prefix : prefixList) { + if (prefix.equals("xmlns")) { + sb.append("#default "); + } else { + sb.append(prefix + " "); + } + } + this.constructionElement.setAttributeNS( + null, InclusiveNamespaces._ATT_EC_PREFIXLIST, sb.toString().trim()); + } + /** + * Constructor InclusiveNamespaces + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public InclusiveNamespaces(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - for (String prefix : prefixList) { - if (prefix.equals("xmlns")) { - sb.append("#default "); - } else { - sb.append(prefix + " "); - } - } + /** + * Method getInclusiveNamespaces + * + * @return The Inclusive Namespace string + */ + public String getInclusiveNamespaces() { + return this.constructionElement.getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); + } - this._constructionElement - .setAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST, - sb.toString().trim()); - } + /** + * Decodes the inclusiveNamespaces String and returns all + * selected namespace prefixes as a Set. The #default + * namespace token is represented as an empty namespace prefix + * ("xmlns"). + *
    + * The String inclusiveNamespaces=" xenc ds #default" + * is returned as a Set containing the following Strings: + *
      + *
    • xmlns
    • + *
    • xenc
    • + *
    • ds
    • + *
    + * + * @param inclusiveNamespaces + * @return A set to string + */ + public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + SortedSet prefixes = new TreeSet(); - /** - * Method getInclusiveNamespaces - * - * @return The Inclusive Namespace string - */ - public String getInclusiveNamespaces() { - return this._constructionElement - .getAttributeNS(null, InclusiveNamespaces._ATT_EC_PREFIXLIST); - } + if ((inclusiveNamespaces == null) || (inclusiveNamespaces.length() == 0)) { + return prefixes; + } - /** - * Constructor InclusiveNamespaces - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public InclusiveNamespaces(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + String[] tokens = inclusiveNamespaces.split("\\s"); + for (String prefix : tokens) { + if (prefix.equals("#default")) { + prefixes.add("xmlns"); + } else { + prefixes.add(prefix); + } + } - /** - * Decodes the inclusiveNamespaces String and returns all - * selected namespace prefixes as a Set. The #default - * namespace token is represented as an empty namespace prefix - * ("xmlns"). - *
    - * The String inclusiveNamespaces=" xenc ds #default" - * is returned as a Set containing the following Strings: - *
      - *
    • xmlns
    • - *
    • xenc
    • - *
    • ds
    • - *
    - * - * @param inclusiveNamespaces - * @return A set to string - */ - public static SortedSet prefixStr2Set(String inclusiveNamespaces) { + return prefixes; + } - SortedSet prefixes = new TreeSet(); + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public String getBaseNamespace() { + return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; + } - if ((inclusiveNamespaces == null) - || (inclusiveNamespaces.length() == 0)) { - return prefixes; - } - - StringTokenizer st = new StringTokenizer(inclusiveNamespaces, " \t\r\n"); - - while (st.hasMoreTokens()) { - String prefix = st.nextToken(); - - if (prefix.equals("#default")) { - prefixes.add("xmlns" ); - } else { - prefixes.add( prefix); - } - } - - return prefixes; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public String getBaseNamespace() { - return InclusiveNamespaces.ExclusiveCanonicalizationNamespace; - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public String getBaseLocalName() { - return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public String getBaseLocalName() { + return InclusiveNamespaces._TAG_EC_INCLUSIVENAMESPACES; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java index 366f31acf80..19de51976cf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; @@ -32,284 +32,261 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -public class XPath2FilterContainer extends ElementProxy - implements TransformParam { +public class XPath2FilterContainer extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER */ - private static final String _ATT_FILTER = "Filter"; + /** Field _ATT_FILTER */ + private static final String _ATT_FILTER = "Filter"; - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _ATT_FILTER_VALUE_UNION = "union"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _ATT_FILTER_VALUE_UNION = "union"; - /** Field INTERSECT */ - public static final String INTERSECT = - XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT; + /** Field INTERSECT */ + public static final String INTERSECT = + XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT; - /** Field SUBTRACT */ - public static final String SUBTRACT = - XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT; + /** Field SUBTRACT */ + public static final String SUBTRACT = + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT; - /** Field UNION */ - public static final String UNION = - XPath2FilterContainer._ATT_FILTER_VALUE_UNION; + /** Field UNION */ + public static final String UNION = + XPath2FilterContainer._ATT_FILTER_VALUE_UNION; - /** Field _TAG_XPATH2 */ - public static final String _TAG_XPATH2 = "XPath"; + /** Field _TAG_XPATH2 */ + public static final String _TAG_XPATH2 = "XPath"; - /** Field XPathFiler2NS */ - public static final String XPathFilter2NS = - "http://www.w3.org/2002/06/xmldsig-filter2"; + /** Field XPathFiler2NS */ + public static final String XPathFilter2NS = + "http://www.w3.org/2002/06/xmldsig-filter2"; - /** - * Constructor XPath2FilterContainer - * - */ - private XPath2FilterContainer() { + /** + * Constructor XPath2FilterContainer + * + */ + private XPath2FilterContainer() { + // no instantiation + } - // no instantiation - } + /** + * Constructor XPath2FilterContainer + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer(Document doc, String xpath2filter, String filterType) { + super(doc); - /** - * Constructor XPath2FilterContainer - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer(Document doc, String xpath2filter, - String filterType) { + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer._ATT_FILTER, filterType); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } - super(doc); + /** + * Constructor XPath2FilterContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer(Element element, String BaseURI) throws XMLSecurityException { - this._constructionElement - .setAttributeNS(null, XPath2FilterContainer._ATT_FILTER, filterType); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - } + super(element, BaseURI); - /** - * Constructor XPath2FilterContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer(Element element, String BaseURI) - throws XMLSecurityException { + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer._ATT_FILTER); - super(element, BaseURI); + if (!filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT) + && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT) + && !filterStr.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) { + Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr, + XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT + + ", " + + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT + + " or " + + XPath2FilterContainer._ATT_FILTER_VALUE_UNION }; - String filterStr = this._constructionElement.getAttributeNS(null, - XPath2FilterContainer._ATT_FILTER); + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } - if (!filterStr - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION)) { - Object exArgs[] = { XPath2FilterContainer._ATT_FILTER, filterStr, - XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT - + ", " - + XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT - + " or " - + XPath2FilterContainer._ATT_FILTER_VALUE_UNION }; + /** + * Creates a new XPath2FilterContainer with the filter type "intersect". + * + * @param doc + * @param xpath2filter + * @return the filter. + */ + public static XPath2FilterContainer newInstanceIntersect( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } + /** + * Creates a new XPath2FilterContainer with the filter type "subtract". + * + * @param doc + * @param xpath2filter + * @return the filter. + */ + public static XPath2FilterContainer newInstanceSubtract(Document doc, String xpath2filter) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } - /** - * Creates a new XPath2FilterContainer with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceIntersect(Document doc, - String xpath2filter) { + /** + * Creates a new XPath2FilterContainer with the filter type "union". + * + * @param doc + * @param xpath2filter + * @return the filter + */ + public static XPath2FilterContainer newInstanceUnion(Document doc, String xpath2filter) { + return new XPath2FilterContainer( + doc, xpath2filter, XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT); - } + /** + * Method newInstances + * + * @param doc + * @param params + * @return the nodelist with the data + */ + public static NodeList newInstances(Document doc, String[][] params) { + HelperNodeList nl = new HelperNodeList(); - /** - * Creates a new XPath2FilterContainer with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the filter. - */ - public static XPath2FilterContainer newInstanceSubtract(Document doc, - String xpath2filter) { + XMLUtils.addReturnToElement(doc, nl); - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT); - } + for (int i = 0; i < params.length; i++) { + String type = params[i][0]; + String xpath = params[i][1]; - /** - * Creates a new XPath2FilterContainer with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the filter - */ - public static XPath2FilterContainer newInstanceUnion(Document doc, - String xpath2filter) { + if (!(type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT) + || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT) + || type.equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION))){ + throw new IllegalArgumentException("The type(" + i + ")=\"" + type + + "\" is illegal"); + } - return new XPath2FilterContainer(doc, xpath2filter, - XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION); - } + XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); - /** - * Method newInstances - * - * @param doc - * @param params - * @return the nodelist with the data - */ - public static NodeList newInstances(Document doc, String[][] params) { + nl.appendChild(c.getElement()); + XMLUtils.addReturnToElement(doc, nl); + } - HelperNodeList nl = new HelperNodeList(); + return nl; + } - XMLUtils.addReturnToElement(doc, nl); + /** + * Creates a XPath2FilterContainer from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * @return the filter + * + * @throws XMLSecurityException + */ + public static XPath2FilterContainer newInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPath2FilterContainer(element, BaseURI); + } - for (int i = 0; i < params.length; i++) { - String type = params[i][0]; - String xpath = params[i][1]; + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); + } - if (!(type.equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_INTERSECT) || type - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_SUBTRACT) || type - .equals(XPath2FilterContainer - ._ATT_FILTER_VALUE_UNION))) { - throw new IllegalArgumentException("The type(" + i + ")=\"" + type - + "\" is illegal"); - } + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); + } - XPath2FilterContainer c = new XPath2FilterContainer(doc, xpath, type); + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer._ATT_FILTER + ).equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); + } - nl.appendChild(c.getElement()); - XMLUtils.addReturnToElement(doc, nl); - } + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } - return nl; - } + /** + * Returns the first Text node which contains information from the XPath 2 + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { - /** - * Creates a XPath2FilterContainer from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * @return the filter - * - * @throws XMLSecurityException - */ - public static XPath2FilterContainer newInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPath2FilterContainer(element, BaseURI); - } + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_INTERSECT); - } + return null; + } - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { + /** + * Method getBaseLocalName + * + * @return the XPATH2 tag + */ + public final String getBaseLocalName() { + return XPath2FilterContainer._TAG_XPATH2; + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_SUBTRACT); - } - - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer._ATT_FILTER) - .equals(XPath2FilterContainer._ATT_FILTER_VALUE_UNION); - } - - /** - * Returns the XPath 2 Filter String - * - * @return the XPath 2 Filter String - */ - public String getXPathFilterStr() { - return this.getTextFromTextChild(); - } - - /** - * Returns the first Text node which contains information from the XPath 2 - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @return the first Text node which contains information from the XPath 2 Filter String - */ - public Node getXPathFilterTextNode() { - - NodeList children = this._constructionElement.getChildNodes(); - int length = children.getLength(); - - for (int i = 0; i < length; i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - return children.item(i); - } - } - - return null; - } - - /** - * Method getBaseLocalName - * - * @return the XPATH2 tag - */ - public final String getBaseLocalName() { - return XPath2FilterContainer._TAG_XPATH2; - } - - /** - * Method getBaseNamespace - * - * @return XPATH2 tag namespace - */ - public final String getBaseNamespace() { - return XPath2FilterContainer.XPathFilter2NS; - } + /** + * Method getBaseNamespace + * + * @return XPATH2 tag namespace + */ + public final String getBaseNamespace() { + return XPath2FilterContainer.XPathFilter2NS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java index 25008eed743..2eed2cb1fdf 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPath2FilterContainer04.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; @@ -31,237 +31,222 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; - /** * Implements the parameters for the XPath Filter v2.0. * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see XPath Filter v2.0 (TR) - * @see XPath Filter v2.0 (editors copy) */ -public class XPath2FilterContainer04 extends ElementProxy - implements TransformParam { +public class XPath2FilterContainer04 extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER */ - private static final String _ATT_FILTER = "Filter"; + /** Field _ATT_FILTER */ + private static final String _ATT_FILTER = "Filter"; - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _ATT_FILTER_VALUE_INTERSECT = "intersect"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _ATT_FILTER_VALUE_SUBTRACT = "subtract"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _ATT_FILTER_VALUE_UNION = "union"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _ATT_FILTER_VALUE_UNION = "union"; - /** Field _TAG_XPATH2 */ - public static final String _TAG_XPATH2 = "XPath"; + /** Field _TAG_XPATH2 */ + public static final String _TAG_XPATH2 = "XPath"; - /** Field XPathFiler2NS */ - public static final String XPathFilter2NS = - "http://www.w3.org/2002/04/xmldsig-filter2"; + /** Field XPathFiler2NS */ + public static final String XPathFilter2NS = + "http://www.w3.org/2002/04/xmldsig-filter2"; - /** - * Constructor XPath2FilterContainer04 - * - */ - private XPath2FilterContainer04() { + /** + * Constructor XPath2FilterContainer04 + * + */ + private XPath2FilterContainer04() { - // no instantiation - } + // no instantiation + } - /** - * Constructor XPath2FilterContainer04 - * - * @param doc - * @param xpath2filter - * @param filterType - */ - private XPath2FilterContainer04(Document doc, String xpath2filter, - String filterType) { + /** + * Constructor XPath2FilterContainer04 + * + * @param doc + * @param xpath2filter + * @param filterType + */ + private XPath2FilterContainer04(Document doc, String xpath2filter, String filterType) { + super(doc); - super(doc); + this.constructionElement.setAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER, filterType); - this._constructionElement.setAttributeNS(null, XPath2FilterContainer04._ATT_FILTER, - filterType); + if ((xpath2filter.length() > 2) + && (!Character.isWhitespace(xpath2filter.charAt(0)))) { + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + XMLUtils.addReturnToElement(this.constructionElement); + } else { + this.constructionElement.appendChild(doc.createTextNode(xpath2filter)); + } + } - if ((xpath2filter.length() > 2) - && (!Character.isWhitespace(xpath2filter.charAt(0)))) { - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(doc.createTextNode(xpath2filter)); - XMLUtils.addReturnToElement(this._constructionElement); - } else { - this._constructionElement - .appendChild(doc.createTextNode(xpath2filter)); - } - } + /** + * Constructor XPath2FilterContainer04 + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPath2FilterContainer04(Element element, String BaseURI) + throws XMLSecurityException { - /** - * Constructor XPath2FilterContainer04 - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPath2FilterContainer04(Element element, String BaseURI) - throws XMLSecurityException { + super(element, BaseURI); - super(element, BaseURI); + String filterStr = + this.constructionElement.getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER); - String filterStr = - this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER); + if (!filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT) + && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT) + && !filterStr.equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) { + Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr, + XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT + + ", " + + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT + + " or " + + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION }; - if (!filterStr - .equals(XPath2FilterContainer04 - ._ATT_FILTER_VALUE_INTERSECT) &&!filterStr - .equals(XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT) &&!filterStr - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION)) { - Object exArgs[] = { XPath2FilterContainer04._ATT_FILTER, filterStr, - XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT - + ", " - + XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT - + " or " - + XPath2FilterContainer04._ATT_FILTER_VALUE_UNION }; + throw new XMLSecurityException("attributeValueIllegal", exArgs); + } + } - throw new XMLSecurityException("attributeValueIllegal", exArgs); - } - } + /** + * Creates a new XPath2FilterContainer04 with the filter type "intersect". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceIntersect( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "intersect". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceIntersect(Document doc, - String xpath2filter) { + /** + * Creates a new XPath2FilterContainer04 with the filter type "subtract". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceSubtract( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_INTERSECT); - } + /** + * Creates a new XPath2FilterContainer04 with the filter type "union". + * + * @param doc + * @param xpath2filter + * @return the instance + */ + public static XPath2FilterContainer04 newInstanceUnion( + Document doc, String xpath2filter + ) { + return new XPath2FilterContainer04( + doc, xpath2filter, XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "subtract". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceSubtract(Document doc, - String xpath2filter) { + /** + * Creates a XPath2FilterContainer04 from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * @return the instance + * + * @throws XMLSecurityException + */ + public static XPath2FilterContainer04 newInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPath2FilterContainer04(element, BaseURI); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_SUBTRACT); - } + /** + * Returns true if the Filter attribute has value "intersect". + * + * @return true if the Filter attribute has value "intersect". + */ + public boolean isIntersect() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); + } - /** - * Creates a new XPath2FilterContainer04 with the filter type "union". - * - * @param doc - * @param xpath2filter - * @return the instance - */ - public static XPath2FilterContainer04 newInstanceUnion(Document doc, - String xpath2filter) { + /** + * Returns true if the Filter attribute has value "subtract". + * + * @return true if the Filter attribute has value "subtract". + */ + public boolean isSubtract() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); + } - return new XPath2FilterContainer04(doc, xpath2filter, - XPath2FilterContainer04 - ._ATT_FILTER_VALUE_UNION); - } + /** + * Returns true if the Filter attribute has value "union". + * + * @return true if the Filter attribute has value "union". + */ + public boolean isUnion() { + return this.constructionElement.getAttributeNS( + null, XPath2FilterContainer04._ATT_FILTER + ).equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); + } - /** - * Creates a XPath2FilterContainer04 from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * @return the instance - * - * @throws XMLSecurityException - */ - public static XPath2FilterContainer04 newInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPath2FilterContainer04(element, BaseURI); - } + /** + * Returns the XPath 2 Filter String + * + * @return the XPath 2 Filter String + */ + public String getXPathFilterStr() { + return this.getTextFromTextChild(); + } - /** - * Returns true if the Filter attribute has value "intersect". - * - * @return true if the Filter attribute has value "intersect". - */ - public boolean isIntersect() { + /** + * Returns the first Text node which contains information from the XPath 2 + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @return the first Text node which contains information from the XPath 2 Filter String + */ + public Node getXPathFilterTextNode() { + NodeList children = this.constructionElement.getChildNodes(); + int length = children.getLength(); - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_INTERSECT); - } + for (int i = 0; i < length; i++) { + if (children.item(i).getNodeType() == Node.TEXT_NODE) { + return children.item(i); + } + } - /** - * Returns true if the Filter attribute has value "subtract". - * - * @return true if the Filter attribute has value "subtract". - */ - public boolean isSubtract() { + return null; + } - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_SUBTRACT); - } + /** @inheritDoc */ + public final String getBaseLocalName() { + return XPath2FilterContainer04._TAG_XPATH2; + } - /** - * Returns true if the Filter attribute has value "union". - * - * @return true if the Filter attribute has value "union". - */ - public boolean isUnion() { - - return this._constructionElement - .getAttributeNS(null, XPath2FilterContainer04._ATT_FILTER) - .equals(XPath2FilterContainer04._ATT_FILTER_VALUE_UNION); - } - - /** - * Returns the XPath 2 Filter String - * - * @return the XPath 2 Filter String - */ - public String getXPathFilterStr() { - return this.getTextFromTextChild(); - } - - /** - * Returns the first Text node which contains information from the XPath 2 - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @return the first Text node which contains information from the XPath 2 Filter String - */ - public Node getXPathFilterTextNode() { - NodeList children = this._constructionElement.getChildNodes(); - int length = children.getLength(); - - for (int i = 0; i < length; i++) { - if (children.item(i).getNodeType() == Node.TEXT_NODE) { - return children.item(i); - } - } - - return null; - } - - /** @inheritDoc */ - public final String getBaseLocalName() { - return XPath2FilterContainer04._TAG_XPATH2; - } - - /** @inheritDoc */ - public final String getBaseNamespace() { - return XPath2FilterContainer04.XPathFilter2NS; - } + /** @inheritDoc */ + public final String getBaseNamespace() { + return XPath2FilterContainer04.XPathFilter2NS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java index 717889d576f..74f2ff1f50d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathContainer.java @@ -2,26 +2,27 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - import com.sun.org.apache.xml.internal.security.transforms.TransformParam; import com.sun.org.apache.xml.internal.security.utils.Constants; import com.sun.org.apache.xml.internal.security.utils.SignatureElementProxy; @@ -29,7 +30,6 @@ import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.w3c.dom.Text; - /** * This Object serves both as namespace prefix resolver and as container for * the ds:XPath Element. It implements the {@link org.w3c.dom.Element} interface @@ -39,45 +39,44 @@ import org.w3c.dom.Text; */ public class XPathContainer extends SignatureElementProxy implements TransformParam { - /** - * Constructor XPathContainer - * - * @param doc - */ - public XPathContainer(Document doc) { - super(doc); - } + /** + * Constructor XPathContainer + * + * @param doc + */ + public XPathContainer(Document doc) { + super(doc); + } - /** - * Sets the TEXT value of the ds:XPath Element. - * - * @param xpath - */ - public void setXPath(String xpath) { + /** + * Sets the TEXT value of the ds:XPath Element. + * + * @param xpath + */ + public void setXPath(String xpath) { + if (this.constructionElement.getChildNodes() != null) { + NodeList nl = this.constructionElement.getChildNodes(); - if (this._constructionElement.getChildNodes() != null) { - NodeList nl = this._constructionElement.getChildNodes(); + for (int i = 0; i < nl.getLength(); i++) { + this.constructionElement.removeChild(nl.item(i)); + } + } - for (int i = 0; i < nl.getLength(); i++) { - this._constructionElement.removeChild(nl.item(i)); - } - } + Text xpathText = this.doc.createTextNode(xpath); + this.constructionElement.appendChild(xpathText); + } - Text xpathText = this._doc.createTextNode(xpath); - this._constructionElement.appendChild(xpathText); - } + /** + * Returns the TEXT value of the ds:XPath Element. + * + * @return the TEXT value of the ds:XPath Element. + */ + public String getXPath() { + return this.getTextFromTextChild(); + } - /** - * Returns the TEXT value of the ds:XPath Element. - * - * @return the TEXT value of the ds:XPath Element. - */ - public String getXPath() { - return this.getTextFromTextChild(); - } - - /** @inheritDoc */ - public String getBaseLocalName() { - return Constants._TAG_XPATH; - } + /** @inheritDoc */ + public String getBaseLocalName() { + return Constants._TAG_XPATH; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java index 86199d7ab63..0bb4f7e5f09 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/transforms/params/XPathFilterCHGPContainer.java @@ -2,320 +2,315 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.transforms.params; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import com.sun.org.apache.xml.internal.security.transforms.TransformParam; -import com.sun.org.apache.xml.internal.security.transforms.Transforms; import com.sun.org.apache.xml.internal.security.utils.ElementProxy; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * Implements the parameters for a custom Transform which has a better performance - * thatn the xfilter2. + * than the xfilter2. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ -public class XPathFilterCHGPContainer extends ElementProxy - implements TransformParam { +public class XPathFilterCHGPContainer extends ElementProxy implements TransformParam { - /** Field _ATT_FILTER_VALUE_INTERSECT */ - private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; + public static final String TRANSFORM_XPATHFILTERCHGP = + "http://www.nue.et-inf.uni-siegen.de/~geuer-pollmann/#xpathFilter"; - /** Field _ATT_FILTER_VALUE_SUBTRACT */ - private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; + /** Field _ATT_FILTER_VALUE_INTERSECT */ + private static final String _TAG_INCLUDE_BUT_SEARCH = "IncludeButSearch"; - /** Field _ATT_FILTER_VALUE_UNION */ - private static final String _TAG_EXCLUDE = "Exclude"; + /** Field _ATT_FILTER_VALUE_SUBTRACT */ + private static final String _TAG_EXCLUDE_BUT_SEARCH = "ExcludeButSearch"; - /** Field _TAG_XPATHCHGP */ - public static final String _TAG_XPATHCHGP = "XPathAlternative"; + /** Field _ATT_FILTER_VALUE_UNION */ + private static final String _TAG_EXCLUDE = "Exclude"; - /** Field _ATT_INCLUDESLASH */ - public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; + /** Field _TAG_XPATHCHGP */ + public static final String _TAG_XPATHCHGP = "XPathAlternative"; - /** Field IncludeSlash */ - public static final boolean IncludeSlash = true; + /** Field _ATT_INCLUDESLASH */ + public static final String _ATT_INCLUDESLASH = "IncludeSlashPolicy"; - /** Field ExcludeSlash */ - public static final boolean ExcludeSlash = false; + /** Field IncludeSlash */ + public static final boolean IncludeSlash = true; - /** - * Constructor XPathFilterCHGPContainer - * - */ - private XPathFilterCHGPContainer() { + /** Field ExcludeSlash */ + public static final boolean ExcludeSlash = false; - // no instantiation - } + /** + * Constructor XPathFilterCHGPContainer + * + */ + private XPathFilterCHGPContainer() { + // no instantiation + } - /** - * Constructor XPathFilterCHGPContainer - * - * @param doc - * @param includeSlashPolicy - * @param includeButSearch - * @param excludeButSearch - * @param exclude - */ - private XPathFilterCHGPContainer(Document doc, boolean includeSlashPolicy, - String includeButSearch, - String excludeButSearch, String exclude) { + /** + * Constructor XPathFilterCHGPContainer + * + * @param doc + * @param includeSlashPolicy + * @param includeButSearch + * @param excludeButSearch + * @param exclude + */ + private XPathFilterCHGPContainer( + Document doc, boolean includeSlashPolicy, String includeButSearch, + String excludeButSearch, String exclude + ) { + super(doc); - super(doc); + if (includeSlashPolicy) { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true" + ); + } else { + this.constructionElement.setAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false" + ); + } - if (includeSlashPolicy) { - this._constructionElement - .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "true"); - } else { - this._constructionElement - .setAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH, "false"); - } + if ((includeButSearch != null) && (includeButSearch.trim().length() > 0)) { + Element includeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH + ); - if ((includeButSearch != null) - && (includeButSearch.trim().length() > 0)) { - Element includeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_INCLUDE_BUT_SEARCH); + includeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(includeButSearch)) + ); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(includeButSearchElem); + } - includeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(includeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(includeButSearchElem); - } + if ((excludeButSearch != null) && (excludeButSearch.trim().length() > 0)) { + Element excludeButSearchElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH + ); - if ((excludeButSearch != null) - && (excludeButSearch.trim().length() > 0)) { - Element excludeButSearchElem = - ElementProxy.createElementForFamily(doc, this.getBaseNamespace(), - XPathFilterCHGPContainer - ._TAG_EXCLUDE_BUT_SEARCH); + excludeButSearchElem.appendChild( + this.doc.createTextNode(indentXPathText(excludeButSearch))); - excludeButSearchElem - .appendChild(this._doc - .createTextNode(indentXPathText(excludeButSearch))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeButSearchElem); - } + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeButSearchElem); + } - if ((exclude != null) && (exclude.trim().length() > 0)) { - Element excludeElem = ElementProxy.createElementForFamily(doc, - this.getBaseNamespace(), - XPathFilterCHGPContainer._TAG_EXCLUDE); + if ((exclude != null) && (exclude.trim().length() > 0)) { + Element excludeElem = + ElementProxy.createElementForFamily( + doc, this.getBaseNamespace(), XPathFilterCHGPContainer._TAG_EXCLUDE); - excludeElem - .appendChild(this._doc.createTextNode(indentXPathText(exclude))); - XMLUtils.addReturnToElement(this._constructionElement); - this._constructionElement.appendChild(excludeElem); - } + excludeElem.appendChild(this.doc.createTextNode(indentXPathText(exclude))); + XMLUtils.addReturnToElement(this.constructionElement); + this.constructionElement.appendChild(excludeElem); + } - XMLUtils.addReturnToElement(this._constructionElement); - } + XMLUtils.addReturnToElement(this.constructionElement); + } - /** - * Method indentXPathText - * - * @param xp - * @return the string with enters - */ - static String indentXPathText(String xp) { + /** + * Method indentXPathText + * + * @param xp + * @return the string with enters + */ + static String indentXPathText(String xp) { + if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { + return "\n" + xp + "\n"; + } + return xp; + } - if ((xp.length() > 2) && (!Character.isWhitespace(xp.charAt(0)))) { - return "\n" + xp + "\n"; - } - return xp; + /** + * Constructor XPathFilterCHGPContainer + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + private XPathFilterCHGPContainer(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - } + /** + * Creates a new XPathFilterCHGPContainer; needed for generation. + * + * @param doc + * @param includeSlashPolicy + * @param includeButSearch + * @param excludeButSearch + * @param exclude + * @return the created object + */ + public static XPathFilterCHGPContainer getInstance( + Document doc, boolean includeSlashPolicy, String includeButSearch, + String excludeButSearch, String exclude + ) { + return new XPathFilterCHGPContainer( + doc, includeSlashPolicy, includeButSearch, excludeButSearch, exclude); + } - /** - * Constructor XPathFilterCHGPContainer - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - private XPathFilterCHGPContainer(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification. + * + * @param element + * @param BaseURI + * + * @throws XMLSecurityException + * @return the created object. + */ + public static XPathFilterCHGPContainer getInstance( + Element element, String BaseURI + ) throws XMLSecurityException { + return new XPathFilterCHGPContainer(element, BaseURI); + } - /** - * Creates a new XPathFilterCHGPContainer; needed for generation. - * - * @param doc - * @param includeSlashPolicy - * @param includeButSearch - * @param excludeButSearch - * @param exclude - * @return the created object - */ - public static XPathFilterCHGPContainer getInstance(Document doc, - boolean includeSlashPolicy, String includeButSearch, - String excludeButSearch, String exclude) { + /** + * Method getXStr + * + * @param type + * @return The Xstr + */ + private String getXStr(String type) { + if (this.length(this.getBaseNamespace(), type) != 1) { + return ""; + } - return new XPathFilterCHGPContainer(doc, includeSlashPolicy, - includeButSearch, excludeButSearch, - exclude); - } + Element xElem = + XMLUtils.selectNode( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); - /** - * Creates a XPathFilterCHGPContainer from an existing Element; needed for verification. - * - * @param element - * @param BaseURI - * - * @throws XMLSecurityException - * @return the created object. - */ - public static XPathFilterCHGPContainer getInstance( - Element element, String BaseURI) throws XMLSecurityException { - return new XPathFilterCHGPContainer(element, BaseURI); - } + return XMLUtils.getFullTextChildrenFromElement(xElem); + } - /** - * Method getXStr - * - * @param type - * @return The Xstr - */ - private String getXStr(String type) { + /** + * Method getIncludeButSearch + * + * @return the string + */ + public String getIncludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } - if (this.length(this.getBaseNamespace(), type) != 1) { - return ""; - } + /** + * Method getExcludeButSearch + * + * @return the string + */ + public String getExcludeButSearch() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } - Element xElem = XMLUtils.selectNode(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); + /** + * Method getExclude + * + * @return the string + */ + public String getExclude() { + return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); + } - return XMLUtils.getFullTextChildrenFromElement(xElem); - } + /** + * Method getIncludeSlashPolicy + * + * @return the string + */ + public boolean getIncludeSlashPolicy() { + return this.constructionElement.getAttributeNS( + null, XPathFilterCHGPContainer._ATT_INCLUDESLASH).equals("true"); + } - /** - * Method getIncludeButSearch - * - * @return the string - */ - public String getIncludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } + /** + * Returns the first Text node which contains information from the XPath + * Filter String. We must use this stupid hook to enable the here() function + * to work. + * + * $todo$ I dunno whether this crashes: here()/ds:Signature[1] + * @param type + * @return the first Text node which contains information from the XPath 2 Filter String + */ + private Node getHereContextNode(String type) { - /** - * Method getExcludeButSearch - * - * @return the string - */ - public String getExcludeButSearch() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } + if (this.length(this.getBaseNamespace(), type) != 1) { + return null; + } - /** - * Method getExclude - * - * @return the string - */ - public String getExclude() { - return this.getXStr(XPathFilterCHGPContainer._TAG_EXCLUDE); - } + return XMLUtils.selectNodeText( + this.constructionElement.getFirstChild(), this.getBaseNamespace(), type, 0 + ); + } - /** - * Method getIncludeSlashPolicy - * - * @return the string - */ - public boolean getIncludeSlashPolicy() { + /** + * Method getHereContextNodeIncludeButSearch + * + * @return the string + */ + public Node getHereContextNodeIncludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); + } - return this._constructionElement - .getAttributeNS(null, XPathFilterCHGPContainer._ATT_INCLUDESLASH) - .equals("true"); - } + /** + * Method getHereContextNodeExcludeButSearch + * + * @return the string + */ + public Node getHereContextNodeExcludeButSearch() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); + } - /** - * Returns the first Text node which contains information from the XPath - * Filter String. We must use this stupid hook to enable the here() function - * to work. - * - * $todo$ I dunno whether this crashes: here()/ds:Signature[1] - * @param type - * @return the first Text node which contains information from the XPath 2 Filter String - */ - private Node getHereContextNode(String type) { + /** + * Method getHereContextNodeExclude + * + * @return the string + */ + public Node getHereContextNodeExclude() { + return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); + } - if (this.length(this.getBaseNamespace(), type) != 1) { - return null; - } + /** + * Method getBaseLocalName + * + * @inheritDoc + */ + public final String getBaseLocalName() { + return XPathFilterCHGPContainer._TAG_XPATHCHGP; + } - return XMLUtils.selectNodeText(this._constructionElement.getFirstChild(), this.getBaseNamespace(), - type,0); - } - - /** - * Method getHereContextNodeIncludeButSearch - * - * @return the string - */ - public Node getHereContextNodeIncludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_INCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExcludeButSearch - * - * @return the string - */ - public Node getHereContextNodeExcludeButSearch() { - return this - .getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE_BUT_SEARCH); - } - - /** - * Method getHereContextNodeExclude - * - * @return the string - */ - public Node getHereContextNodeExclude() { - return this.getHereContextNode(XPathFilterCHGPContainer._TAG_EXCLUDE); - } - - /** - * Method getBaseLocalName - * - * @inheritDoc - */ - public final String getBaseLocalName() { - return XPathFilterCHGPContainer._TAG_XPATHCHGP; - } - - /** - * Method getBaseNamespace - * - * @inheritDoc - */ - public final String getBaseNamespace() { - return Transforms.TRANSFORM_XPATHFILTERCHGP; - } + /** + * Method getBaseNamespace + * + * @inheritDoc + */ + public final String getBaseNamespace() { + return TRANSFORM_XPATHFILTERCHGP; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java index 9e9c7de8b0f..db1f49eaee4 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Base64.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -32,762 +34,765 @@ import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; - /** * Implementation of MIME's Base64 encoding and decoding conversions. * Optimized code. (raw version taken from oreilly.jonathan.util, - * and currently com.sun.org.apache.xerces.internal.ds.util.Base64) + * and currently org.apache.xerces.ds.util.Base64) * * @author Raul Benito(Of the xerces copy, and little adaptations). * @author Anli Shundi * @author Christian Geuer-Pollmann - * @see RFC 2045 + * @see RFC 2045 * @see com.sun.org.apache.xml.internal.security.transforms.implementations.TransformBase64Decode */ public class Base64 { - - /** Field BASE64DEFAULTLENGTH */ - public static final int BASE64DEFAULTLENGTH = 76; - - private Base64() { - // we don't allow instantiation - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - static final byte[] getBytes(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - if (((big.bitLength() % 8) != 0) - && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - - // some copying needed - int startSrc = 0; // no need to skip anything - int bigLen = bigBytes.length; //valid length of the string - - if ((big.bitLength() % 8) == 0) { // correct values - startSrc = 1; // skip sign bit - - bigLen--; // valid length of the string - } - - int startDst = bitlen / 8 - bigLen; //pad with leading nulls - byte[] resizedBytes = new byte[bitlen / 8]; - - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - - return resizedBytes; - - } - - /** - * Encode in Base64 the given {@link BigInteger}. - * - * @param big - * @return String with Base64 encoding - */ - public static final String encode(BigInteger big) { - return encode(getBytes(big, big.bitLength())); - } - - /** - * Returns a byte-array representation of a {@link BigInteger}. - * No sign-bit is outputed. - * - * N.B.: {@link BigInteger}'s toByteArray - * retunrs eventually longer arrays because of the leading sign-bit. - * - * @param big BigInteger to be converted - * @param bitlen int the desired length in bits of the representation - * @return a byte array with bitlen bits of big - */ - public static final byte[] encode(BigInteger big, int bitlen) { - - //round bitlen - bitlen = ((bitlen + 7) >> 3) << 3; - - if (bitlen < big.bitLength()) { - throw new IllegalArgumentException(I18n - .translate("utils.Base64.IllegalBitlength")); - } - - byte[] bigBytes = big.toByteArray(); - - if (((big.bitLength() % 8) != 0) - && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { - return bigBytes; - } - - // some copying needed - int startSrc = 0; // no need to skip anything - int bigLen = bigBytes.length; //valid length of the string - - if ((big.bitLength() % 8) == 0) { // correct values - startSrc = 1; // skip sign bit - - bigLen--; // valid length of the string - } - - int startDst = bitlen / 8 - bigLen; //pad with leading nulls - byte[] resizedBytes = new byte[bitlen / 8]; - - System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); - - return resizedBytes; - - } - - /** - * Method decodeBigIntegerFromElement - * - * @param element - * @return the biginter obtained from the node - * @throws Base64DecodingException - */ - public static final BigInteger decodeBigIntegerFromElement(Element element) throws Base64DecodingException - { - return new BigInteger(1, Base64.decode(element)); - } - - /** - * Method decodeBigIntegerFromText - * - * @param text - * @return the biginter obtained from the text node - * @throws Base64DecodingException - */ - public static final BigInteger decodeBigIntegerFromText(Text text) throws Base64DecodingException - { - return new BigInteger(1, Base64.decode(text.getData())); - } - - /** - * This method takes an (empty) Element and a BigInteger and adds the - * base64 encoded BigInteger to the Element. - * - * @param element - * @param biginteger - */ - public static final void fillElementWithBigInteger(Element element, - BigInteger biginteger) { - - String encodedInt = encode(biginteger); - - if (encodedInt.length() > 76) { - encodedInt = "\n" + encodedInt + "\n"; - } - - Document doc = element.getOwnerDocument(); - Text text = doc.createTextNode(encodedInt); - - element.appendChild(text); - } - - /** - * Method decode - * - * Takes the Text children of the Element and interprets - * them as input for the Base64.decode() function. - * - * @param element - * @return the byte obtained of the decoding the element - * $todo$ not tested yet - * @throws Base64DecodingException - */ - public static final byte[] decode(Element element) throws Base64DecodingException { - - Node sibling = element.getFirstChild(); - StringBuffer sb = new StringBuffer(); - - while (sibling!=null) { - if (sibling.getNodeType() == Node.TEXT_NODE) { - Text t = (Text) sibling; - - sb.append(t.getData()); - } - sibling=sibling.getNextSibling(); - } - - return decode(sb.toString()); - } - - /** - * Method encodeToElement - * - * @param doc - * @param localName - * @param bytes - * @return an Element with the base64 encoded in the text. - * - */ - public static final Element encodeToElement(Document doc, String localName, - byte[] bytes) { - - Element el = XMLUtils.createElementInSignatureSpace(doc, localName); - Text text = doc.createTextNode(encode(bytes)); - - el.appendChild(text); - - return el; - } - - /** - * Method decode - * - * - * @param base64 - * @return the UTF bytes of the base64 - * @throws Base64DecodingException - * - */ - public final static byte[] decode(byte[] base64) throws Base64DecodingException { - return decodeInternal(base64, -1); - } - - - - /** - * Encode a byte array and fold lines at the standard 76th character unless - * ignore line breaks property is set. - * - * @param binaryData byte[] to be base64 encoded - * @return the String with encoded data - */ - public static final String encode(byte[] binaryData) { - return XMLUtils.ignoreLineBreaks() - ? encode(binaryData, Integer.MAX_VALUE) - : encode(binaryData, BASE64DEFAULTLENGTH); - } - - /** - * Base64 decode the lines from the reader and return an InputStream - * with the bytes. - * - * - * @param reader - * @return InputStream with the decoded bytes - * @exception IOException passes what the reader throws - * @throws IOException - * @throws Base64DecodingException - */ - public final static byte[] decode(BufferedReader reader) - throws IOException, Base64DecodingException { - - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - String line; - - while (null != (line = reader.readLine())) { - byte[] bytes = decode(line); - - baos.write(bytes); - } - - return baos.toByteArray(); - } - - static private final int BASELENGTH = 255; - static private final int LOOKUPLENGTH = 64; - static private final int TWENTYFOURBITGROUP = 24; - static private final int EIGHTBIT = 8; - static private final int SIXTEENBIT = 16; - static private final int FOURBYTE = 4; - static private final int SIGN = -128; - static private final char PAD = '='; - static final private byte [] base64Alphabet = new byte[BASELENGTH]; - static final private char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; - - static { - - for (int i = 0; i= 'A'; i--) { - base64Alphabet[i] = (byte) (i-'A'); - } - for (int i = 'z'; i>= 'a'; i--) { - base64Alphabet[i] = (byte) ( i-'a' + 26); - } - - for (int i = '9'; i >= '0'; i--) { - base64Alphabet[i] = (byte) (i-'0' + 52); - } - - base64Alphabet['+'] = 62; - base64Alphabet['/'] = 63; - - for (int i = 0; i<=25; i++) - lookUpBase64Alphabet[i] = (char)('A'+i); - - for (int i = 26, j = 0; i<=51; i++, j++) - lookUpBase64Alphabet[i] = (char)('a'+ j); - - for (int i = 52, j = 0; i<=61; i++, j++) - lookUpBase64Alphabet[i] = (char)('0' + j); - lookUpBase64Alphabet[62] = '+'; - lookUpBase64Alphabet[63] = '/'; - - } - - protected static final boolean isWhiteSpace(byte octect) { - return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); - } - - protected static final boolean isPad(byte octect) { - return (octect == PAD); - } - - - /** - * Encodes hex octects into Base64 - * - * @param binaryData Array containing binaryData - * @return Encoded Base64 array - */ - /** - * Encode a byte array in Base64 format and return an optionally - * wrapped line. - * - * @param binaryData byte[] data to be encoded - * @param length int length of wrapped lines; No wrapping if less than 4. - * @return a String with encoded data - */ - public static final String encode(byte[] binaryData,int length) { - - if (length<4) { - length=Integer.MAX_VALUE; + /** Field BASE64DEFAULTLENGTH */ + public static final int BASE64DEFAULTLENGTH = 76; + + private static final int BASELENGTH = 255; + private static final int LOOKUPLENGTH = 64; + private static final int TWENTYFOURBITGROUP = 24; + private static final int EIGHTBIT = 8; + private static final int SIXTEENBIT = 16; + private static final int FOURBYTE = 4; + private static final int SIGN = -128; + private static final char PAD = '='; + private static final byte [] base64Alphabet = new byte[BASELENGTH]; + private static final char [] lookUpBase64Alphabet = new char[LOOKUPLENGTH]; + + static { + for (int i = 0; i < BASELENGTH; i++) { + base64Alphabet[i] = -1; + } + for (int i = 'Z'; i >= 'A'; i--) { + base64Alphabet[i] = (byte) (i - 'A'); + } + for (int i = 'z'; i>= 'a'; i--) { + base64Alphabet[i] = (byte) (i - 'a' + 26); } - if (binaryData == null) - return null; + for (int i = '9'; i >= '0'; i--) { + base64Alphabet[i] = (byte) (i - '0' + 52); + } - int lengthDataBits = binaryData.length*EIGHTBIT; - if (lengthDataBits == 0) { - return ""; - } + base64Alphabet['+'] = 62; + base64Alphabet['/'] = 63; - int fewerThan24bits = lengthDataBits%TWENTYFOURBITGROUP; - int numberTriplets = lengthDataBits/TWENTYFOURBITGROUP; - int numberQuartet = fewerThan24bits != 0 ? numberTriplets+1 : numberTriplets; - int quartesPerLine = length/4; - int numberLines = (numberQuartet-1)/quartesPerLine; - char encodedData[] = null; + for (int i = 0; i <= 25; i++) { + lookUpBase64Alphabet[i] = (char)('A' + i); + } - encodedData = new char[numberQuartet*4+numberLines]; + for (int i = 26, j = 0; i <= 51; i++, j++) { + lookUpBase64Alphabet[i] = (char)('a' + j); + } - byte k=0, l=0, b1=0,b2=0,b3=0; + for (int i = 52, j = 0; i <= 61; i++, j++) { + lookUpBase64Alphabet[i] = (char)('0' + j); + } + lookUpBase64Alphabet[62] = '+'; + lookUpBase64Alphabet[63] = '/'; + } - int encodedIndex = 0; - int dataIndex = 0; - int i = 0; - - - for (int line = 0; line < numberLines; line++) { - for (int quartet = 0; quartet < 19; quartet++) { - b1 = binaryData[dataIndex++]; - b2 = binaryData[dataIndex++]; - b3 = binaryData[dataIndex++]; - - - l = (byte)(b2 & 0x0f); - k = (byte)(b1 & 0x03); - - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); - - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; - - i++; - } - encodedData[encodedIndex++] = 0xa; - } - - for (; i>2):(byte)((b1)>>2^0xc0); - - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - byte val3 = ((b3 & SIGN)==0)?(byte)(b3>>6):(byte)((b3)>>6^0xfc); - - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ (l <<2 ) | val3 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ b3 & 0x3f ]; - } - - // form integral number of 6-bit groups - if (fewerThan24bits == EIGHTBIT) { - b1 = binaryData[dataIndex]; - k = (byte) ( b1 &0x03 ); - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ k<<4 ]; - encodedData[encodedIndex++] = PAD; - encodedData[encodedIndex++] = PAD; - } else if (fewerThan24bits == SIXTEENBIT) { - b1 = binaryData[dataIndex]; - b2 = binaryData[dataIndex +1 ]; - l = ( byte ) ( b2 &0x0f ); - k = ( byte ) ( b1 &0x03 ); - - byte val1 = ((b1 & SIGN)==0)?(byte)(b1>>2):(byte)((b1)>>2^0xc0); - byte val2 = ((b2 & SIGN)==0)?(byte)(b2>>4):(byte)((b2)>>4^0xf0); - - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val1 ]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ val2 | ( k<<4 )]; - encodedData[encodedIndex++] = lookUpBase64Alphabet[ l<<2 ]; - encodedData[encodedIndex++] = PAD; - } - - //encodedData[encodedIndex] = 0xa; - - return new String(encodedData); - } + private Base64() { + // we don't allow instantiation + } /** - * Decodes Base64 data into octects + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + static final byte[] getBytes(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + if (((big.bitLength() % 8) != 0) + && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + + // some copying needed + int startSrc = 0; // no need to skip anything + int bigLen = bigBytes.length; //valid length of the string + + if ((big.bitLength() % 8) == 0) { // correct values + startSrc = 1; // skip sign bit + + bigLen--; // valid length of the string + } + + int startDst = bitlen / 8 - bigLen; //pad with leading nulls + byte[] resizedBytes = new byte[bitlen / 8]; + + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + + return resizedBytes; + } + + /** + * Encode in Base64 the given {@link BigInteger}. + * + * @param big + * @return String with Base64 encoding + */ + public static final String encode(BigInteger big) { + return encode(getBytes(big, big.bitLength())); + } + + /** + * Returns a byte-array representation of a {@link BigInteger}. + * No sign-bit is output. + * + * N.B.: {@link BigInteger}'s toByteArray + * returns eventually longer arrays because of the leading sign-bit. + * + * @param big BigInteger to be converted + * @param bitlen int the desired length in bits of the representation + * @return a byte array with bitlen bits of big + */ + public static final byte[] encode(BigInteger big, int bitlen) { + + //round bitlen + bitlen = ((bitlen + 7) >> 3) << 3; + + if (bitlen < big.bitLength()) { + throw new IllegalArgumentException(I18n.translate("utils.Base64.IllegalBitlength")); + } + + byte[] bigBytes = big.toByteArray(); + + if (((big.bitLength() % 8) != 0) + && (((big.bitLength() / 8) + 1) == (bitlen / 8))) { + return bigBytes; + } + + // some copying needed + int startSrc = 0; // no need to skip anything + int bigLen = bigBytes.length; //valid length of the string + + if ((big.bitLength() % 8) == 0) { // correct values + startSrc = 1; // skip sign bit + + bigLen--; // valid length of the string + } + + int startDst = bitlen / 8 - bigLen; //pad with leading nulls + byte[] resizedBytes = new byte[bitlen / 8]; + + System.arraycopy(bigBytes, startSrc, resizedBytes, startDst, bigLen); + + return resizedBytes; + } + + /** + * Method decodeBigIntegerFromElement + * + * @param element + * @return the biginteger obtained from the node + * @throws Base64DecodingException + */ + public static final BigInteger decodeBigIntegerFromElement(Element element) + throws Base64DecodingException { + return new BigInteger(1, Base64.decode(element)); + } + + /** + * Method decodeBigIntegerFromText + * + * @param text + * @return the biginter obtained from the text node + * @throws Base64DecodingException + */ + public static final BigInteger decodeBigIntegerFromText(Text text) + throws Base64DecodingException { + return new BigInteger(1, Base64.decode(text.getData())); + } + + /** + * This method takes an (empty) Element and a BigInteger and adds the + * base64 encoded BigInteger to the Element. + * + * @param element + * @param biginteger + */ + public static final void fillElementWithBigInteger(Element element, BigInteger biginteger) { + + String encodedInt = encode(biginteger); + + if (!XMLUtils.ignoreLineBreaks() && encodedInt.length() > BASE64DEFAULTLENGTH) { + encodedInt = "\n" + encodedInt + "\n"; + } + + Document doc = element.getOwnerDocument(); + Text text = doc.createTextNode(encodedInt); + + element.appendChild(text); + } + + /** + * Method decode + * + * Takes the Text children of the Element and interprets + * them as input for the Base64.decode() function. + * + * @param element + * @return the byte obtained of the decoding the element + * $todo$ not tested yet + * @throws Base64DecodingException + */ + public static final byte[] decode(Element element) throws Base64DecodingException { + + Node sibling = element.getFirstChild(); + StringBuffer sb = new StringBuffer(); + + while (sibling != null) { + if (sibling.getNodeType() == Node.TEXT_NODE) { + Text t = (Text) sibling; + + sb.append(t.getData()); + } + sibling = sibling.getNextSibling(); + } + + return decode(sb.toString()); + } + + /** + * Method encodeToElement + * + * @param doc + * @param localName + * @param bytes + * @return an Element with the base64 encoded in the text. + * + */ + public static final Element encodeToElement(Document doc, String localName, byte[] bytes) { + Element el = XMLUtils.createElementInSignatureSpace(doc, localName); + Text text = doc.createTextNode(encode(bytes)); + + el.appendChild(text); + + return el; + } + + /** + * Method decode + * + * @param base64 + * @return the UTF bytes of the base64 + * @throws Base64DecodingException + * + */ + public static final byte[] decode(byte[] base64) throws Base64DecodingException { + return decodeInternal(base64, -1); + } + + /** + * Encode a byte array and fold lines at the standard 76th character unless + * ignore line breaks property is set. + * + * @param binaryData byte[] to be base64 encoded + * @return the String with encoded data + */ + public static final String encode(byte[] binaryData) { + return XMLUtils.ignoreLineBreaks() + ? encode(binaryData, Integer.MAX_VALUE) + : encode(binaryData, BASE64DEFAULTLENGTH); + } + + /** + * Base64 decode the lines from the reader and return an InputStream + * with the bytes. + * + * @param reader + * @return InputStream with the decoded bytes + * @exception IOException passes what the reader throws + * @throws IOException + * @throws Base64DecodingException + */ + public static final byte[] decode(BufferedReader reader) + throws IOException, Base64DecodingException { + + byte[] retBytes = null; + UnsyncByteArrayOutputStream baos = null; + try { + baos = new UnsyncByteArrayOutputStream(); + String line; + + while (null != (line = reader.readLine())) { + byte[] bytes = decode(line); + baos.write(bytes); + } + retBytes = baos.toByteArray(); + } finally { + baos.close(); + } + + return retBytes; + } + + protected static final boolean isWhiteSpace(byte octect) { + return (octect == 0x20 || octect == 0xd || octect == 0xa || octect == 0x9); + } + + protected static final boolean isPad(byte octect) { + return (octect == PAD); + } + + /** + * Encodes hex octets into Base64 + * + * @param binaryData Array containing binaryData + * @return Encoded Base64 array + */ + /** + * Encode a byte array in Base64 format and return an optionally + * wrapped line. + * + * @param binaryData byte[] data to be encoded + * @param length int length of wrapped lines; No wrapping if less than 4. + * @return a String with encoded data + */ + public static final String encode(byte[] binaryData,int length) { + if (length < 4) { + length = Integer.MAX_VALUE; + } + + if (binaryData == null) { + return null; + } + + int lengthDataBits = binaryData.length * EIGHTBIT; + if (lengthDataBits == 0) { + return ""; + } + + int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP; + int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP; + int numberQuartet = fewerThan24bits != 0 ? numberTriplets + 1 : numberTriplets; + int quartesPerLine = length / 4; + int numberLines = (numberQuartet - 1) / quartesPerLine; + char encodedData[] = null; + + encodedData = new char[numberQuartet * 4 + numberLines]; + + byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0; + int encodedIndex = 0; + int dataIndex = 0; + int i = 0; + + for (int line = 0; line < numberLines; line++) { + for (int quartet = 0; quartet < 19; quartet++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte)(b2 & 0x0f); + k = (byte)(b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2): (byte)((b1) >> 2 ^ 0xc0); + + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); + + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + + i++; + } + encodedData[encodedIndex++] = 0xa; + } + + for (; i < numberTriplets; i++) { + b1 = binaryData[dataIndex++]; + b2 = binaryData[dataIndex++]; + b3 = binaryData[dataIndex++]; + + l = (byte)(b2 & 0x0f); + k = (byte)(b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); + + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + byte val3 = ((b3 & SIGN) == 0) ? (byte)(b3 >> 6) : (byte)((b3) >> 6 ^ 0xfc); + + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[(l << 2) | val3]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[b3 & 0x3f]; + } + + // form integral number of 6-bit groups + if (fewerThan24bits == EIGHTBIT) { + b1 = binaryData[dataIndex]; + k = (byte) (b1 &0x03); + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2):(byte)((b1) >> 2 ^ 0xc0); + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[k << 4]; + encodedData[encodedIndex++] = PAD; + encodedData[encodedIndex++] = PAD; + } else if (fewerThan24bits == SIXTEENBIT) { + b1 = binaryData[dataIndex]; + b2 = binaryData[dataIndex +1 ]; + l = ( byte ) (b2 & 0x0f); + k = ( byte ) (b1 & 0x03); + + byte val1 = ((b1 & SIGN) == 0) ? (byte)(b1 >> 2) : (byte)((b1) >> 2 ^ 0xc0); + byte val2 = ((b2 & SIGN) == 0) ? (byte)(b2 >> 4) : (byte)((b2) >> 4 ^ 0xf0); + + encodedData[encodedIndex++] = lookUpBase64Alphabet[val1]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[val2 | (k << 4)]; + encodedData[encodedIndex++] = lookUpBase64Alphabet[l << 2]; + encodedData[encodedIndex++] = PAD; + } + + //encodedData[encodedIndex] = 0xa; + + return new String(encodedData); + } + + /** + * Decodes Base64 data into octets * * @param encoded String containing base64 encoded data * @return byte array containing the decoded data * @throws Base64DecodingException if there is a problem decoding the data */ - public final static byte[] decode(String encoded) throws Base64DecodingException { - - if (encoded == null) - return null; - byte []bytes=new byte[encoded.length()]; - int len=getBytesInternal(encoded, bytes); - return decodeInternal(bytes, len); + public static final byte[] decode(String encoded) throws Base64DecodingException { + if (encoded == null) { + return null; } + byte[] bytes = new byte[encoded.length()]; + int len = getBytesInternal(encoded, bytes); + return decodeInternal(bytes, len); + } - protected static final int getBytesInternal(String s,byte[] result) { - int length=s.length(); + protected static final int getBytesInternal(String s, byte[] result) { + int length = s.length(); - int newSize=0; + int newSize = 0; for (int i = 0; i < length; i++) { - byte dataS=(byte)s.charAt(i); - if (!isWhiteSpace(dataS)) + byte dataS = (byte)s.charAt(i); + if (!isWhiteSpace(dataS)) { result[newSize++] = dataS; + } } return newSize; - } - protected final static byte[] decodeInternal(byte[] base64Data, int len) throws Base64DecodingException { - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four - } + protected static final byte[] decodeInternal(byte[] base64Data, int len) + throws Base64DecodingException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); + } - int numberQuadruple = (len/FOURBYTE ); + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } - if (numberQuadruple == 0) - return new byte[0]; + int numberQuadruple = (len / FOURBYTE); - byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; + if (numberQuadruple == 0) { + return new byte[0]; + } + byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; - int i = 0; - int encodedIndex = 0; - int dataIndex = 0; + int i = 0; + int encodedIndex = 0; + int dataIndex = 0; - //decodedData = new byte[ (numberQuadruple)*3]; - dataIndex=(numberQuadruple-1)*4; - encodedIndex=(numberQuadruple-1)*3; - //first last bits. - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - if ((b1==-1) || (b2==-1)) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null + //decodedData = new byte[ (numberQuadruple)*3]; + dataIndex = (numberQuadruple - 1) * 4; + encodedIndex = (numberQuadruple - 1) * 3; + //first last bits. + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + if ((b1==-1) || (b2==-1)) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); } - byte d3,d4; - b3 = base64Alphabet[d3=base64Data[dataIndex++]]; - b4 = base64Alphabet[d4=base64Data[dataIndex++]]; - if ((b3==-1 ) || (b4==-1) ) { - //Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - decodedData = new byte[ encodedIndex + 1 ]; - decodedData[encodedIndex] = (byte)( b1 <<2 | b2>>4 ) ; - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - decodedData = new byte[ encodedIndex + 2 ]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ); - decodedData[encodedIndex] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); + byte d3, d4; + b3 = base64Alphabet[d3 = base64Data[dataIndex++]]; + b4 = base64Alphabet[d4 = base64Data[dataIndex++]]; + if ((b3 == -1) || (b4 == -1) ) { + //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + decodedData = new byte[encodedIndex + 1]; + decodedData[encodedIndex] = (byte)(b1 << 2 | b2 >> 4) ; + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + if ((b3 & 0x3) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + decodedData = new byte[encodedIndex + 2]; + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4); + decodedData[encodedIndex] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); } } else { //No PAD e.g 3cQl decodedData = new byte[encodedIndex+3]; - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4); } - encodedIndex=0; - dataIndex=0; - //the begin - for (i=numberQuadruple-1; i>0; i--) { - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - b3 = base64Alphabet[base64Data[dataIndex++]]; - b4 = base64Alphabet[base64Data[dataIndex++]]; + encodedIndex = 0; + dataIndex = 0; + //the begin + for (i = numberQuadruple - 1; i > 0; i--) { + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + b3 = base64Alphabet[base64Data[dataIndex++]]; + b4 = base64Alphabet[base64Data[dataIndex++]]; - if ( (b1==-1) || - (b2==-1) || - (b3==-1) || - (b4==-1) ) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } + if ((b1 == -1) || + (b2 == -1) || + (b3 == -1) || + (b4 == -1)) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - decodedData[encodedIndex++] = (byte)( b1 <<2 | b2>>4 ) ; - decodedData[encodedIndex++] = (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) ); - decodedData[encodedIndex++] = (byte)( b3<<6 | b4 ); - } - return decodedData; - } - /** - * Decodes Base64 data into outputstream - * - * @param base64Data String containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(String base64Data, - OutputStream os) throws Base64DecodingException, IOException { - byte[] bytes=new byte[base64Data.length()]; - int len=getBytesInternal(base64Data, bytes); - decode(bytes,os,len); - } - /** - * Decodes Base64 data into outputstream - * - * @param base64Data Byte array containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(byte[] base64Data, - OutputStream os) throws Base64DecodingException, IOException { - decode(base64Data,os,-1); - } - protected final static void decode(byte[] base64Data, - OutputStream os,int len) throws Base64DecodingException, IOException { - - // remove white spaces - if (len==-1) - len = removeWhiteSpace(base64Data); - - if (len%FOURBYTE != 0) { - throw new Base64DecodingException("decoding.divisible.four"); - //should be divisible by four + decodedData[encodedIndex++] = (byte)(b1 << 2 | b2 >> 4) ; + decodedData[encodedIndex++] = (byte)(((b2 & 0xf) << 4) |((b3 >> 2) & 0xf)); + decodedData[encodedIndex++] = (byte)(b3 << 6 | b4 ); + } + return decodedData; } - int numberQuadruple = (len/FOURBYTE ); + /** + * Decodes Base64 data into outputstream + * + * @param base64Data String containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(String base64Data, OutputStream os) + throws Base64DecodingException, IOException { + byte[] bytes = new byte[base64Data.length()]; + int len = getBytesInternal(base64Data, bytes); + decode(bytes,os,len); + } - if (numberQuadruple == 0) - return; + /** + * Decodes Base64 data into outputstream + * + * @param base64Data Byte array containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(byte[] base64Data, OutputStream os) + throws Base64DecodingException, IOException { + decode(base64Data,os,-1); + } - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; + protected static final void decode(byte[] base64Data, OutputStream os, int len) + throws Base64DecodingException, IOException { + // remove white spaces + if (len == -1) { + len = removeWhiteSpace(base64Data); + } - int i = 0; + if (len % FOURBYTE != 0) { + throw new Base64DecodingException("decoding.divisible.four"); + //should be divisible by four + } - int dataIndex = 0; + int numberQuadruple = (len / FOURBYTE); - //the begin - for (i=numberQuadruple-1; i>0; i--) { + if (numberQuadruple == 0) { + return; + } + + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; + + int i = 0; + int dataIndex = 0; + + //the begin + for (i=numberQuadruple - 1; i > 0; i--) { + b1 = base64Alphabet[base64Data[dataIndex++]]; + b2 = base64Alphabet[base64Data[dataIndex++]]; + b3 = base64Alphabet[base64Data[dataIndex++]]; + b4 = base64Alphabet[base64Data[dataIndex++]]; + if ((b1 == -1) || + (b2 == -1) || + (b3 == -1) || + (b4 == -1) ) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } + + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4 ) | ((b3 >> 2) & 0xf))); + os.write( (byte)(b3 << 6 | b4)); + } b1 = base64Alphabet[base64Data[dataIndex++]]; b2 = base64Alphabet[base64Data[dataIndex++]]; - b3 = base64Alphabet[base64Data[dataIndex++]]; - b4 = base64Alphabet[base64Data[dataIndex++]]; - if ( (b1==-1) || - (b2==-1) || - (b3==-1) || - (b4==-1) ) - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write( (byte)( b3<<6 | b4 )); - } - b1 = base64Alphabet[base64Data[dataIndex++]]; - b2 = base64Alphabet[base64Data[dataIndex++]]; - - // first last bits. - if ((b1==-1) || - (b2==-1) ){ - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } - - byte d3,d4; - b3= base64Alphabet[d3 = base64Data[dataIndex++]]; - b4= base64Alphabet[d4 = base64Data[dataIndex++]]; - if ((b3==-1 ) || - (b4==-1) ) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 ) ); - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 )); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { - //No PAD e.g 3cQl - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } - return ; - } - - /** - * Decodes Base64 data into outputstream - * - * @param is containing Base64 data - * @param os the outputstream - * @throws IOException - * @throws Base64DecodingException - */ - public final static void decode(InputStream is, - OutputStream os) throws Base64DecodingException, IOException { - //byte decodedData[] = null; - byte b1=0,b2=0,b3=0, b4=0; - - int index=0; - byte []data=new byte[4]; - int read; - //the begin - while ((read=is.read())>0) { - byte readed=(byte)read; - if (isWhiteSpace(readed)) { - continue; - } - if (isPad(readed)) { - data[index++]=readed; - if (index==3) - data[index++]=(byte)is.read(); - break; + // first last bits. + if ((b1 == -1) || (b2 == -1) ) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); } - - if ((data[index++]=readed)==-1) { - throw new Base64DecodingException("decoding.general");//if found "no data" just return null - } - - if (index!=4) { - continue; + byte d3, d4; + b3 = base64Alphabet[d3 = base64Data[dataIndex++]]; + b4 = base64Alphabet[d4 = base64Data[dataIndex++]]; + if ((b3 == -1 ) || (b4 == -1) ) { //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + if ((b3 & 0x3 ) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + } else { + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); + } + } else { + //No PAD e.g 3cQl + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write( (byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); } - index=0; - b1 = base64Alphabet[data[0]]; - b2 = base64Alphabet[data[1]]; - b3 = base64Alphabet[data[2]]; - b4 = base64Alphabet[data[3]]; - - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write((byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write( (byte)( b3<<6 | b4 )); } + /** + * Decodes Base64 data into outputstream + * + * @param is containing Base64 data + * @param os the outputstream + * @throws IOException + * @throws Base64DecodingException + */ + public static final void decode(InputStream is, OutputStream os) + throws Base64DecodingException, IOException { + //byte decodedData[] = null; + byte b1 = 0, b2 = 0, b3 = 0, b4 = 0; - byte d1=data[0],d2=data[1],d3=data[2], d4=data[3]; - b1 = base64Alphabet[d1]; - b2 = base64Alphabet[d2]; - b3 = base64Alphabet[ d3 ]; - b4 = base64Alphabet[ d4 ]; - if ((b3==-1 ) || - (b4==-1) ) {//Check if they are PAD characters - if (isPad( d3 ) && isPad( d4)) { //Two PAD e.g. 3c[Pad][Pad] - if ((b2 & 0xf) != 0)//last 4 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 ) ); - } else if (!isPad( d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] - b3 = base64Alphabet[ d3 ]; - if ((b3 & 0x3 ) != 0)//last 2 bits should be zero - throw new Base64DecodingException("decoding.general"); - os.write( (byte)( b1 <<2 | b2>>4 )); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - } else { - throw new Base64DecodingException("decoding.general");//an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data - } - } else { - //No PAD e.g 3cQl + int index=0; + byte[] data = new byte[4]; + int read; + //the begin + while ((read = is.read()) > 0) { + byte readed = (byte)read; + if (isWhiteSpace(readed)) { + continue; + } + if (isPad(readed)) { + data[index++] = readed; + if (index == 3) { + data[index++] = (byte)is.read(); + } + break; + } - os.write((byte)( b1 <<2 | b2>>4 ) ); - os.write( (byte)(((b2 & 0xf)<<4 ) |( (b3>>2) & 0xf) )); - os.write((byte)( b3<<6 | b4 )); - } + if ((data[index++] = readed) == -1) { + //if found "no data" just return null + throw new Base64DecodingException("decoding.general"); + } - return ; - } - /** - * remove WhiteSpace from MIME containing encoded Base64 data. - * - * @param data the byte array of base64 data (with WS) - * @return the new length - */ - protected static final int removeWhiteSpace(byte[] data) { - if (data == null) - return 0; + if (index != 4) { + continue; + } + index = 0; + b1 = base64Alphabet[data[0]]; + b2 = base64Alphabet[data[1]]; + b3 = base64Alphabet[data[2]]; + b4 = base64Alphabet[data[3]]; - // count characters that's not whitespace - int newSize = 0; - int len = data.length; - for (int i = 0; i < len; i++) { - byte dataS=data[i]; - if (!isWhiteSpace(dataS)) - data[newSize++] = dataS; - } - return newSize; - } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); + } + + byte d1 = data[0], d2 = data[1], d3 = data[2], d4 = data[3]; + b1 = base64Alphabet[d1]; + b2 = base64Alphabet[d2]; + b3 = base64Alphabet[d3]; + b4 = base64Alphabet[d4]; + if ((b3 == -1) || (b4 == -1)) { //Check if they are PAD characters + if (isPad(d3) && isPad(d4)) { //Two PAD e.g. 3c[Pad][Pad] + if ((b2 & 0xf) != 0) { //last 4 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + } else if (!isPad(d3) && isPad(d4)) { //One PAD e.g. 3cQ[Pad] + b3 = base64Alphabet[d3]; + if ((b3 & 0x3) != 0) { //last 2 bits should be zero + throw new Base64DecodingException("decoding.general"); + } + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + } else { + //an error like "3c[Pad]r", "3cdX", "3cXd", "3cXX" where X is non data + throw new Base64DecodingException("decoding.general"); + } + } else { + //No PAD e.g 3cQl + os.write((byte)(b1 << 2 | b2 >> 4)); + os.write((byte)(((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf))); + os.write((byte)(b3 << 6 | b4)); + } + } + + /** + * remove WhiteSpace from MIME containing encoded Base64 data. + * + * @param data the byte array of base64 data (with WS) + * @return the new length + */ + protected static final int removeWhiteSpace(byte[] data) { + if (data == null) { + return 0; + } + + // count characters that's not whitespace + int newSize = 0; + int len = data.length; + for (int i = 0; i < len; i++) { + byte dataS = data[i]; + if (!isWhiteSpace(dataS)) { + data[newSize++] = dataS; + } + } + return newSize; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java deleted file mode 100644 index 0a7503a9331..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathAPIHolder.java +++ /dev/null @@ -1,65 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.sun.org.apache.xml.internal.security.utils; - -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import org.w3c.dom.Document; - -/** - * @author Raul Benito - */ -public class CachedXPathAPIHolder { - - static ThreadLocal local=new ThreadLocal(); - static ThreadLocal localDoc=new ThreadLocal(); - - /** - * Sets the doc for the xpath transformation. Resets the cache if needed - * @param doc - */ - public static void setDoc(Document doc) { - if (localDoc.get()!=doc) { - CachedXPathAPI cx=local.get(); - if (cx==null) { - cx=new CachedXPathAPI(); - local.set(cx); - localDoc.set(doc); - return; - } - //Different docs reset. - cx.getXPathContext().reset(); - localDoc.set(doc); - } - } - - /** - * @return the cachexpathapi for this thread - */ - public static CachedXPathAPI getCachedXPathAPI() { - CachedXPathAPI cx=local.get(); - if (cx==null) { - cx=new CachedXPathAPI(); - local.set(cx); - localDoc.set(null); - } - return cx; - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java deleted file mode 100644 index fe1ae841755..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/CachedXPathFuncHereAPI.java +++ /dev/null @@ -1,466 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.sun.org.apache.xml.internal.security.utils; - - - -import com.sun.org.apache.xml.internal.dtm.DTMManager; -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere; -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext; -import com.sun.org.apache.xml.internal.utils.PrefixResolver; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.CachedXPathAPI; -import com.sun.org.apache.xpath.internal.Expression; -import com.sun.org.apache.xpath.internal.XPath; -import com.sun.org.apache.xpath.internal.XPathContext; -import com.sun.org.apache.xpath.internal.compiler.FunctionTable; -import com.sun.org.apache.xpath.internal.objects.XObject; -import org.w3c.dom.*; -import org.w3c.dom.traversal.NodeIterator; - -import javax.xml.transform.ErrorListener; -import javax.xml.transform.SourceLocator; -import javax.xml.transform.TransformerException; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; - -/** - * - * @author $Author: mullan $ - */ -public class CachedXPathFuncHereAPI { - - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(CachedXPathFuncHereAPI.class.getName()); - /** - * XPathContext, and thus DTMManager and DTMs, persists through multiple - * calls to this object. - */ - FuncHereContext _funcHereContext = null; - - /** Field _dtmManager */ - DTMManager _dtmManager = null; - - XPathContext _context = null; - - String xpathStr=null; - - XPath xpath=null; - - static FunctionTable _funcTable = null; - - static { - fixupFunctionTable(); - } - - /** - * Method getFuncHereContext - * @return the context for this object - * - */ - public FuncHereContext getFuncHereContext() { - return this._funcHereContext; - } - - /** - * Constructor CachedXPathFuncHereAPI - * - */ - private CachedXPathFuncHereAPI() {} - - /** - * Constructor CachedXPathFuncHereAPI - * - * @param existingXPathContext - */ - public CachedXPathFuncHereAPI(XPathContext existingXPathContext) { - this._dtmManager = existingXPathContext.getDTMManager(); - this._context=existingXPathContext; - } - - /** - * Constructor CachedXPathFuncHereAPI - * - * @param previouslyUsed - */ - public CachedXPathFuncHereAPI(CachedXPathAPI previouslyUsed) { - this._dtmManager = previouslyUsed.getXPathContext().getDTMManager(); - this._context=previouslyUsed.getXPathContext(); - } - - /** - * Use an XPath string to select a single node. XPath namespace - * prefixes are resolved from the context node, which may not - * be what you want (see the next method). - * - * @param contextNode The node to start searching from. - * @param xpathnode A Node containing a valid XPath string. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public Node selectSingleNode(Node contextNode, Node xpathnode) - throws TransformerException { - return selectSingleNode(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a single node. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public Node selectSingleNode( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Have the XObject return its result as a NodeSetDTM. - NodeIterator nl = selectNodeIterator(contextNode, xpathnode, - namespaceNode); - - // Return the first node, or null - return nl.nextNode(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public NodeIterator selectNodeIterator(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeIterator(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, getStrFromNode(xpathnode), namespaceNode); - - // Have the XObject return its result as a NodeSetDTM. - return list.nodeset(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public NodeList selectNodeList(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeList(contextNode, xpathnode, getStrFromNode(xpathnode), contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public NodeList selectNodeList( - Node contextNode, Node xpathnode, String str, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, str, namespaceNode); - - // Return a NodeList. - return list.nodelist(); - } - - /** - * Evaluate XPath string to an XObject. Using this method, - * XPath namespace prefixes will be resolved from the namespaceNode. - * @param contextNode The node to start searching from. - * @param xpathnode - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - * @deprecated - */ - @Deprecated - public XObject eval(Node contextNode, Node xpathnode) - throws TransformerException { - return eval(contextNode, xpathnode, getStrFromNode(xpathnode),contextNode); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode) - throws TransformerException { - // Create the XPath object. - //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - if (this._funcHereContext == null) { - this._funcHereContext = new FuncHereContext(xpathnode, - this._dtmManager); - } - - // Create an object to resolve namespace prefixes. - // XPath namespaces are resolved from the input context node's document element - // if it is a root node, or else the current context node (for lack of a better - // resolution space, given the simplicity of this sample code). - PrefixResolverDefault prefixResolver = - new PrefixResolverDefault((namespaceNode.getNodeType() - == Node.DOCUMENT_NODE) - ? ((Document) namespaceNode) - .getDocumentElement() - : namespaceNode); - - // only check if string points to different object (for performance) - if (str!=xpathStr) { - if (str.indexOf("here()")>0) { - _context.reset(); - _dtmManager=_context.getDTMManager(); - } - xpath = createXPath(str, prefixResolver); - xpathStr=str; - } - - // Execute the XPath, and have it return the result - // return xpath.execute(xpathSupport, contextNode, prefixResolver); - int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode); - - return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param str - * @param prefixResolver Will be called if the parser encounters namespace - * prefixes, to resolve the prefixes to URLs. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public XObject eval( - Node contextNode, Node xpathnode, String str, PrefixResolver prefixResolver) - throws TransformerException { - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - // Create the XPath object. - //String str = CachedXPathFuncHereAPI.getStrFromNode(xpathnode); - // only check if string points to different object (for performance) - if (str!=xpathStr) { - if (str.indexOf("here()")>0) { - _context.reset(); - _dtmManager=_context.getDTMManager(); - } - try { - xpath = createXPath(str, prefixResolver); - } catch (TransformerException ex) { - //Try to see if it is a problem with the classloader. - Throwable th= ex.getCause(); - if (th instanceof ClassNotFoundException) { - if (th.getMessage().indexOf("FuncHere")>0) { - throw new RuntimeException(I18n.translate("endorsed.jdk1.4.0")/*,*/+ex); - } - } - throw ex; - } - xpathStr=str; - } - - // Execute the XPath, and have it return the result - if (this._funcHereContext == null) { - this._funcHereContext = new FuncHereContext(xpathnode, - this._dtmManager); - } - - int ctxtNode = this._funcHereContext.getDTMHandleFromNode(contextNode); - - return xpath.execute(this._funcHereContext, ctxtNode, prefixResolver); - } - - private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException { - XPath xpath = null; - Class[] classes = new Class[]{String.class, SourceLocator.class, PrefixResolver.class, int.class, - ErrorListener.class, FunctionTable.class}; - Object[] objects = new Object[]{str, null, prefixResolver, new Integer(XPath.SELECT), null, _funcTable}; - try { - Constructor constructor = XPath.class.getConstructor(classes); - xpath = constructor.newInstance(objects); - } catch (Throwable t) { - } - if (xpath == null) { - xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - } - return xpath; - } - - /** - * Method getStrFromNode - * - * @param xpathnode - * @return the string for the node. - */ - public static String getStrFromNode(Node xpathnode) { - - if (xpathnode.getNodeType() == Node.TEXT_NODE) { - - // we iterate over all siblings of the context node because eventually, - // the text is "polluted" with pi's or comments - StringBuffer sb = new StringBuffer(); - - for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); - currentSibling != null; - currentSibling = currentSibling.getNextSibling()) { - if (currentSibling.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) currentSibling).getData()); - } - } - - return sb.toString(); - } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { - return ((Attr) xpathnode).getNodeValue(); - } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return ((ProcessingInstruction) xpathnode).getNodeValue(); - } - - return null; - } - - private static void fixupFunctionTable() { - boolean installed = false; - log.log(java.util.logging.Level.INFO, "Registering Here function"); - /** - * Try to register our here() implementation as internal function. - */ - try { - Class []args = {String.class, Expression.class}; - Method installFunction = FunctionTable.class.getMethod("installFunction", args); - if ((installFunction.getModifiers() & Modifier.STATIC) != 0) { - Object []params = {"here", new FuncHere()}; - installFunction.invoke(null, params); - installed = true; - } - } catch (Throwable t) { - log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t); - } - if(!installed) { - try { - _funcTable = new FunctionTable(); - Class []args = {String.class, Class.class}; - Method installFunction = FunctionTable.class.getMethod("installFunction", args); - Object []params = {"here", FuncHere.class}; - installFunction.invoke(_funcTable, params); - installed = true; - } catch (Throwable t) { - log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", t); - } - } - if (log.isLoggable(java.util.logging.Level.FINE)) { - if (installed) { - log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName() - + " for XPath function 'here()' function in internal table"); - } else { - log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName() - + " for XPath function 'here()' function in internal table"); - } - } - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java new file mode 100644 index 00000000000..c9b910a4611 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ClassLoaderUtils.java @@ -0,0 +1,277 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package com.sun.org.apache.xml.internal.security.utils; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URL; +import java.util.ArrayList; +import java.util.Enumeration; +import java.util.List; + +/** + * This class is extremely useful for loading resources and classes in a fault + * tolerant manner that works across different applications servers. Do not + * touch this unless you're a grizzled classloading guru veteran who is going to + * verify any change on 6 different application servers. + */ +final class ClassLoaderUtils { + + /** {@link org.apache.commons.logging} logging facility */ + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ClassLoaderUtils.class.getName()); + + private ClassLoaderUtils() { + } + + /** + * Load a given resource.

    This method will try to load the resource + * using the following methods (in order): + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • callingClass.getClassLoader() + *
    + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static URL getResource(String resourceName, Class callingClass) { + URL url = Thread.currentThread().getContextClassLoader().getResource(resourceName); + if (url == null && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + url = + Thread.currentThread().getContextClassLoader().getResource( + resourceName.substring(1) + ); + } + + ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); + if (cluClassloader == null) { + cluClassloader = ClassLoader.getSystemClassLoader(); + } + if (url == null) { + url = cluClassloader.getResource(resourceName); + } + if (url == null && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + url = cluClassloader.getResource(resourceName.substring(1)); + } + + if (url == null) { + ClassLoader cl = callingClass.getClassLoader(); + + if (cl != null) { + url = cl.getResource(resourceName); + } + } + + if (url == null) { + url = callingClass.getResource(resourceName); + } + + if ((url == null) && (resourceName != null) && (resourceName.charAt(0) != '/')) { + return getResource('/' + resourceName, callingClass); + } + + return url; + } + + /** + * Load a given resources.

    This method will try to load the resources + * using the following methods (in order): + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • callingClass.getClassLoader() + *
    + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static List getResources(String resourceName, Class callingClass) { + List ret = new ArrayList(); + Enumeration urls = new Enumeration() { + public boolean hasMoreElements() { + return false; + } + public URL nextElement() { + return null; + } + + }; + try { + urls = Thread.currentThread().getContextClassLoader().getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + //ignore + } + if (!urls.hasMoreElements() && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + try { + urls = + Thread.currentThread().getContextClassLoader().getResources( + resourceName.substring(1) + ); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + + ClassLoader cluClassloader = ClassLoaderUtils.class.getClassLoader(); + if (cluClassloader == null) { + cluClassloader = ClassLoader.getSystemClassLoader(); + } + if (!urls.hasMoreElements()) { + try { + urls = cluClassloader.getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + if (!urls.hasMoreElements() && resourceName.startsWith("/")) { + //certain classloaders need it without the leading / + try { + urls = cluClassloader.getResources(resourceName.substring(1)); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + + if (!urls.hasMoreElements()) { + ClassLoader cl = callingClass.getClassLoader(); + + if (cl != null) { + try { + urls = cl.getResources(resourceName); + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + // ignore + } + } + } + + if (!urls.hasMoreElements()) { + URL url = callingClass.getResource(resourceName); + if (url != null) { + ret.add(url); + } + } + while (urls.hasMoreElements()) { + ret.add(urls.nextElement()); + } + + + if (ret.isEmpty() && (resourceName != null) && (resourceName.charAt(0) != '/')) { + return getResources('/' + resourceName, callingClass); + } + return ret; + } + + + /** + * This is a convenience method to load a resource as a stream.

    The + * algorithm used to find the resource is given in getResource() + * + * @param resourceName The name of the resource to load + * @param callingClass The Class object of the calling object + */ + static InputStream getResourceAsStream(String resourceName, Class callingClass) { + URL url = getResource(resourceName, callingClass); + + try { + return (url != null) ? url.openStream() : null; + } catch (IOException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + return null; + } + } + + /** + * Load a class with a given name.

    It will try to load the class in the + * following order: + *

      + *
    • From Thread.currentThread().getContextClassLoader() + *
    • Using the basic Class.forName() + *
    • From ClassLoaderUtil.class.getClassLoader() + *
    • From the callingClass.getClassLoader() + *
    + * + * @param className The name of the class to load + * @param callingClass The Class object of the calling object + * @throws ClassNotFoundException If the class cannot be found anywhere. + */ + static Class loadClass(String className, Class callingClass) + throws ClassNotFoundException { + try { + ClassLoader cl = Thread.currentThread().getContextClassLoader(); + + if (cl != null) { + return cl.loadClass(className); + } + } catch (ClassNotFoundException e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + //ignore + } + return loadClass2(className, callingClass); + } + + private static Class loadClass2(String className, Class callingClass) + throws ClassNotFoundException { + try { + return Class.forName(className); + } catch (ClassNotFoundException ex) { + try { + if (ClassLoaderUtils.class.getClassLoader() != null) { + return ClassLoaderUtils.class.getClassLoader().loadClass(className); + } + } catch (ClassNotFoundException exc) { + if (callingClass != null && callingClass.getClassLoader() != null) { + return callingClass.getClassLoader().loadClass(className); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + throw ex; + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java index 39ec71d8794..78907b09595 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Constants.java @@ -2,26 +2,26 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - /** * Provides all constants and some translation functions for i18n. * @@ -29,202 +29,245 @@ import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; * XML * Signature specification. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class Constants { - /** Field configurationFile */ - public static final String configurationFile = "data/websig.conf"; + /** Field configurationFile */ + public static final String configurationFile = "data/websig.conf"; - /** Field configurationFileNew */ - public static final String configurationFileNew = ".xmlsecurityconfig"; + /** Field configurationFileNew */ + public static final String configurationFileNew = ".xmlsecurityconfig"; - /** Field exceptionMessagesResourceBundleDir */ - public static final String exceptionMessagesResourceBundleDir = - "com/sun/org/apache/xml/internal/security/resource"; + /** Field exceptionMessagesResourceBundleDir */ + public static final String exceptionMessagesResourceBundleDir = + "com/sun/org/apache/xml/internal/security/resource"; - /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ - public static final String exceptionMessagesResourceBundleBase = - exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - //J- - /** - * The URL of the XML Signature specification - */ - public static final String SIGNATURESPECIFICATION_URL = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + /** Field exceptionMessagesResourceBundleBase is the location of the ResourceBundle */ + public static final String exceptionMessagesResourceBundleBase = + exceptionMessagesResourceBundleDir + "/" + "xmlsecurity"; - /** - * The namespace of the XML Signature specification - */ - public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; - /** The URL for more algorithm **/ - public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; - /** The URI for XML spec*/ - public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; - /** The URI for XMLNS spec*/ - public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; + /** + * The URL of the + * XML Signature specification + */ + public static final String SIGNATURESPECIFICATION_URL = + "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; - /** Tag of Attr Algorithm**/ - public static final String _ATT_ALGORITHM = "Algorithm"; - /** Tag of Attr URI**/ - public static final String _ATT_URI = "URI"; - /** Tag of Attr Type**/ - public static final String _ATT_TYPE = "Type"; - /** Tag of Attr Id**/ - public static final String _ATT_ID = "Id"; - /** Tag of Attr MimeType**/ - public static final String _ATT_MIMETYPE = "MimeType"; - /** Tag of Attr Encoding**/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr Target**/ - public static final String _ATT_TARGET = "Target"; + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpecNS = "http://www.w3.org/2000/09/xmldsig#"; - // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData) - // KeyValue (DSAKeyValue|RSAKeyValue) - // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?) - // RSAKeyValue (Modulus, Exponent) - // RetrievalMethod (Transforms?) - // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL) - // X509IssuerSerial (X509IssuerName, X509SerialNumber) - // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket)) - // SPKIData (SPKISexp) + /** + * The namespace of the + * XML Signature specification + */ + public static final String SignatureSpec11NS = "http://www.w3.org/2009/xmldsig11#"; - /** Tag of Element CanonicalizationMethod **/ - public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod"; - /** Tag of Element DigestMethod **/ - public static final String _TAG_DIGESTMETHOD = "DigestMethod"; - /** Tag of Element DigestValue **/ - public static final String _TAG_DIGESTVALUE = "DigestValue"; - /** Tag of Element Manifest **/ - public static final String _TAG_MANIFEST = "Manifest"; - /** Tag of Element Methods **/ - public static final String _TAG_METHODS = "Methods"; - /** Tag of Element Object **/ - public static final String _TAG_OBJECT = "Object"; - /** Tag of Element Reference **/ - public static final String _TAG_REFERENCE = "Reference"; - /** Tag of Element Signature **/ - public static final String _TAG_SIGNATURE = "Signature"; - /** Tag of Element SignatureMethod **/ - public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod"; - /** Tag of Element HMACOutputLength **/ - public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength"; - /** Tag of Element SignatureProperties **/ - public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties"; - /** Tag of Element SignatureProperty **/ - public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty"; - /** Tag of Element SignatureValue **/ - public static final String _TAG_SIGNATUREVALUE = "SignatureValue"; - /** Tag of Element SignedInfo **/ - public static final String _TAG_SIGNEDINFO = "SignedInfo"; - /** Tag of Element Transform **/ - public static final String _TAG_TRANSFORM = "Transform"; - /** Tag of Element Transforms **/ - public static final String _TAG_TRANSFORMS = "Transforms"; - /** Tag of Element XPath **/ - public static final String _TAG_XPATH = "XPath"; - /** Tag of Element KeyInfo **/ - public static final String _TAG_KEYINFO = "KeyInfo"; - /** Tag of Element KeyName **/ - public static final String _TAG_KEYNAME = "KeyName"; - /** Tag of Element KeyValue **/ - public static final String _TAG_KEYVALUE = "KeyValue"; - /** Tag of Element RetrievalMethod **/ - public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod"; - /** Tag of Element X509Data **/ - public static final String _TAG_X509DATA = "X509Data"; - /** Tag of Element PGPData **/ - public static final String _TAG_PGPDATA = "PGPData"; - /** Tag of Element SPKIData **/ - public static final String _TAG_SPKIDATA = "SPKIData"; - /** Tag of Element MgmtData **/ - public static final String _TAG_MGMTDATA = "MgmtData"; - /** Tag of Element RSAKeyValue **/ - public static final String _TAG_RSAKEYVALUE = "RSAKeyValue"; - /** Tag of Element Exponent **/ - public static final String _TAG_EXPONENT = "Exponent"; - /** Tag of Element Modulus **/ - public static final String _TAG_MODULUS = "Modulus"; - /** Tag of Element DSAKeyValue **/ - public static final String _TAG_DSAKEYVALUE = "DSAKeyValue"; - /** Tag of Element P **/ - public static final String _TAG_P = "P"; - /** Tag of Element Q **/ - public static final String _TAG_Q = "Q"; - /** Tag of Element G **/ - public static final String _TAG_G = "G"; - /** Tag of Element Y **/ - public static final String _TAG_Y = "Y"; - /** Tag of Element J **/ - public static final String _TAG_J = "J"; - /** Tag of Element Seed **/ - public static final String _TAG_SEED = "Seed"; - /** Tag of Element PgenCounter **/ - public static final String _TAG_PGENCOUNTER = "PgenCounter"; - /** Tag of Element rawX509Certificate **/ - public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate"; - /** Tag of Element X509IssuerSerial **/ - public static final String _TAG_X509ISSUERSERIAL = "X509IssuerSerial"; - /** Tag of Element X509SKI **/ - public static final String _TAG_X509SKI = "X509SKI"; - /** Tag of Element X509SubjectName **/ - public static final String _TAG_X509SUBJECTNAME = "X509SubjectName"; - /** Tag of Element X509Certificate **/ - public static final String _TAG_X509CERTIFICATE = "X509Certificate"; - /** Tag of Element X509CRL **/ - public static final String _TAG_X509CRL = "X509CRL"; - /** Tag of Element X509IssuerName **/ - public static final String _TAG_X509ISSUERNAME = "X509IssuerName"; - /** Tag of Element X509SerialNumber **/ - public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber"; - /** Tag of Element PGPKeyID **/ - public static final String _TAG_PGPKEYID = "PGPKeyID"; - /** Tag of Element PGPKeyPacket **/ - public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket"; - /** Tag of Element SPKISexp **/ - public static final String _TAG_SPKISEXP = "SPKISexp"; + /** The URL for more algorithms **/ + public static final String MoreAlgorithmsSpecNS = "http://www.w3.org/2001/04/xmldsig-more#"; - /** Digest - Required SHA1 */ - public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + /** The URI for XML spec*/ + public static final String XML_LANG_SPACE_SpecNS = "http://www.w3.org/XML/1998/namespace"; - /** - * @see - * draft-blake-wilson-xmldsig-ecdsa-02.txt - */ - public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; - //J+ + /** The URI for XMLNS spec*/ + public static final String NamespaceSpecNS = "http://www.w3.org/2000/xmlns/"; - private Constants() { - // we don't allow instantiation - } + /** Tag of Attr Algorithm**/ + public static final String _ATT_ALGORITHM = "Algorithm"; - /** - * Sets the namespace prefix which will be used to identify elements in the - * XML Signature Namespace. - * - *
    -    * Constants.setSignatureSpecNSprefix("dsig");
    -    * 
    - * - * @param newPrefix is the new namespace prefix. - * @throws XMLSecurityException - * @see com.sun.org.apache.xml.internal.security.utils.Constants#getSignatureSpecNSprefix - * $todo$ Add consistency checking for valid prefix - */ - public static void setSignatureSpecNSprefix(String newPrefix) throws XMLSecurityException { - ElementProxy.setDefaultPrefix(Constants.SignatureSpecNS, newPrefix); - } + /** Tag of Attr URI**/ + public static final String _ATT_URI = "URI"; + + /** Tag of Attr Type**/ + public static final String _ATT_TYPE = "Type"; + + /** Tag of Attr Id**/ + public static final String _ATT_ID = "Id"; + + /** Tag of Attr MimeType**/ + public static final String _ATT_MIMETYPE = "MimeType"; + + /** Tag of Attr Encoding**/ + public static final String _ATT_ENCODING = "Encoding"; + + /** Tag of Attr Target**/ + public static final String _ATT_TARGET = "Target"; + + // KeyInfo (KeyName|KeyValue|RetrievalMethod|X509Data|PGPData|SPKIData|MgmtData) + // KeyValue (DSAKeyValue|RSAKeyValue) + // DSAKeyValue (P, Q, G, Y, J?, (Seed, PgenCounter)?) + // RSAKeyValue (Modulus, Exponent) + // RetrievalMethod (Transforms?) + // X509Data ((X509IssuerSerial | X509SKI | X509SubjectName | X509Certificate)+ | X509CRL) + // X509IssuerSerial (X509IssuerName, X509SerialNumber) + // PGPData ((PGPKeyID, PGPKeyPacket?) | (PGPKeyPacket)) + // SPKIData (SPKISexp) + + /** Tag of Element CanonicalizationMethod **/ + public static final String _TAG_CANONICALIZATIONMETHOD = "CanonicalizationMethod"; + + /** Tag of Element DigestMethod **/ + public static final String _TAG_DIGESTMETHOD = "DigestMethod"; + + /** Tag of Element DigestValue **/ + public static final String _TAG_DIGESTVALUE = "DigestValue"; + + /** Tag of Element Manifest **/ + public static final String _TAG_MANIFEST = "Manifest"; + + /** Tag of Element Methods **/ + public static final String _TAG_METHODS = "Methods"; + + /** Tag of Element Object **/ + public static final String _TAG_OBJECT = "Object"; + + /** Tag of Element Reference **/ + public static final String _TAG_REFERENCE = "Reference"; + + /** Tag of Element Signature **/ + public static final String _TAG_SIGNATURE = "Signature"; + + /** Tag of Element SignatureMethod **/ + public static final String _TAG_SIGNATUREMETHOD = "SignatureMethod"; + + /** Tag of Element HMACOutputLength **/ + public static final String _TAG_HMACOUTPUTLENGTH = "HMACOutputLength"; + + /** Tag of Element SignatureProperties **/ + public static final String _TAG_SIGNATUREPROPERTIES = "SignatureProperties"; + + /** Tag of Element SignatureProperty **/ + public static final String _TAG_SIGNATUREPROPERTY = "SignatureProperty"; + + /** Tag of Element SignatureValue **/ + public static final String _TAG_SIGNATUREVALUE = "SignatureValue"; + + /** Tag of Element SignedInfo **/ + public static final String _TAG_SIGNEDINFO = "SignedInfo"; + + /** Tag of Element Transform **/ + public static final String _TAG_TRANSFORM = "Transform"; + + /** Tag of Element Transforms **/ + public static final String _TAG_TRANSFORMS = "Transforms"; + + /** Tag of Element XPath **/ + public static final String _TAG_XPATH = "XPath"; + + /** Tag of Element KeyInfo **/ + public static final String _TAG_KEYINFO = "KeyInfo"; + + /** Tag of Element KeyName **/ + public static final String _TAG_KEYNAME = "KeyName"; + + /** Tag of Element KeyValue **/ + public static final String _TAG_KEYVALUE = "KeyValue"; + + /** Tag of Element RetrievalMethod **/ + public static final String _TAG_RETRIEVALMETHOD = "RetrievalMethod"; + + /** Tag of Element X509Data **/ + public static final String _TAG_X509DATA = "X509Data"; + + /** Tag of Element PGPData **/ + public static final String _TAG_PGPDATA = "PGPData"; + + /** Tag of Element SPKIData **/ + public static final String _TAG_SPKIDATA = "SPKIData"; + + /** Tag of Element MgmtData **/ + public static final String _TAG_MGMTDATA = "MgmtData"; + + /** Tag of Element RSAKeyValue **/ + public static final String _TAG_RSAKEYVALUE = "RSAKeyValue"; + + /** Tag of Element Exponent **/ + public static final String _TAG_EXPONENT = "Exponent"; + + /** Tag of Element Modulus **/ + public static final String _TAG_MODULUS = "Modulus"; + + /** Tag of Element DSAKeyValue **/ + public static final String _TAG_DSAKEYVALUE = "DSAKeyValue"; + + /** Tag of Element P **/ + public static final String _TAG_P = "P"; + + /** Tag of Element Q **/ + public static final String _TAG_Q = "Q"; + + /** Tag of Element G **/ + public static final String _TAG_G = "G"; + + /** Tag of Element Y **/ + public static final String _TAG_Y = "Y"; + + /** Tag of Element J **/ + public static final String _TAG_J = "J"; + + /** Tag of Element Seed **/ + public static final String _TAG_SEED = "Seed"; + + /** Tag of Element PgenCounter **/ + public static final String _TAG_PGENCOUNTER = "PgenCounter"; + + /** Tag of Element rawX509Certificate **/ + public static final String _TAG_RAWX509CERTIFICATE = "rawX509Certificate"; + + /** Tag of Element X509IssuerSerial **/ + public static final String _TAG_X509ISSUERSERIAL= "X509IssuerSerial"; + + /** Tag of Element X509SKI **/ + public static final String _TAG_X509SKI = "X509SKI"; + + /** Tag of Element X509SubjectName **/ + public static final String _TAG_X509SUBJECTNAME = "X509SubjectName"; + + /** Tag of Element X509Certificate **/ + public static final String _TAG_X509CERTIFICATE = "X509Certificate"; + + /** Tag of Element X509CRL **/ + public static final String _TAG_X509CRL = "X509CRL"; + + /** Tag of Element X509IssuerName **/ + public static final String _TAG_X509ISSUERNAME = "X509IssuerName"; + + /** Tag of Element X509SerialNumber **/ + public static final String _TAG_X509SERIALNUMBER = "X509SerialNumber"; + + /** Tag of Element PGPKeyID **/ + public static final String _TAG_PGPKEYID = "PGPKeyID"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_PGPKEYPACKET = "PGPKeyPacket"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_DERENCODEDKEYVALUE = "DEREncodedKeyValue"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_KEYINFOREFERENCE = "KeyInfoReference"; + + /** Tag of Element PGPKeyPacket **/ + public static final String _TAG_X509DIGEST = "X509Digest"; + + /** Tag of Element SPKISexp **/ + public static final String _TAG_SPKISEXP = "SPKISexp"; + + /** Digest - Required SHA1 */ + public static final String ALGO_ID_DIGEST_SHA1 = SignatureSpecNS + "sha1"; + + /** + * @see + * draft-blake-wilson-xmldsig-ecdsa-02.txt + */ + public static final String ALGO_ID_SIGNATURE_ECDSA_CERTICOM = + "http://www.certicom.com/2000/11/xmlecdsig#ecdsa-sha1"; + + private Constants() { + // we don't allow instantiation + } - /** - * Returns the XML namespace prefix which is used for elements in the XML - * Signature namespace. - * - * It is defaulted to dsig, but can be changed using the - * {@link #setSignatureSpecNSprefix} function. - * - * @return the current used namespace prefix - * @see #setSignatureSpecNSprefix - */ - public static String getSignatureSpecNSprefix() { - return ElementProxy.getDefaultPrefix(Constants.SignatureSpecNS); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java new file mode 100644 index 00000000000..b4572b481ca --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DOMNamespaceContext.java @@ -0,0 +1,79 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +import javax.xml.namespace.NamespaceContext; + +import org.w3c.dom.Attr; +import org.w3c.dom.Element; +import org.w3c.dom.NamedNodeMap; +import org.w3c.dom.Node; + +/** + */ +public class DOMNamespaceContext implements NamespaceContext { + + private Map namespaceMap = new HashMap(); + + public DOMNamespaceContext(Node contextNode) { + addNamespaces(contextNode); + } + + public String getNamespaceURI(String arg0) { + return namespaceMap.get(arg0); + } + + public String getPrefix(String arg0) { + for (String key : namespaceMap.keySet()) { + String value = namespaceMap.get(key); + if (value.equals(arg0)) { + return key; + } + } + return null; + } + + public Iterator getPrefixes(String arg0) { + return namespaceMap.keySet().iterator(); + } + + private void addNamespaces(Node element) { + if (element.getParentNode() != null) { + addNamespaces(element.getParentNode()); + } + if (element instanceof Element) { + Element el = (Element)element; + NamedNodeMap map = el.getAttributes(); + for (int x = 0; x < map.getLength(); x++) { + Attr attr = (Attr)map.item(x); + if ("xmlns".equals(attr.getPrefix())) { + namespaceMap.put(attr.getLocalName(), attr.getValue()); + } + } + } + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java index bdf560dc78e..bd06b7d7c27 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/DigesterOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -29,16 +31,16 @@ import com.sun.org.apache.xml.internal.security.algorithms.MessageDigestAlgorith * */ public class DigesterOutputStream extends ByteArrayOutputStream { + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(DigesterOutputStream.class.getName()); + final MessageDigestAlgorithm mda; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (DigesterOutputStream.class.getName()); /** * @param mda */ public DigesterOutputStream(MessageDigestAlgorithm mda) { - this.mda=mda; + this.mda = mda; } /** @inheritDoc */ @@ -55,9 +57,9 @@ public class DigesterOutputStream extends ByteArrayOutputStream { public void write(byte[] arg0, int arg1, int arg2) { if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Pre-digested input:"); - StringBuffer sb = new StringBuffer(arg2); - for (int i=arg1; i<(arg1+arg2); i++) { - sb.append((char) arg0[i]); + StringBuilder sb = new StringBuilder(arg2); + for (int i = arg1; i < (arg1 + arg2); i++) { + sb.append((char)arg0[i]); } log.log(java.util.logging.Level.FINE, sb.toString()); } @@ -68,6 +70,6 @@ public class DigesterOutputStream extends ByteArrayOutputStream { * @return the digest value */ public byte[] getDigestValue() { - return mda.digest(); + return mda.digest(); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java index 9da45ce8cd1..618659c9f19 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementChecker.java @@ -1,17 +1,41 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package com.sun.org.apache.xml.internal.security.utils; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Element; import org.w3c.dom.Node; +/**@deprecated*/ +@Deprecated public interface ElementChecker { - /** - * Check that the elemnt is the one expect - * - * @throws XMLSecurityException - */ - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual) - throws XMLSecurityException; + /** + * Check that the element is the one expect + * + * @throws XMLSecurityException + */ + void guaranteeThatElementInCorrectSpace(ElementProxy expected, Element actual) + throws XMLSecurityException; - public boolean isNamespaceElement(Node el, String type, String ns); + boolean isNamespaceElement(Node el, String type, String ns); } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java index 5a94927d1c6..d71fd100384 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementCheckerImpl.java @@ -1,60 +1,90 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ package com.sun.org.apache.xml.internal.security.utils; import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Element; import org.w3c.dom.Node; +/**@deprecated*/ +@Deprecated public abstract class ElementCheckerImpl implements ElementChecker { - public boolean isNamespaceElement(Node el, String type, String ns) { - if ((el == null) || - ns!=el.getNamespaceURI() || !el.getLocalName().equals(type)){ - return false; - } - return true; - } - /** A checker for DOM that interns NS */ - public static class InternedNsChecker extends ElementCheckerImpl{ - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); - - String localnameIS = actual.getLocalName(); - String namespaceIS = actual.getNamespaceURI(); - if ((namespaceSHOULDBE!=namespaceIS) || - !localnameSHOULDBE.equals(localnameIS) ) { - Object exArgs[] = { namespaceIS +":"+ localnameIS, - namespaceSHOULDBE +":"+ localnameSHOULDBE}; - throw new XMLSecurityException("xml.WrongElement", exArgs); - } - } + public boolean isNamespaceElement(Node el, String type, String ns) { + if ((el == null) || + ns != el.getNamespaceURI() || !el.getLocalName().equals(type)){ + return false; } - /** A checker for DOM that interns NS */ - public static class FullChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { + return true; + } - String localnameSHOULDBE = expected.getBaseLocalName(); - String namespaceSHOULDBE = expected.getBaseNamespace(); + /** A checker for DOM that interns NS */ + public static class InternedNsChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { - String localnameIS = actual.getLocalName(); - String namespaceIS = actual.getNamespaceURI(); - if ((!namespaceSHOULDBE.equals(namespaceIS)) || - !localnameSHOULDBE.equals(localnameIS) ) { - Object exArgs[] = { namespaceIS +":"+ localnameIS, - namespaceSHOULDBE +":"+ localnameSHOULDBE}; - throw new XMLSecurityException("xml.WrongElement", exArgs); - } - } + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = expected.getBaseNamespace(); + + String localnameIS = actual.getLocalName(); + String namespaceIS = actual.getNamespaceURI(); + if ((expectedNamespace != namespaceIS) || + !expectedLocalname.equals(localnameIS)) { + Object exArgs[] = { namespaceIS + ":" + localnameIS, + expectedNamespace + ":" + expectedLocalname}; + throw new XMLSecurityException("xml.WrongElement", exArgs); + } } + } - /** An empty checker if schema checking is used */ - public static class EmptyChecker extends ElementCheckerImpl { - public void guaranteeThatElementInCorrectSpace(ElementProxy expected, - Element actual) throws XMLSecurityException { - } + /** A checker for DOM that interns NS */ + public static class FullChecker extends ElementCheckerImpl { + + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + String expectedLocalname = expected.getBaseLocalName(); + String expectedNamespace = expected.getBaseNamespace(); + + String localnameIS = actual.getLocalName(); + String namespaceIS = actual.getNamespaceURI(); + if ((!expectedNamespace.equals(namespaceIS)) || + !expectedLocalname.equals(localnameIS) ) { + Object exArgs[] = { namespaceIS + ":" + localnameIS, + expectedNamespace + ":" + expectedLocalname}; + throw new XMLSecurityException("xml.WrongElement", exArgs); + } } + } + + /** An empty checker if schema checking is used */ + public static class EmptyChecker extends ElementCheckerImpl { + public void guaranteeThatElementInCorrectSpace( + ElementProxy expected, Element actual + ) throws XMLSecurityException { + // empty + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java index 2d2fdeb61bb..ac7a53eba4f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/ElementProxy.java @@ -45,13 +45,13 @@ public abstract class ElementProxy { java.util.logging.Logger.getLogger(ElementProxy.class.getName()); /** Field constructionElement */ - protected Element _constructionElement = null; + protected Element constructionElement = null; /** Field baseURI */ - protected String _baseURI = null; + protected String baseURI = null; /** Field doc */ - protected Document _doc = null; + protected Document doc = null; /** Field prefixMappings */ private static Map prefixMappings = new ConcurrentHashMap(); @@ -73,9 +73,9 @@ public abstract class ElementProxy { throw new RuntimeException("Document is null"); } - this._doc = doc; - this._constructionElement = - createElementForFamilyLocal(this._doc, this.getBaseNamespace(), this.getBaseLocalName()); + this.doc = doc; + this.constructionElement = + createElementForFamilyLocal(this.doc, this.getBaseNamespace(), this.getBaseLocalName()); } /** @@ -94,9 +94,9 @@ public abstract class ElementProxy { log.log(java.util.logging.Level.FINE, "setElement(\"" + element.getTagName() + "\", \"" + BaseURI + "\")"); } - this._doc = element.getOwnerDocument(); - this._constructionElement = element; - this._baseURI = BaseURI; + this.doc = element.getOwnerDocument(); + this.constructionElement = element; + this.baseURI = BaseURI; this.guaranteeThatElementInCorrectSpace(); } @@ -184,9 +184,9 @@ public abstract class ElementProxy { log.log(java.util.logging.Level.FINE, "setElement(" + element.getTagName() + ", \"" + BaseURI + "\""); } - this._doc = element.getOwnerDocument(); - this._constructionElement = element; - this._baseURI = BaseURI; + this.doc = element.getOwnerDocument(); + this.constructionElement = element; + this.baseURI = BaseURI; } @@ -196,7 +196,7 @@ public abstract class ElementProxy { * @return the Element which was constructed by the Object. */ public final Element getElement() { - return this._constructionElement; + return this.constructionElement; } /** @@ -208,9 +208,9 @@ public abstract class ElementProxy { HelperNodeList nl = new HelperNodeList(); - nl.appendChild(this._doc.createTextNode("\n")); + nl.appendChild(this.doc.createTextNode("\n")); nl.appendChild(this.getElement()); - nl.appendChild(this._doc.createTextNode("\n")); + nl.appendChild(this.doc.createTextNode("\n")); return nl; } @@ -221,7 +221,7 @@ public abstract class ElementProxy { * @return the Document where this element is contained. */ public Document getDocument() { - return this._doc; + return this.doc; } /** @@ -230,7 +230,7 @@ public abstract class ElementProxy { * @return the base uri of the namespace of this element */ public String getBaseURI() { - return this._baseURI; + return this.baseURI; } /** @@ -243,8 +243,8 @@ public abstract class ElementProxy { String expectedLocalName = this.getBaseLocalName(); String expectedNamespaceUri = this.getBaseNamespace(); - String actualLocalName = this._constructionElement.getLocalName(); - String actualNamespaceUri = this._constructionElement.getNamespaceURI(); + String actualLocalName = this.constructionElement.getLocalName(); + String actualNamespaceUri = this.constructionElement.getNamespaceURI(); if(!expectedNamespaceUri.equals(actualNamespaceUri) && !expectedLocalName.equals(actualLocalName)) { @@ -262,11 +262,11 @@ public abstract class ElementProxy { */ public void addBigIntegerElement(BigInteger bi, String localname) { if (bi != null) { - Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname); + Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname); Base64.fillElementWithBigInteger(e, bi); - this._constructionElement.appendChild(e); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(e); + XMLUtils.addReturnToElement(this.constructionElement); } } @@ -278,11 +278,11 @@ public abstract class ElementProxy { */ public void addBase64Element(byte[] bytes, String localname) { if (bytes != null) { - Element e = Base64.encodeToElement(this._doc, localname, bytes); + Element e = Base64.encodeToElement(this.doc, localname, bytes); - this._constructionElement.appendChild(e); + this.constructionElement.appendChild(e); if (!XMLUtils.ignoreLineBreaks()) { - this._constructionElement.appendChild(this._doc.createTextNode("\n")); + this.constructionElement.appendChild(this.doc.createTextNode("\n")); } } } @@ -294,12 +294,12 @@ public abstract class ElementProxy { * @param localname */ public void addTextElement(String text, String localname) { - Element e = XMLUtils.createElementInSignatureSpace(this._doc, localname); - Text t = this._doc.createTextNode(text); + Element e = XMLUtils.createElementInSignatureSpace(this.doc, localname); + Text t = this.doc.createTextNode(text); e.appendChild(t); - this._constructionElement.appendChild(e); - XMLUtils.addReturnToElement(this._constructionElement); + this.constructionElement.appendChild(e); + XMLUtils.addReturnToElement(this.constructionElement); } /** @@ -310,9 +310,9 @@ public abstract class ElementProxy { public void addBase64Text(byte[] bytes) { if (bytes != null) { Text t = XMLUtils.ignoreLineBreaks() - ? this._doc.createTextNode(Base64.encode(bytes)) - : this._doc.createTextNode("\n" + Base64.encode(bytes) + "\n"); - this._constructionElement.appendChild(t); + ? this.doc.createTextNode(Base64.encode(bytes)) + : this.doc.createTextNode("\n" + Base64.encode(bytes) + "\n"); + this.constructionElement.appendChild(t); } } @@ -323,9 +323,9 @@ public abstract class ElementProxy { */ public void addText(String text) { if (text != null) { - Text t = this._doc.createTextNode(text); + Text t = this.doc.createTextNode(text); - this._constructionElement.appendChild(t); + this.constructionElement.appendChild(t); } } @@ -342,7 +342,7 @@ public abstract class ElementProxy { ) throws Base64DecodingException { return Base64.decodeBigIntegerFromText( XMLUtils.selectNodeText( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ) ); } @@ -360,7 +360,7 @@ public abstract class ElementProxy { throws XMLSecurityException { Element e = XMLUtils.selectNode( - this._constructionElement.getFirstChild(), namespace, localname, 0 + this.constructionElement.getFirstChild(), namespace, localname, 0 ); return Base64.decode(e); @@ -375,7 +375,7 @@ public abstract class ElementProxy { */ public String getTextFromChildElement(String localname, String namespace) { return XMLUtils.selectNode( - this._constructionElement.getFirstChild(), + this.constructionElement.getFirstChild(), namespace, localname, 0).getTextContent(); @@ -388,7 +388,7 @@ public abstract class ElementProxy { * @throws XMLSecurityException */ public byte[] getBytesFromTextChild() throws XMLSecurityException { - return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this._constructionElement)); + return Base64.decode(XMLUtils.getFullTextChildrenFromElement(this.constructionElement)); } /** @@ -398,7 +398,7 @@ public abstract class ElementProxy { * element */ public String getTextFromTextChild() { - return XMLUtils.getFullTextChildrenFromElement(this._constructionElement); + return XMLUtils.getFullTextChildrenFromElement(this.constructionElement); } /** @@ -410,7 +410,7 @@ public abstract class ElementProxy { */ public int length(String namespace, String localname) { int number = 0; - Node sibling = this._constructionElement.getFirstChild(); + Node sibling = this.constructionElement.getFirstChild(); while (sibling != null) { if (localname.equals(sibling.getLocalName()) && namespace.equals(sibling.getNamespaceURI())) { @@ -448,18 +448,18 @@ public abstract class ElementProxy { ns = "xmlns:" + prefix; } - Attr a = this._constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns); + Attr a = this.constructionElement.getAttributeNodeNS(Constants.NamespaceSpecNS, ns); if (a != null) { if (!a.getNodeValue().equals(uri)) { - Object exArgs[] = { ns, this._constructionElement.getAttributeNS(null, ns) }; + Object exArgs[] = { ns, this.constructionElement.getAttributeNS(null, ns) }; throw new XMLSecurityException("namespacePrefixAlreadyUsedByOtherURI", exArgs); } return; } - this._constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri); + this.constructionElement.setAttributeNS(Constants.NamespaceSpecNS, ns, uri); } /** @@ -515,16 +515,4 @@ public abstract class ElementProxy { return prefixMappings.get(namespace); } - protected void setLocalIdAttribute(String attrName, String value) { - - if (value != null) { - Attr attr = getDocument().createAttributeNS(null, attrName); - attr.setValue(value); - getElement().setAttributeNodeNS(attr); - getElement().setIdAttributeNode(attr, true); - } - else { - getElement().removeAttributeNS(null, attrName); - } - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java index e250bff2a16..175911e169f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionConstants.java @@ -2,179 +2,238 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - - -import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; - - -/** - * - * @author $Author: mullan $ - */ public class EncryptionConstants { - //J- - // Attributes that exist in XML Signature in the same way + // Attributes that exist in XML Signature in the same way /** Tag of Attr Algorithm **/ - public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; - /** Tag of Attr Id**/ - public static final String _ATT_ID = Constants._ATT_ID; - /** Tag of Attr Target **/ - public static final String _ATT_TARGET = Constants._ATT_TARGET; - /** Tag of Attr Type **/ - public static final String _ATT_TYPE = Constants._ATT_TYPE; - /** Tag of Attr URI **/ - public static final String _ATT_URI = Constants._ATT_URI; + public static final String _ATT_ALGORITHM = Constants._ATT_ALGORITHM; - // Attributes new in XML Encryption - /** Tag of Attr encoding **/ - public static final String _ATT_ENCODING = "Encoding"; - /** Tag of Attr recipient **/ - public static final String _ATT_RECIPIENT = "Recipient"; - /** Tag of Attr mimetype **/ - public static final String _ATT_MIMETYPE = "MimeType"; + /** Tag of Attr Id**/ + public static final String _ATT_ID = Constants._ATT_ID; - /** Tag of Element CarriedKeyName **/ - public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; - /** Tag of Element CipherData **/ - public static final String _TAG_CIPHERDATA = "CipherData"; - /** Tag of Element CipherReference **/ - public static final String _TAG_CIPHERREFERENCE = "CipherReference"; - /** Tag of Element CipherValue **/ - public static final String _TAG_CIPHERVALUE = "CipherValue"; - /** Tag of Element DataReference **/ - public static final String _TAG_DATAREFERENCE = "DataReference"; - /** Tag of Element EncryptedData **/ - public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; - /** Tag of Element EncryptedKey **/ - public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; - /** Tag of Element EncryptionMethod **/ - public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod"; - /** Tag of Element EncryptionProperties **/ - public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties"; - /** Tag of Element EncryptionProperty **/ - public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty"; - /** Tag of Element KeyReference **/ - public static final String _TAG_KEYREFERENCE = "KeyReference"; - /** Tag of Element KeySize **/ - public static final String _TAG_KEYSIZE = "KeySize"; - /** Tag of Element OAEPparams **/ - public static final String _TAG_OAEPPARAMS = "OAEPparams"; - /** Tag of Element ReferenceList **/ - public static final String _TAG_REFERENCELIST = "ReferenceList"; - /** Tag of Element Transforms **/ - public static final String _TAG_TRANSFORMS = "Transforms"; - /** Tag of Element AgreementMethod **/ - public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod"; - /** Tag of Element KA-Nonce **/ - public static final String _TAG_KA_NONCE = "KA-Nonce"; - /** Tag of Element OriginatorKeyInfo **/ - public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo"; - /** Tag of Element RecipientKeyInfo **/ - public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo"; + /** Tag of Attr Target **/ + public static final String _ATT_TARGET = Constants._ATT_TARGET; - /** Field ENCRYPTIONSPECIFICATION_URL */ - public static final String ENCRYPTIONSPECIFICATION_URL = "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; + /** Tag of Attr Type **/ + public static final String _ATT_TYPE = Constants._ATT_TYPE; - /** The namespace of the XML Encryption Syntax and Processing */ - public static final String EncryptionSpecNS = "http://www.w3.org/2001/04/xmlenc#"; + /** Tag of Attr URI **/ + public static final String _ATT_URI = Constants._ATT_URI; - /** URI for content*/ - public static final String TYPE_CONTENT = EncryptionSpecNS + "Content"; - /** URI for element*/ - public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element"; - /** URI for mediatype*/ - public static final String TYPE_MEDIATYPE = "http://www.isi.edu/in-notes/iana/assignments/media-types/"; // + "*/*"; + // Attributes new in XML Encryption + /** Tag of Attr encoding **/ + public static final String _ATT_ENCODING = "Encoding"; - /** Block Encryption - REQUIRED TRIPLEDES */ - public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "tripledes-cbc"; - /** Block Encryption - REQUIRED AES-128 */ - public static final String ALGO_ID_BLOCKCIPHER_AES128 = EncryptionConstants.EncryptionSpecNS + "aes128-cbc"; - /** Block Encryption - REQUIRED AES-256 */ - public static final String ALGO_ID_BLOCKCIPHER_AES256 = EncryptionConstants.EncryptionSpecNS + "aes256-cbc"; - /** Block Encryption - OPTIONAL AES-192 */ - public static final String ALGO_ID_BLOCKCIPHER_AES192 = EncryptionConstants.EncryptionSpecNS + "aes192-cbc"; + /** Tag of Attr recipient **/ + public static final String _ATT_RECIPIENT = "Recipient"; - /** Key Transport - REQUIRED RSA-v1.5*/ - public static final String ALGO_ID_KEYTRANSPORT_RSA15 = EncryptionConstants.EncryptionSpecNS + "rsa-1_5"; - /** Key Transport - REQUIRED RSA-OAEP */ - public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p"; + /** Tag of Attr mimetype **/ + public static final String _ATT_MIMETYPE = "MimeType"; - /** Key Agreement - OPTIONAL Diffie-Hellman */ - public static final String ALGO_ID_KEYAGREEMENT_DH = EncryptionConstants.EncryptionSpecNS + "dh"; + /** Tag of Element CarriedKeyName **/ + public static final String _TAG_CARRIEDKEYNAME = "CarriedKeyName"; - /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */ - public static final String ALGO_ID_KEYWRAP_TRIPLEDES = EncryptionConstants.EncryptionSpecNS + "kw-tripledes"; - /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES128 = EncryptionConstants.EncryptionSpecNS + "kw-aes128"; - /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES256 = EncryptionConstants.EncryptionSpecNS + "kw-aes256"; - /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */ - public static final String ALGO_ID_KEYWRAP_AES192 = EncryptionConstants.EncryptionSpecNS + "kw-aes192"; + /** Tag of Element CipherData **/ + public static final String _TAG_CIPHERDATA = "CipherData"; - /* - // Message Digest - REQUIRED SHA1 - public static final String ALGO_ID_DIGEST_SHA160 = Constants.ALGO_ID_DIGEST_SHA1; - // Message Digest - RECOMMENDED SHA256 - public static final String ALGO_ID_DIGEST_SHA256 = EncryptionConstants.EncryptionSpecNS + "sha256"; - // Message Digest - OPTIONAL SHA512 - public static final String ALGO_ID_DIGEST_SHA512 = EncryptionConstants.EncryptionSpecNS + "sha512"; - // Message Digest - OPTIONAL RIPEMD-160 - public static final String ALGO_ID_DIGEST_RIPEMD160 = EncryptionConstants.EncryptionSpecNS + "ripemd160"; - */ + /** Tag of Element CipherReference **/ + public static final String _TAG_CIPHERREFERENCE = "CipherReference"; - /** Message Authentication - RECOMMENDED XML Digital Signature */ - public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + /** Tag of Element CipherValue **/ + public static final String _TAG_CIPHERVALUE = "CipherValue"; - /** Canonicalization - OPTIONAL Canonical XML with Comments */ - public static final String ALGO_ID_C14N_WITHCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; - /** Canonicalization - OPTIONAL Canonical XML (omits comments) */ - public static final String ALGO_ID_C14N_OMITCOMMENTS = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + /** Tag of Element DataReference **/ + public static final String _TAG_DATAREFERENCE = "DataReference"; - /** Encoding - REQUIRED base64 */ - public static final String ALGO_ID_ENCODING_BASE64 = "http://www.w3.org/2000/09/xmldsig#base64"; - //J+ + /** Tag of Element EncryptedData **/ + public static final String _TAG_ENCRYPTEDDATA = "EncryptedData"; - private EncryptionConstants() { - // we don't allow instantiation - } + /** Tag of Element EncryptedKey **/ + public static final String _TAG_ENCRYPTEDKEY = "EncryptedKey"; - /** - * Method setEncryptionSpecNSprefix - * - * @param newPrefix - * @throws XMLSecurityException - */ - public static void setEncryptionSpecNSprefix(String newPrefix) - throws XMLSecurityException { - ElementProxy.setDefaultPrefix(EncryptionConstants.EncryptionSpecNS, - newPrefix); - } + /** Tag of Element EncryptionMethod **/ + public static final String _TAG_ENCRYPTIONMETHOD = "EncryptionMethod"; + + /** Tag of Element EncryptionProperties **/ + public static final String _TAG_ENCRYPTIONPROPERTIES = "EncryptionProperties"; + + /** Tag of Element EncryptionProperty **/ + public static final String _TAG_ENCRYPTIONPROPERTY = "EncryptionProperty"; + + /** Tag of Element KeyReference **/ + public static final String _TAG_KEYREFERENCE = "KeyReference"; + + /** Tag of Element KeySize **/ + public static final String _TAG_KEYSIZE = "KeySize"; + + /** Tag of Element OAEPparams **/ + public static final String _TAG_OAEPPARAMS = "OAEPparams"; + + /** Tag of Element MGF **/ + public static final String _TAG_MGF = "MGF"; + + /** Tag of Element ReferenceList **/ + public static final String _TAG_REFERENCELIST = "ReferenceList"; + + /** Tag of Element Transforms **/ + public static final String _TAG_TRANSFORMS = "Transforms"; + + /** Tag of Element AgreementMethod **/ + public static final String _TAG_AGREEMENTMETHOD = "AgreementMethod"; + + /** Tag of Element KA-Nonce **/ + public static final String _TAG_KA_NONCE = "KA-Nonce"; + + /** Tag of Element OriginatorKeyInfo **/ + public static final String _TAG_ORIGINATORKEYINFO = "OriginatorKeyInfo"; + + /** Tag of Element RecipientKeyInfo **/ + public static final String _TAG_RECIPIENTKEYINFO = "RecipientKeyInfo"; + + /** Field ENCRYPTIONSPECIFICATION_URL */ + public static final String ENCRYPTIONSPECIFICATION_URL = + "http://www.w3.org/TR/2001/WD-xmlenc-core-20010626/"; + + /** The namespace of the + * + * XML Encryption Syntax and Processing */ + public static final String EncryptionSpecNS = + "http://www.w3.org/2001/04/xmlenc#"; + + /** + * The namespace of the XML Encryption 1.1 specification + */ + public static final String EncryptionSpec11NS = + "http://www.w3.org/2009/xmlenc11#"; + + /** URI for content*/ + public static final String TYPE_CONTENT = EncryptionSpecNS + "Content"; + + /** URI for element*/ + public static final String TYPE_ELEMENT = EncryptionSpecNS + "Element"; + + /** URI for mediatype*/ + public static final String TYPE_MEDIATYPE = + "http://www.isi.edu/in-notes/iana/assignments/media-types/"; + + /** Block Encryption - REQUIRED TRIPLEDES */ + public static final String ALGO_ID_BLOCKCIPHER_TRIPLEDES = + EncryptionConstants.EncryptionSpecNS + "tripledes-cbc"; + + /** Block Encryption - REQUIRED AES-128 */ + public static final String ALGO_ID_BLOCKCIPHER_AES128 = + EncryptionConstants.EncryptionSpecNS + "aes128-cbc"; + + /** Block Encryption - REQUIRED AES-256 */ + public static final String ALGO_ID_BLOCKCIPHER_AES256 = + EncryptionConstants.EncryptionSpecNS + "aes256-cbc"; + + /** Block Encryption - OPTIONAL AES-192 */ + public static final String ALGO_ID_BLOCKCIPHER_AES192 = + EncryptionConstants.EncryptionSpecNS + "aes192-cbc"; + + /** Block Encryption - OPTIONAL AES-128-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES128_GCM = + "http://www.w3.org/2009/xmlenc11#aes128-gcm"; + + /** Block Encryption - OPTIONAL AES-192-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES192_GCM = + "http://www.w3.org/2009/xmlenc11#aes192-gcm"; + + /** Block Encryption - OPTIONAL AES-256-GCM */ + public static final String ALGO_ID_BLOCKCIPHER_AES256_GCM = + "http://www.w3.org/2009/xmlenc11#aes256-gcm"; + + /** Key Transport - REQUIRED RSA-v1.5*/ + public static final String ALGO_ID_KEYTRANSPORT_RSA15 = + EncryptionConstants.EncryptionSpecNS + "rsa-1_5"; + + /** Key Transport - REQUIRED RSA-OAEP */ + public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP = + EncryptionConstants.EncryptionSpecNS + "rsa-oaep-mgf1p"; + + /** Key Transport - OPTIONAL RSA-OAEP_11 */ + public static final String ALGO_ID_KEYTRANSPORT_RSAOAEP_11 = + EncryptionConstants.EncryptionSpec11NS + "rsa-oaep"; + + /** Key Agreement - OPTIONAL Diffie-Hellman */ + public static final String ALGO_ID_KEYAGREEMENT_DH = + EncryptionConstants.EncryptionSpecNS + "dh"; + + /** Symmetric Key Wrap - REQUIRED TRIPLEDES KeyWrap */ + public static final String ALGO_ID_KEYWRAP_TRIPLEDES = + EncryptionConstants.EncryptionSpecNS + "kw-tripledes"; + + /** Symmetric Key Wrap - REQUIRED AES-128 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES128 = + EncryptionConstants.EncryptionSpecNS + "kw-aes128"; + + /** Symmetric Key Wrap - REQUIRED AES-256 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES256 = + EncryptionConstants.EncryptionSpecNS + "kw-aes256"; + + /** Symmetric Key Wrap - OPTIONAL AES-192 KeyWrap */ + public static final String ALGO_ID_KEYWRAP_AES192 = + EncryptionConstants.EncryptionSpecNS + "kw-aes192"; + + /** Message Authentication - RECOMMENDED XML Digital Signature */ + public static final String ALGO_ID_AUTHENTICATION_XMLSIGNATURE = + "http://www.w3.org/TR/2001/CR-xmldsig-core-20010419/"; + + /** Canonicalization - OPTIONAL Canonical XML with Comments */ + public static final String ALGO_ID_C14N_WITHCOMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315#WithComments"; + + /** Canonicalization - OPTIONAL Canonical XML (omits comments) */ + public static final String ALGO_ID_C14N_OMITCOMMENTS = + "http://www.w3.org/TR/2001/REC-xml-c14n-20010315"; + + /** Encoding - REQUIRED base64 */ + public static final String ALGO_ID_ENCODING_BASE64 = + "http://www.w3.org/2000/09/xmldsig#base64"; + + /** MGF1 with SHA-1 */ + public static final String MGF1_SHA1 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha1"; + + /** MGF1 with SHA-224 */ + public static final String MGF1_SHA224 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha224"; + + /** MGF1 with SHA-256 */ + public static final String MGF1_SHA256 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha256"; + + /** MGF1 with SHA-384 */ + public static final String MGF1_SHA384 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha384"; + + /** MGF1 with SHA-512 */ + public static final String MGF1_SHA512 = + EncryptionConstants.EncryptionSpec11NS + "mgf1sha512"; + + + private EncryptionConstants() { + // we don't allow instantiation + } - /** - * Method getEncryptionSpecNSprefix - * - * @return the prefix for this node. - */ - public static String getEncryptionSpecNSprefix() { - return ElementProxy - .getDefaultPrefix(EncryptionConstants.EncryptionSpecNS); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java index d6fd93d1aa7..53a5cc88c5e 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/EncryptionElementProxy.java @@ -2,62 +2,62 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * This is the base object for all objects which map directly to an Element from * the xenc spec. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public abstract class EncryptionElementProxy extends ElementProxy { - /** - * Constructor EncryptionElementProxy - * - * @param doc - */ - public EncryptionElementProxy(Document doc) { - super(doc); - } + /** + * Constructor EncryptionElementProxy + * + * @param doc + */ + public EncryptionElementProxy(Document doc) { + super(doc); + } - /** - * Constructor EncryptionElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public EncryptionElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); - } + /** + * Constructor EncryptionElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public EncryptionElementProxy(Element element, String BaseURI) + throws XMLSecurityException { + super(element, BaseURI); + } - /** @inheritDoc */ - public final String getBaseNamespace() { - return EncryptionConstants.EncryptionSpecNS; - } + /** @inheritDoc */ + public final String getBaseNamespace() { + return EncryptionConstants.EncryptionSpecNS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java index cd40b79d47a..8ba53a6153c 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/HelperNodeList.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -28,75 +30,69 @@ import org.w3c.dom.Node; import org.w3c.dom.NodeList; /** - * * @author Christian Geuer-Pollmann - * */ public class HelperNodeList implements NodeList { - /** Field nodes */ - List nodes = new ArrayList(20); - boolean _allNodesMustHaveSameParent = false; + /** Field nodes */ + List nodes = new ArrayList(); + boolean allNodesMustHaveSameParent = false; - /** - * - */ - public HelperNodeList() { - this(false); - } + /** + * + */ + public HelperNodeList() { + this(false); + } - /** - * @param allNodesMustHaveSameParent - */ - public HelperNodeList(boolean allNodesMustHaveSameParent) { - this._allNodesMustHaveSameParent = allNodesMustHaveSameParent; - } + /** + * @param allNodesMustHaveSameParent + */ + public HelperNodeList(boolean allNodesMustHaveSameParent) { + this.allNodesMustHaveSameParent = allNodesMustHaveSameParent; + } - /** - * Method item - * - * @param index - * @return node with inde i - */ - public Node item(int index) { + /** + * Method item + * + * @param index + * @return node with index i + */ + public Node item(int index) { + return nodes.get(index); + } - // log.log(java.util.logging.Level.FINE, "item(" + index + ") of " + this.getLength() + " nodes"); + /** + * Method getLength + * + * @return length of the list + */ + public int getLength() { + return nodes.size(); + } - return nodes.get(index); - } - - /** - * Method getLength - * - * @return length of the list - */ - public int getLength() { - return nodes.size(); - } - - /** - * Method appendChild - * - * @param node - * @throws IllegalArgumentException - */ - public void appendChild(Node node) throws IllegalArgumentException { - if (this._allNodesMustHaveSameParent && this.getLength() > 0) { - if (this.item(0).getParentNode() != node.getParentNode()) { + /** + * Method appendChild + * + * @param node + * @throws IllegalArgumentException + */ + public void appendChild(Node node) throws IllegalArgumentException { + if (this.allNodesMustHaveSameParent && this.getLength() > 0 + && this.item(0).getParentNode() != node.getParentNode()) { throw new IllegalArgumentException("Nodes have not the same Parent"); - } - } - nodes.add(node); - } + } + nodes.add(node); + } - /** - * @return the document that contains this nodelist - */ - public Document getOwnerDocument() { - if (this.getLength() == 0) { - return null; - } - return XMLUtils.getOwnerDocument(this.item(0)); - } + /** + * @return the document that contains this nodelist + */ + public Document getOwnerDocument() { + if (this.getLength() == 0) { + return null; + } + return XMLUtils.getOwnerDocument(this.item(0)); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java index 4ee51ac92ab..ea9ec28d6e8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IdResolver.java @@ -2,85 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; -import java.lang.ref.WeakReference; -import java.util.Arrays; -import java.util.WeakHashMap; -import java.util.Map; - import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; -import org.w3c.dom.NamedNodeMap; -import org.w3c.dom.Node; /** * Purpose of this class is to enable the XML Parser to keep track of ID * attributes. This is done by 'registering' attributes of type ID at the - * IdResolver. This is necessary if we create a document from scratch and we - * sign some resources with a URI using a fragent identifier... - *
    - * The problem is that if you do not validate a document, you cannot use the - * getElementByID functionality. So this modules uses some implicit - * knowledge on selected Schemas and DTDs to pick the right Element for a given - * ID: We know that all @Id attributes in an Element from the XML - * Signature namespace are of type ID. - * - * @author $Author: mullan $ - * @see "Identity Crisis" on xml.com + * IdResolver. + * @deprecated */ +@Deprecated public class IdResolver { - /** {@link java.util.logging} logging facility */ - private static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(IdResolver.class.getName()); - - private static Map>> docMap = - new WeakHashMap>>(); - - /** - * Constructor IdResolver - * - */ private IdResolver() { - // we don't allow instantiation - } - - /** - * Method registerElementById - * - * @param element the element to register - * @param idValue the value of the ID attribute - */ - public static void registerElementById(Element element, String idValue) { - Document doc = element.getOwnerDocument(); - Map> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - if (elementMap == null) { - elementMap = new WeakHashMap>(); - docMap.put(doc, elementMap); - } - } - elementMap.put(idValue, new WeakReference(element)); + // we don't allow instantiation } /** @@ -90,7 +47,7 @@ public class IdResolver { * @param id the ID attribute */ public static void registerElementById(Element element, Attr id) { - IdResolver.registerElementById(element, id.getNodeValue()); + element.setIdAttributeNode(id, true); } /** @@ -101,194 +58,7 @@ public class IdResolver { * @return the element obtained by the id, or null if it is not found. */ public static Element getElementById(Document doc, String id) { - - Element result = IdResolver.getElementByIdType(doc, id); - - if (result != null) { - log.log(java.util.logging.Level.FINE, - "I could find an Element using the simple getElementByIdType method: " - + result.getTagName()); - - return result; - } - - result = IdResolver.getElementByIdUsingDOM(doc, id); - - if (result != null) { - log.log(java.util.logging.Level.FINE, - "I could find an Element using the simple getElementByIdUsingDOM method: " - + result.getTagName()); - - return result; - } - // this must be done so that Xalan can catch ALL namespaces - //XMLUtils.circumventBug2650(doc); - result = IdResolver.getElementBySearching(doc, id); - - if (result != null) { - IdResolver.registerElementById(result, id); - - return result; - } - - return null; - } - - - /** - * Method getElementByIdUsingDOM - * - * @param doc the document - * @param id the value of the ID - * @return the element obtained by the id, or null if it is not found. - */ - private static Element getElementByIdUsingDOM(Document doc, String id) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "getElementByIdUsingDOM() Search for ID " + id); return doc.getElementById(id); } - /** - * Method getElementByIdType - * - * @param doc the document - * @param id the value of the ID - * @return the element obtained by the id, or null if it is not found. - */ - private static Element getElementByIdType(Document doc, String id) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "getElementByIdType() Search for ID " + id); - Map> elementMap; - synchronized (docMap) { - elementMap = docMap.get(doc); - } - if (elementMap != null) { - WeakReference weakReference = elementMap.get(id); - if (weakReference != null) { - return weakReference.get(); - } - } - return null; - } - - private static java.util.List names; - private static int namesLength; - static { - String namespaces[]={ - Constants.SignatureSpecNS, - EncryptionConstants.EncryptionSpecNS, - "http://schemas.xmlsoap.org/soap/security/2000-12", - "http://www.w3.org/2002/03/xkms#", - "urn:oasis:names:tc:SAML:1.0:assertion", - "urn:oasis:names:tc:SAML:1.0:protocol" - }; - names = Arrays.asList(namespaces); - namesLength = names.size(); - } - - - private static Element getElementBySearching(Node root,String id) { - Element []els=new Element[namesLength + 1]; - getEl(root,id,els); - for (int i=0;i2) - continue; - String value=n.getNodeValue(); - if (name.charAt(0)=='I') { - char ch=name.charAt(1); - if (ch=='d' && value.equals(id)) { - els[index]=el; - if (index==0) { - return 1; - } - } else if (ch=='D' &&value.endsWith(id)) { - if (index!=3) { - index=namesLength; - } - els[index]=el; - } - } else if ( "id".equals(name) && value.equals(id) ) { - if (index!=2) { - index=namesLength; - } - els[index]=el; - } - } - //For an element namespace search for importants - if ((elementIndex==3)&&( - el.getAttribute("OriginalRequestID").equals(id) || - el.getAttribute("RequestID").equals(id) || - el.getAttribute("ResponseID").equals(id))) { - els[3]=el; - } else if ((elementIndex==4)&&( - el.getAttribute("AssertionID").equals(id))) { - els[4]=el; - } else if ((elementIndex==5)&&( - el.getAttribute("RequestID").equals(id) || - el.getAttribute("ResponseID").equals(id))) { - els[5]=el; - } - return 0; - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java index 6eae527a570..d06a41ffd20 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/IgnoreAllErrorHandler.java @@ -2,82 +2,80 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - import org.xml.sax.ErrorHandler; import org.xml.sax.SAXException; import org.xml.sax.SAXParseException; - /** - * This {@link org.xml.sax.ErrorHandler} does absulutely nothing but logging + * This {@link org.xml.sax.ErrorHandler} does absolutely nothing but log * the events. * * @author Christian Geuer-Pollmann */ public class IgnoreAllErrorHandler implements ErrorHandler { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - IgnoreAllErrorHandler.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(IgnoreAllErrorHandler.class.getName()); - /** Field throwExceptions */ - static final boolean warnOnExceptions = System.getProperty( - "com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); + /** Field throwExceptions */ + private static final boolean warnOnExceptions = + System.getProperty("com.sun.org.apache.xml.internal.security.test.warn.on.exceptions", "false").equals("true"); - /** Field throwExceptions */ - static final boolean throwExceptions = System.getProperty( - "com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); + /** Field throwExceptions */ + private static final boolean throwExceptions = + System.getProperty("com.sun.org.apache.xml.internal.security.test.throw.exceptions", "false").equals("true"); - /** @inheritDoc */ - public void warning(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.WARNING, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** @inheritDoc */ + public void warning(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.WARNING, "", ex); } - - - /** @inheritDoc */ - public void error(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.SEVERE, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; } + } - - /** @inheritDoc */ - public void fatalError(SAXParseException ex) throws SAXException { - if (IgnoreAllErrorHandler.warnOnExceptions) { - log.log(java.util.logging.Level.WARNING, "", ex); - } - if (IgnoreAllErrorHandler.throwExceptions) { - throw ex; - } + /** @inheritDoc */ + public void error(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.SEVERE, "", ex); } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; + } + } + + + /** @inheritDoc */ + public void fatalError(SAXParseException ex) throws SAXException { + if (IgnoreAllErrorHandler.warnOnExceptions) { + log.log(java.util.logging.Level.WARNING, "", ex); + } + if (IgnoreAllErrorHandler.throwExceptions) { + throw ex; + } + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java new file mode 100644 index 00000000000..242e80ff6e9 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathAPI.java @@ -0,0 +1,132 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import javax.xml.XMLConstants; +import javax.xml.transform.TransformerException; +import javax.xml.xpath.XPath; +import javax.xml.xpath.XPathConstants; +import javax.xml.xpath.XPathExpression; +import javax.xml.xpath.XPathExpressionException; +import javax.xml.xpath.XPathFactory; +import javax.xml.xpath.XPathFactoryConfigurationException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An implementation for XPath evaluation that uses the JDK API. + */ +public class JDKXPathAPI implements XPathAPI { + + private XPathFactory xpf; + + private String xpathStr; + + private XPathExpression xpathExpression; + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + public NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException { + if (!str.equals(xpathStr) || xpathExpression == null) { + if (xpf == null) { + xpf = XPathFactory.newInstance(); + try { + xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + } catch (XPathFactoryConfigurationException ex) { + throw new TransformerException("empty", ex); + } + } + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); + xpathStr = str; + try { + xpathExpression = xpath.compile(xpathStr); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + try { + return (NodeList)xpathExpression.evaluate(contextNode, XPathConstants.NODESET); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + if (!str.equals(xpathStr) || xpathExpression == null) { + if (xpf == null) { + xpf = XPathFactory.newInstance(); + try { + xpf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE); + } catch (XPathFactoryConfigurationException ex) { + throw new TransformerException("empty", ex); + } + } + XPath xpath = xpf.newXPath(); + xpath.setNamespaceContext(new DOMNamespaceContext(namespaceNode)); + xpathStr = str; + try { + xpathExpression = xpath.compile(xpathStr); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + try { + Boolean result = (Boolean)xpathExpression.evaluate(contextNode, XPathConstants.BOOLEAN); + return result.booleanValue(); + } catch (XPathExpressionException ex) { + throw new TransformerException("empty", ex); + } + } + + /** + * Clear any context information from this object + */ + public void clear() { + xpathStr = null; + xpathExpression = null; + xpf = null; + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java new file mode 100644 index 00000000000..98c1872898a --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JDKXPathFactory.java @@ -0,0 +1,37 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return a JDKXPathAPI instance. + */ +public class JDKXPathFactory extends XPathFactory { + + /** + * Get a new XPathAPI instance + */ + public XPathAPI newXPathAPI() { + return new JDKXPathAPI(); + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java index 540c722f45c..cf55f4088ba 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/JavaUtils.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -33,8 +35,8 @@ import java.io.InputStream; */ public class JavaUtils { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = java.util.logging.Logger.getLogger(JavaUtils.class.getName()); private JavaUtils() { @@ -45,7 +47,7 @@ public class JavaUtils { * Method getBytesFromFile * * @param fileName - * @return the bytes readed from the file + * @return the bytes read from the file * * @throws FileNotFoundException * @throws IOException @@ -55,9 +57,11 @@ public class JavaUtils { byte refBytes[] = null; - FileInputStream fisRef = new FileInputStream(fileName); + FileInputStream fisRef = null; + UnsyncByteArrayOutputStream baos = null; try { - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); + fisRef = new FileInputStream(fileName); + baos = new UnsyncByteArrayOutputStream(); byte buf[] = new byte[1024]; int len; @@ -67,7 +71,12 @@ public class JavaUtils { refBytes = baos.toByteArray(); } finally { - fisRef.close(); + if (baos != null) { + baos.close(); + } + if (fisRef != null) { + fisRef.close(); + } } return refBytes; @@ -80,7 +89,6 @@ public class JavaUtils { * @param bytes */ public static void writeBytesToFilename(String filename, byte[] bytes) { - FileOutputStream fos = null; try { if (filename != null && bytes != null) { @@ -91,13 +99,19 @@ public class JavaUtils { fos.write(bytes); fos.close(); } else { - log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed"); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "writeBytesToFilename got null byte[] pointed"); + } } } catch (IOException ex) { if (fos != null) { try { fos.close(); - } catch (IOException ioe) {} + } catch (IOException ioe) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ioe.getMessage(), ioe); + } + } } } } @@ -107,25 +121,28 @@ public class JavaUtils { * returns them as a byte array. * * @param inputStream - * @return the bytes readed from the stream + * @return the bytes read from the stream * * @throws FileNotFoundException * @throws IOException */ - public static byte[] getBytesFromStream(InputStream inputStream) - throws IOException { + public static byte[] getBytesFromStream(InputStream inputStream) throws IOException { + UnsyncByteArrayOutputStream baos = null; - byte refBytes[] = null; + byte[] retBytes = null; + try { + baos = new UnsyncByteArrayOutputStream(); + byte buf[] = new byte[4 * 1024]; + int len; - UnsyncByteArrayOutputStream baos = new UnsyncByteArrayOutputStream(); - byte buf[] = new byte[1024]; - int len; - - while ((len = inputStream.read(buf)) > 0) { - baos.write(buf, 0, len); + while ((len = inputStream.read(buf)) > 0) { + baos.write(buf, 0, len); + } + retBytes = baos.toByteArray(); + } finally { + baos.close(); } - refBytes = baos.toByteArray(); - return refBytes; + return retBytes; } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java index 66a587511e8..1ab91701b6a 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/RFC2253Parser.java @@ -2,573 +2,473 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - - import java.io.IOException; import java.io.StringReader; - -/** - * - * @author $Author: mullan $ - */ public class RFC2253Parser { + /** + * Method rfc2253toXMLdsig + * + * @param dn + * @return normalized string + */ + public static String rfc2253toXMLdsig(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, true); - /** {@link java.util.logging} logging facility */ - /* static java.util.logging.Logger log = - java.util.logging.Logger.getLogger(RFC2253Parser.class.getName()); - */ + return rfctoXML(normalized); + } - static boolean _TOXML = true; + /** + * Method xmldsigtoRFC2253 + * + * @param dn + * @return normalized string + */ + public static String xmldsigtoRFC2253(String dn) { + // Transform from RFC1779 to RFC2253 + String normalized = normalize(dn, false); - /** - * Method rfc2253toXMLdsig - * - * @param dn - * @return normalized string - * - */ - public static String rfc2253toXMLdsig(String dn) { + return xmltoRFC(normalized); + } - _TOXML = true; + /** + * Method normalize + * + * @param dn + * @return normalized string + */ + public static String normalize(String dn) { + return normalize(dn, true); + } - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); + /** + * Method normalize + * + * @param dn + * @param toXml + * @return normalized string + */ + public static String normalize(String dn, boolean toXml) { + //if empty string + if ((dn == null) || dn.equals("")) { + return ""; + } - return rfctoXML(normalized); - } + try { + String DN = semicolonToComma(dn); + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - /** - * Method xmldsigtoRFC2253 - * - * @param dn - * @return normalized string - */ - public static String xmldsigtoRFC2253(String dn) { + //for name component + for (int j = 0; (k = DN.indexOf(',', j)) >= 0; j = k + 1) { + l += countQuotes(DN, j, k); - _TOXML = false; + if ((k > 0) && (DN.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseRDN(DN.substring(i, k).trim(), toXml) + ","); - // Transform from RFC1779 to RFC2253 - String normalized = normalize(dn); - - return xmltoRFC(normalized); - } - - /** - * Method normalize - * - * @param dn - * @return normalized string - */ - public static String normalize(String dn) { - - //if empty string - if ((dn == null) || dn.equals("")) { - return ""; - } - - try { - String _DN = semicolonToComma(dn); - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; - - //for name component - for (int j = 0; (k = _DN.indexOf(",", j)) >= 0; j = k + 1) { - l += countQuotes(_DN, j, k); - - if ((k > 0) && (_DN.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseRDN(_DN.substring(i, k).trim()) + ","); - - i = k + 1; - l = 0; + i = k + 1; + l = 0; + } } - } - sb.append(parseRDN(trim(_DN.substring(i)))); + sb.append(parseRDN(trim(DN.substring(i)), toXml)); - return sb.toString(); - } catch (IOException ex) { - return dn; - } - } + return sb.toString(); + } catch (IOException ex) { + return dn; + } + } - /** - * Method parseRDN - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseRDN(String str) throws IOException { + /** + * Method parseRDN + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String parseRDN(String str, boolean toXml) throws IOException { + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; + for (int j = 0; (k = str.indexOf('+', j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); - for (int j = 0; (k = str.indexOf("+", j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(parseATAV(trim(str.substring(i, k)), toXml) + "+"); - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(parseATAV(trim(str.substring(i, k))) + "+"); + i = k + 1; + l = 0; + } + } - i = k + 1; - l = 0; - } - } + sb.append(parseATAV(trim(str.substring(i)), toXml)); - sb.append(parseATAV(trim(str.substring(i)))); + return sb.toString(); + } - return sb.toString(); - } + /** + * Method parseATAV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String parseATAV(String str, boolean toXml) throws IOException { + int i = str.indexOf('='); - /** - * Method parseATAV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String parseATAV(String str) throws IOException { + if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) { + return str; + } + String attrType = normalizeAT(str.substring(0, i)); + // only normalize if value is a String + String attrValue = null; + if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') { + attrValue = str.substring(i + 1); + } else { + attrValue = normalizeV(str.substring(i + 1), toXml); + } - int i = str.indexOf("="); + return attrType + "=" + attrValue; - if ((i == -1) || ((i > 0) && (str.charAt(i - 1) == '\\'))) { - return str; - } - String attrType = normalizeAT(str.substring(0, i)); - // only normalize if value is a String - String attrValue = null; - if (attrType.charAt(0) >= '0' && attrType.charAt(0) <= '9') { - attrValue = str.substring(i + 1); - } else { - attrValue = normalizeV(str.substring(i + 1)); - } + } - return attrType + "=" + attrValue; + /** + * Method normalizeAT + * + * @param str + * @return normalized string + */ + static String normalizeAT(String str) { - } + String at = str.toUpperCase().trim(); - /** - * Method normalizeAT - * - * @param str - * @return normalized string - */ - static String normalizeAT(String str) { + if (at.startsWith("OID")) { + at = at.substring(3); + } - String at = str.toUpperCase().trim(); + return at; + } - if (at.startsWith("OID")) { - at = at.substring(3); - } + /** + * Method normalizeV + * + * @param str + * @param toXml + * @return normalized string + * @throws IOException + */ + static String normalizeV(String str, boolean toXml) throws IOException { + String value = trim(str); - return at; - } + if (value.startsWith("\"")) { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(value.substring(1, value.length() - 1)); + int i = 0; + char c; - /** - * Method normalizeV - * - * @param str - * @return normalized string - * @throws IOException - */ - static String normalizeV(String str) throws IOException { + while ((i = sr.read()) > -1) { + c = (char) i; - String value = trim(str); + //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 + if ((c == ',') || (c == '=') || (c == '+') || (c == '<') + || (c == '>') || (c == '#') || (c == ';')) { + sb.append('\\'); + } - if (value.startsWith("\"")) { - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(value.substring(1, - value.length() - 1)); - int i = 0; - char c; + sb.append(c); + } - for (; (i = sr.read()) > -1; ) { + value = trim(sb.toString()); + } + + if (toXml) { + if (value.startsWith("#")) { + value = '\\' + value; + } + } else { + if (value.startsWith("\\#")) { + value = value.substring(1); + } + } + + return value; + } + + /** + * Method rfctoXML + * + * @param string + * @return normalized string + */ + static String rfctoXML(String string) { + try { + String s = changeLess32toXML(string); + + return changeWStoXML(s); + } catch (Exception e) { + return string; + } + } + + /** + * Method xmltoRFC + * + * @param string + * @return normalized string + */ + static String xmltoRFC(String string) { + try { + String s = changeLess32toRFC(string); + + return changeWStoRFC(s); + } catch (Exception e) { + return string; + } + } + + /** + * Method changeLess32toRFC + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeLess32toRFC(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + char c; + + while ((i = sr.read()) > -1) { c = (char) i; - //the following char is defined at 4.Relationship with RFC1779 and LDAPv2 inrfc2253 - if ((c == ',') || (c == '=') || (c == '+') || (c == '<') - || (c == '>') || (c == '#') || (c == ';')) { - sb.append('\\'); - } + if (c == '\\') { + sb.append(c); - sb.append(c); - } + char c1 = (char) sr.read(); + char c2 = (char) sr.read(); - value = trim(sb.toString()); - } - - if (_TOXML == true) { - if (value.startsWith("#")) { - value = '\\' + value; - } - } else { - if (value.startsWith("\\#")) { - value = value.substring(1); - } - } - - return value; - } - - /** - * Method rfctoXML - * - * @param string - * @return normalized string - */ - static String rfctoXML(String string) { - - try { - String s = changeLess32toXML(string); - - return changeWStoXML(s); - } catch (Exception e) { - return string; - } - } - - /** - * Method xmltoRFC - * - * @param string - * @return normalized string - */ - static String xmltoRFC(String string) { - - try { - String s = changeLess32toRFC(string); - - return changeWStoRFC(s); - } catch (Exception e) { - return string; - } - } - - /** - * Method changeLess32toRFC - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toRFC(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - char c; - - for (; (i = sr.read()) > -1; ) { - c = (char) i; - - if (c == '\\') { - sb.append(c); - - char c1 = (char) sr.read(); - char c2 = (char) sr.read(); - - //65 (A) 97 (a) - if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102))) + //65 (A) 97 (a) + if ((((c1 >= 48) && (c1 <= 57)) || ((c1 >= 65) && (c1 <= 70)) || ((c1 >= 97) && (c1 <= 102))) && (((c2 >= 48) && (c2 <= 57)) || ((c2 >= 65) && (c2 <= 70)) || ((c2 >= 97) && (c2 <= 102)))) { - char ch = (char) Byte.parseByte("" + c1 + c2, 16); + char ch = (char) Byte.parseByte("" + c1 + c2, 16); - sb.append(ch); + sb.append(ch); + } else { + sb.append(c1); + sb.append(c2); + } } else { - sb.append(c1); - sb.append(c2); + sb.append(c); } - } else { - sb.append(c); - } - } + } - return sb.toString(); - } + return sb.toString(); + } - /** - * Method changeLess32toXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeLess32toXML(String string) throws IOException { + /** + * Method changeLess32toXML + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeLess32toXML(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - - for (; (i = sr.read()) > -1; ) { - if (i < 32) { - sb.append('\\'); - sb.append(Integer.toHexString(i)); - } else { - sb.append((char) i); - } - } - - return sb.toString(); - } - - /** - * Method changeWStoXML - * - * @param string - * @return normalized string - * @throws IOException - */ - static String changeWStoXML(String string) throws IOException { - - StringBuffer sb = new StringBuffer(); - StringReader sr = new StringReader(string); - int i = 0; - char c; - - for (; (i = sr.read()) > -1; ) { - c = (char) i; - - if (c == '\\') { - char c1 = (char) sr.read(); - - if (c1 == ' ') { - sb.append('\\'); - - String s = "20"; - - sb.append(s); + while ((i = sr.read()) > -1) { + if (i < 32) { + sb.append('\\'); + sb.append(Integer.toHexString(i)); } else { - sb.append('\\'); - sb.append(c1); + sb.append((char) i); } - } else { - sb.append(c); - } - } + } - return sb.toString(); - } + return sb.toString(); + } - /** - * Method changeWStoRFC - * - * @param string - * @return normalized string - */ - static String changeWStoRFC(String string) { + /** + * Method changeWStoXML + * + * @param string + * @return normalized string + * @throws IOException + */ + static String changeWStoXML(String string) throws IOException { + StringBuilder sb = new StringBuilder(); + StringReader sr = new StringReader(string); + int i = 0; + char c; - StringBuffer sb = new StringBuffer(); - int i = 0; - int k; + while ((i = sr.read()) > -1) { + c = (char) i; - for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { - sb.append(trim(string.substring(i, k)) + "\\ "); + if (c == '\\') { + char c1 = (char) sr.read(); - i = k + 3; - } + if (c1 == ' ') { + sb.append('\\'); - sb.append(string.substring(i)); + String s = "20"; - return sb.toString(); - } + sb.append(s); + } else { + sb.append('\\'); + sb.append(c1); + } + } else { + sb.append(c); + } + } - /** - * Method semicolonToComma - * - * @param str - * @return normalized string - */ - static String semicolonToComma(String str) { - return removeWSandReplace(str, ";", ","); - } + return sb.toString(); + } - /** - * Method removeWhiteSpace - * - * @param str - * @param symbol - * @return normalized string - */ - static String removeWhiteSpace(String str, String symbol) { - return removeWSandReplace(str, symbol, symbol); - } + /** + * Method changeWStoRFC + * + * @param string + * @return normalized string + */ + static String changeWStoRFC(String string) { + StringBuilder sb = new StringBuilder(); + int i = 0; + int k; - /** - * Method removeWSandReplace - * - * @param str - * @param symbol - * @param replace - * @return normalized string - */ - static String removeWSandReplace(String str, String symbol, String replace) { + for (int j = 0; (k = string.indexOf("\\20", j)) >= 0; j = k + 3) { + sb.append(trim(string.substring(i, k)) + "\\ "); - StringBuffer sb = new StringBuffer(); - int i = 0; - int l = 0; - int k; + i = k + 3; + } - for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { - l += countQuotes(str, j, k); + sb.append(string.substring(i)); - if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) != 1) { - sb.append(trim(str.substring(i, k)) + replace); + return sb.toString(); + } - i = k + 1; - l = 0; - } - } + /** + * Method semicolonToComma + * + * @param str + * @return normalized string + */ + static String semicolonToComma(String str) { + return removeWSandReplace(str, ";", ","); + } - sb.append(trim(str.substring(i))); + /** + * Method removeWhiteSpace + * + * @param str + * @param symbol + * @return normalized string + */ + static String removeWhiteSpace(String str, String symbol) { + return removeWSandReplace(str, symbol, symbol); + } - return sb.toString(); - } + /** + * Method removeWSandReplace + * + * @param str + * @param symbol + * @param replace + * @return normalized string + */ + static String removeWSandReplace(String str, String symbol, String replace) { + StringBuilder sb = new StringBuilder(); + int i = 0; + int l = 0; + int k; - /** - * Returns the number of Quotation from i to j - * - * @param s - * @param i - * @param j - * @return number of quotes - */ - private static int countQuotes(String s, int i, int j) { + for (int j = 0; (k = str.indexOf(symbol, j)) >= 0; j = k + 1) { + l += countQuotes(str, j, k); - int k = 0; + if ((k > 0) && (str.charAt(k - 1) != '\\') && (l % 2) == 0) { + sb.append(trim(str.substring(i, k)) + replace); - for (int l = i; l < j; l++) { - if (s.charAt(l) == '"') { - k++; - } - } + i = k + 1; + l = 0; + } + } - return k; - } + sb.append(trim(str.substring(i))); - //only for the end of a space character occurring at the end of the string from rfc2253 + return sb.toString(); + } - /** - * Method trim - * - * @param str - * @return the string - */ - static String trim(String str) { + /** + * Returns the number of Quotation from i to j + * + * @param s + * @param i + * @param j + * @return number of quotes + */ + private static int countQuotes(String s, int i, int j) { + int k = 0; - String trimed = str.trim(); - int i = str.indexOf(trimed) + trimed.length(); + for (int l = i; l < j; l++) { + if (s.charAt(l) == '"') { + k++; + } + } - if ((str.length() > i) && trimed.endsWith("\\") - &&!trimed.endsWith("\\\\")) { - if (str.charAt(i) == ' ') { + return k; + } + + //only for the end of a space character occurring at the end of the string from rfc2253 + + /** + * Method trim + * + * @param str + * @return the string + */ + static String trim(String str) { + + String trimed = str.trim(); + int i = str.indexOf(trimed) + trimed.length(); + + if ((str.length() > i) && trimed.endsWith("\\") + && !trimed.endsWith("\\\\") && (str.charAt(i) == ' ')) { trimed = trimed + " "; - } - } + } - return trimed; - } + return trimed; + } - /** - * Method main - * - * @param args - * @throws Exception - */ - public static void main(String[] args) throws Exception { - - testToXML("CN=\"Steve, Kille\", O=Isode Limited, C=GB"); - testToXML("CN=Steve Kille , O=Isode Limited,C=GB"); - testToXML("\\ OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\ \\ "); - testToXML("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"); - testToXML("CN=Before\\0DAfter,O=Test,C=GB"); - testToXML("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"); - testToXML("1.3.6.1.4.1.1466.0=#04024869,O=Test,C=GB"); - - { - StringBuffer sb = new StringBuffer(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToXML(test7); - } - - testToRFC("CN=\"Steve, Kille\", O=Isode Limited, C=GB"); - testToRFC("CN=Steve Kille , O=Isode Limited,C=GB"); - testToRFC("\\20OU=Sales+CN=J. Smith,O=Widget Inc.,C=US\\20\\20 "); - testToRFC("CN=L. Eagle,O=Sue\\, Grabbit and Runn,C=GB"); - testToRFC("CN=Before\\12After,O=Test,C=GB"); - testToRFC("CN=\"L. Eagle,O=Sue, = + < > # ;Grabbit and Runn\",C=GB"); - testToRFC("1.3.6.1.4.1.1466.0=\\#04024869,O=Test,C=GB"); - - { - StringBuffer sb = new StringBuffer(); - - sb.append('L'); - sb.append('u'); - sb.append('\uc48d'); - sb.append('i'); - sb.append('\uc487'); - - String test7 = "SN=" + sb.toString(); - - testToRFC(test7); - } - } - - /** Field i */ - static int counter = 0; - - /** - * Method test - * - * @param st - */ - static void testToXML(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + rfc2253toXMLdsig(st)); - System.out.println(""); - } - - /** - * Method testToRFC - * - * @param st - */ - static void testToRFC(String st) { - - System.out.println("start " + counter++ + ": " + st); - System.out.println(" " + xmldsigtoRFC2253(st)); - System.out.println(""); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java new file mode 100644 index 00000000000..dffcd89f47b --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/Signature11ElementProxy.java @@ -0,0 +1,70 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; +import org.w3c.dom.Document; +import org.w3c.dom.Element; + +/** + * Class SignatureElementProxy + * + * @author Brent Putman (putmanb@georgetown.edu) + */ +public abstract class Signature11ElementProxy extends ElementProxy { + + protected Signature11ElementProxy() { + }; + + /** + * Constructor Signature11ElementProxy + * + * @param doc + */ + public Signature11ElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } + + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignature11Space(this.doc, this.getBaseLocalName()); + } + + /** + * Constructor Signature11ElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public Signature11ElementProxy(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpec11NS; + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java index d49cc676acf..3a97bd3d411 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignatureElementProxy.java @@ -2,70 +2,69 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Document; import org.w3c.dom.Element; - /** * Class SignatureElementProxy * - * @author $Author: mullan $ - * @version $Revision: 1.5 $ + * @author $Author: coheigea $ */ public abstract class SignatureElementProxy extends ElementProxy { - protected SignatureElementProxy() { - }; - /** - * Constructor SignatureElementProxy - * - * @param doc - */ - public SignatureElementProxy(Document doc) { - if (doc == null) { - throw new RuntimeException("Document is null"); - } - this._doc = doc; - this._constructionElement = XMLUtils.createElementInSignatureSpace(this._doc, - this.getBaseLocalName()); - } + protected SignatureElementProxy() { + }; - /** - * Constructor SignatureElementProxy - * - * @param element - * @param BaseURI - * @throws XMLSecurityException - */ - public SignatureElementProxy(Element element, String BaseURI) - throws XMLSecurityException { - super(element, BaseURI); + /** + * Constructor SignatureElementProxy + * + * @param doc + */ + public SignatureElementProxy(Document doc) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - } + this.doc = doc; + this.constructionElement = + XMLUtils.createElementInSignatureSpace(this.doc, this.getBaseLocalName()); + } - /** @inheritDoc */ - public String getBaseNamespace() { - return Constants.SignatureSpecNS; - } + /** + * Constructor SignatureElementProxy + * + * @param element + * @param BaseURI + * @throws XMLSecurityException + */ + public SignatureElementProxy(Element element, String BaseURI) throws XMLSecurityException { + super(element, BaseURI); + + } + + /** @inheritDoc */ + public String getBaseNamespace() { + return Constants.SignatureSpecNS; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java index 068d523bd64..c8f5747d396 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/SignerOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2008 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -30,53 +32,50 @@ import com.sun.org.apache.xml.internal.security.signature.XMLSignatureException; * */ public class SignerOutputStream extends ByteArrayOutputStream { + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(SignerOutputStream.class.getName()); + final SignatureAlgorithm sa; - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger - (SignerOutputStream.class.getName()); /** * @param sa */ public SignerOutputStream(SignatureAlgorithm sa) { - this.sa=sa; + this.sa = sa; } /** @inheritDoc */ public void write(byte[] arg0) { - super.write(arg0, 0, arg0.length); try { sa.update(arg0); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } /** @inheritDoc */ public void write(int arg0) { - super.write(arg0); try { sa.update((byte)arg0); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } /** @inheritDoc */ public void write(byte[] arg0, int arg1, int arg2) { - super.write(arg0, arg1, arg2); if (log.isLoggable(java.util.logging.Level.FINE)) { log.log(java.util.logging.Level.FINE, "Canonicalized SignedInfo:"); - StringBuffer sb = new StringBuffer(arg2); - for (int i=arg1; i<(arg1+arg2); i++) { - sb.append((char) arg0[i]); + StringBuilder sb = new StringBuilder(arg2); + for (int i = arg1; i < (arg1 + arg2); i++) { + sb.append((char)arg0[i]); } log.log(java.util.logging.Level.FINE, sb.toString()); } try { - sa.update(arg0,arg1,arg2); + sa.update(arg0, arg1, arg2); } catch (XMLSignatureException e) { - throw new RuntimeException(""+e); + throw new RuntimeException("" + e); } } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java index e9a7935e7ea..f424dd51b74 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncBufferedOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2005 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -24,75 +26,73 @@ import java.io.IOException; import java.io.OutputStream; /** - * A class that buffers writte without synchronize its methods + * A class that buffers without synchronizing its methods * @author raul - * */ public class UnsyncBufferedOutputStream extends OutputStream { - final OutputStream out; + static final int size = 8*1024; - final byte[] buf; - static final int size=8*1024; - private static ThreadLocal bufCahce = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[size]; + private int pointer = 0; + private final OutputStream out; + + private final byte[] buf; + + /** + * Creates a buffered output stream without synchronization + * @param out the outputstream to buffer + */ + public UnsyncBufferedOutputStream(OutputStream out) { + buf = new byte[size]; + this.out = out; + } + + /** @inheritDoc */ + public void write(byte[] arg0) throws IOException { + write(arg0, 0, arg0.length); + } + + /** @inheritDoc */ + public void write(byte[] arg0, int arg1, int len) throws IOException { + int newLen = pointer+len; + if (newLen > size) { + flushBuffer(); + if (len > size) { + out.write(arg0, arg1,len); + return; + } + newLen = len; } - }; - int pointer=0; - /** - * Creates a buffered output stream without synchronization - * @param out the outputstream to buffer - */ - public UnsyncBufferedOutputStream(OutputStream out) { - buf=bufCahce.get(); - this.out=out; + System.arraycopy(arg0, arg1, buf, pointer, len); + pointer = newLen; + } + + private void flushBuffer() throws IOException { + if (pointer > 0) { + out.write(buf, 0, pointer); } + pointer = 0; - /** @inheritDoc */ - public void write(byte[] arg0) throws IOException { - write(arg0,0,arg0.length); + } + + /** @inheritDoc */ + public void write(int arg0) throws IOException { + if (pointer >= size) { + flushBuffer(); } + buf[pointer++] = (byte)arg0; - /** @inheritDoc */ - public void write(byte[] arg0, int arg1, int len) throws IOException { - int newLen=pointer+len; - if (newLen> size) { - flushBuffer(); - if (len>size) { - out.write(arg0,arg1,len); - return; - } - newLen=len; - } - System.arraycopy(arg0,arg1,buf,pointer,len); - pointer=newLen; - } + } - private final void flushBuffer() throws IOException { - if (pointer>0) - out.write(buf,0,pointer); - pointer=0; + /** @inheritDoc */ + public void flush() throws IOException { + flushBuffer(); + out.flush(); + } - } - - /** @inheritDoc */ - public void write(int arg0) throws IOException { - if (pointer>= size) { - flushBuffer(); - } - buf[pointer++]=(byte)arg0; - - } - - /** @inheritDoc */ - public void flush() throws IOException { - flushBuffer(); - out.flush(); - } - - /** @inheritDoc */ - public void close() throws IOException { - flush(); - } + /** @inheritDoc */ + public void close() throws IOException { + flush(); + out.close(); + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java index 2a2f7ddbd03..e6f3ea7c258 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/UnsyncByteArrayOutputStream.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2010 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; @@ -28,22 +30,21 @@ import java.io.OutputStream; * */ public class UnsyncByteArrayOutputStream extends OutputStream { + private static final int INITIAL_SIZE = 8192; - private static ThreadLocal bufCache = new ThreadLocal() { - protected synchronized byte[] initialValue() { - return new byte[INITIAL_SIZE]; - } - }; private byte[] buf; private int size = INITIAL_SIZE; private int pos = 0; public UnsyncByteArrayOutputStream() { - buf = bufCache.get(); + buf = new byte[INITIAL_SIZE]; } public void write(byte[] arg0) { + if ((Integer.MAX_VALUE - pos) < arg0.length) { + throw new OutOfMemoryError(); + } int newPos = pos + arg0.length; if (newPos > size) { expandSize(newPos); @@ -53,6 +54,9 @@ public class UnsyncByteArrayOutputStream extends OutputStream { } public void write(byte[] arg0, int arg1, int arg2) { + if ((Integer.MAX_VALUE - pos) < arg2) { + throw new OutOfMemoryError(); + } int newPos = pos + arg2; if (newPos > size) { expandSize(newPos); @@ -62,6 +66,9 @@ public class UnsyncByteArrayOutputStream extends OutputStream { } public void write(int arg0) { + if ((Integer.MAX_VALUE - pos) == 0) { + throw new OutOfMemoryError(); + } int newPos = pos + 1; if (newPos > size) { expandSize(newPos); @@ -82,7 +89,11 @@ public class UnsyncByteArrayOutputStream extends OutputStream { private void expandSize(int newPos) { int newSize = size; while (newPos > newSize) { - newSize = newSize<<2; + newSize = newSize << 1; + // Deal with overflow + if (newSize < 0) { + newSize = Integer.MAX_VALUE; + } } byte newBuf[] = new byte[newSize]; System.arraycopy(buf, 0, newBuf, 0, pos); diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java index dc01897cca5..620b6735b8f 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XMLUtils.java @@ -2,35 +2,34 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils; - import java.io.IOException; import java.io.OutputStream; import java.security.AccessController; import java.security.PrivilegedAction; import java.util.ArrayList; -import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; -import java.util.Map; import java.util.Set; import com.sun.org.apache.xml.internal.security.c14n.CanonicalizationException; @@ -42,10 +41,9 @@ import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; +import org.w3c.dom.ProcessingInstruction; import org.w3c.dom.Text; - - /** * DOM and XML accessibility and comfort functions. * @@ -53,28 +51,31 @@ import org.w3c.dom.Text; */ public class XMLUtils { - private static boolean ignoreLineBreaks = - AccessController.doPrivileged(new PrivilegedAction() { - public Boolean run() { - return Boolean.getBoolean - ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks"); - } - }); + private static boolean ignoreLineBreaks = + AccessController.doPrivileged(new PrivilegedAction() { + public Boolean run() { + return Boolean.valueOf(Boolean.getBoolean + ("com.sun.org.apache.xml.internal.security.ignoreLineBreaks")); + } + }).booleanValue(); private static volatile String dsPrefix = "ds"; + private static volatile String ds11Prefix = "dsig11"; private static volatile String xencPrefix = "xenc"; + private static volatile String xenc11Prefix = "xenc11"; - private static final java.util.logging.Logger log = - java.util.logging.Logger.getLogger(XMLUtils.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static final java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XMLUtils.class.getName()); - /** - * Constructor XMLUtils - * - */ - private XMLUtils() { - // we don't allow instantiation - } + /** + * Constructor XMLUtils + * + */ + private XMLUtils() { + // we don't allow instantiation + } /** * Set the prefix for the digital signature namespace @@ -84,6 +85,14 @@ public class XMLUtils { dsPrefix = prefix; } + /** + * Set the prefix for the digital signature 1.1 namespace + * @param prefix the new prefix for the digital signature 1.1 namespace + */ + public static void setDs11Prefix(String prefix) { + ds11Prefix = prefix; + } + /** * Set the prefix for the encryption namespace * @param prefix the new prefix for the encryption namespace @@ -92,197 +101,256 @@ public class XMLUtils { xencPrefix = prefix; } - public static Element getNextElement(Node el) { - while ((el!=null) && (el.getNodeType()!=Node.ELEMENT_NODE)) { - el=el.getNextSibling(); - } - return (Element)el; + /** + * Set the prefix for the encryption namespace 1.1 + * @param prefix the new prefix for the encryption namespace 1.1 + */ + public static void setXenc11Prefix(String prefix) { + xenc11Prefix = prefix; + } - } + public static Element getNextElement(Node el) { + Node node = el; + while ((node != null) && (node.getNodeType() != Node.ELEMENT_NODE)) { + node = node.getNextSibling(); + } + return (Element)node; + } - /** - * @param rootNode - * @param result - * @param exclude - * @param com wheather comments or not - */ - public static void getSet(Node rootNode,Set result,Node exclude ,boolean com) { - if ((exclude!=null) && isDescendantOrSelf(exclude,rootNode)){ - return; - } - getSetRec(rootNode,result,exclude,com); - } + /** + * @param rootNode + * @param result + * @param exclude + * @param com whether comments or not + */ + public static void getSet(Node rootNode, Set result, Node exclude, boolean com) { + if ((exclude != null) && isDescendantOrSelf(exclude, rootNode)) { + return; + } + getSetRec(rootNode, result, exclude, com); + } - @SuppressWarnings("fallthrough") - static final void getSetRec(final Node rootNode,final Set result, - final Node exclude ,final boolean com) { - //Set result = new HashSet(); - if (rootNode==exclude) { - return; - } - switch (rootNode.getNodeType()) { - case Node.ELEMENT_NODE: - result.add(rootNode); - Element el=(Element)rootNode; - if (el.hasAttributes()) { - NamedNodeMap nl = ((Element)rootNode).getAttributes(); - for (int i=0;i result, + final Node exclude, final boolean com) { + if (rootNode == exclude) { + return; + } + switch (rootNode.getNodeType()) { + case Node.ELEMENT_NODE: + result.add(rootNode); + Element el = (Element)rootNode; + if (el.hasAttributes()) { + NamedNodeMap nl = el.getAttributes(); + for (int i = 0;i < nl.getLength(); i++) { + result.add(nl.item(i)); } - //no return keep working - ignore fallthrough warning - case Node.DOCUMENT_NODE: - for (Node r=rootNode.getFirstChild();r!=null;r=r.getNextSibling()){ - if (r.getNodeType()==Node.TEXT_NODE) { - result.add(r); - while ((r!=null) && (r.getNodeType()==Node.TEXT_NODE)) { - r=r.getNextSibling(); - } - if (r==null) - return; - } - getSetRec(r,result,exclude,com); - } - return; - case Node.COMMENT_NODE: - if (com) { - result.add(rootNode); - } - return; - case Node.DOCUMENT_TYPE_NODE: - return; - default: - result.add(rootNode); - } - return; - } + } + //no return keep working + case Node.DOCUMENT_NODE: + for (Node r = rootNode.getFirstChild(); r != null; r = r.getNextSibling()) { + if (r.getNodeType() == Node.TEXT_NODE) { + result.add(r); + while ((r != null) && (r.getNodeType() == Node.TEXT_NODE)) { + r = r.getNextSibling(); + } + if (r == null) { + return; + } + } + getSetRec(r, result, exclude, com); + } + return; + case Node.COMMENT_NODE: + if (com) { + result.add(rootNode); + } + return; + case Node.DOCUMENT_TYPE_NODE: + return; + default: + result.add(rootNode); + } + } - /** - * Outputs a DOM tree to an {@link OutputStream}. - * - * @param contextNode root node of the DOM tree - * @param os the {@link OutputStream} - */ - public static void outputDOM(Node contextNode, OutputStream os) { - XMLUtils.outputDOM(contextNode, os, false); - } + /** + * Outputs a DOM tree to an {@link OutputStream}. + * + * @param contextNode root node of the DOM tree + * @param os the {@link OutputStream} + */ + public static void outputDOM(Node contextNode, OutputStream os) { + XMLUtils.outputDOM(contextNode, os, false); + } - /** - * Outputs a DOM tree to an {@link OutputStream}. If an Exception is - * thrown during execution, it's StackTrace is output to System.out, but the - * Exception is not re-thrown. - * - * @param contextNode root node of the DOM tree - * @param os the {@link OutputStream} - * @param addPreamble - */ - public static void outputDOM(Node contextNode, OutputStream os, - boolean addPreamble) { + /** + * Outputs a DOM tree to an {@link OutputStream}. If an Exception is + * thrown during execution, it's StackTrace is output to System.out, but the + * Exception is not re-thrown. + * + * @param contextNode root node of the DOM tree + * @param os the {@link OutputStream} + * @param addPreamble + */ + public static void outputDOM(Node contextNode, OutputStream os, boolean addPreamble) { + try { + if (addPreamble) { + os.write("\n".getBytes("UTF-8")); + } - try { - if (addPreamble) { - os.write("\n".getBytes()); - } + os.write(Canonicalizer.getInstance( + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode) + ); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + catch (InvalidCanonicalizerException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } catch (CanonicalizationException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + } - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException ex) {} - catch (InvalidCanonicalizerException ex) { - ex.printStackTrace(); - } catch (CanonicalizationException ex) { - ex.printStackTrace(); - } - } + /** + * Serializes the contextNode into the OutputStream, but + * suppresses all Exceptions. + *
    + * NOTE: This should only be used for debugging purposes, + * NOT in a production environment; this method ignores all exceptions, + * so you won't notice if something goes wrong. If you're asking what is to + * be used in a production environment, simply use the code inside the + * try{} statement, but handle the Exceptions appropriately. + * + * @param contextNode + * @param os + */ + public static void outputDOMc14nWithComments(Node contextNode, OutputStream os) { + try { + os.write(Canonicalizer.getInstance( + Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree(contextNode) + ); + } catch (IOException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } catch (InvalidCanonicalizerException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } catch (CanonicalizationException ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + // throw new RuntimeException(ex.getMessage()); + } + } - /** - * Serializes the contextNode into the OutputStream, but - * supresses all Exceptions. - *
    - * NOTE: This should only be used for debugging purposes, - * NOT in a production environment; this method ignores all exceptions, - * so you won't notice if something goes wrong. If you're asking what is to - * be used in a production environment, simply use the code inside the - * try{} statement, but handle the Exceptions appropriately. - * - * @param contextNode - * @param os - */ - public static void outputDOMc14nWithComments(Node contextNode, - OutputStream os) { + /** + * Method getFullTextChildrenFromElement + * + * @param element + * @return the string of children + */ + public static String getFullTextChildrenFromElement(Element element) { + StringBuilder sb = new StringBuilder(); - try { - os.write( - Canonicalizer.getInstance( - Canonicalizer.ALGO_ID_C14N_WITH_COMMENTS).canonicalizeSubtree( - contextNode)); - } catch (IOException ex) { + Node child = element.getFirstChild(); + while (child != null) { + if (child.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text)child).getData()); + } + child = child.getNextSibling(); + } - // throw new RuntimeException(ex.getMessage()); - } catch (InvalidCanonicalizerException ex) { + return sb.toString(); + } - // throw new RuntimeException(ex.getMessage()); - } catch (CanonicalizationException ex) { + /** + * Creates an Element in the XML Signature specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInSignatureSpace(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - // throw new RuntimeException(ex.getMessage()); - } - } + if ((dsPrefix == null) || (dsPrefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpecNS, elementName); + } + return doc.createElementNS(Constants.SignatureSpecNS, dsPrefix + ":" + elementName); + } + /** + * Creates an Element in the XML Signature 1.1 specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInSignature11Space(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - /** - * Method getFullTextChildrenFromElement - * - * @param element - * @return the string of chi;ds - */ - public static String getFullTextChildrenFromElement(Element element) { + if ((ds11Prefix == null) || (ds11Prefix.length() == 0)) { + return doc.createElementNS(Constants.SignatureSpec11NS, elementName); + } + return doc.createElementNS(Constants.SignatureSpec11NS, ds11Prefix + ":" + elementName); + } - StringBuffer sb = new StringBuffer(); - NodeList children = element.getChildNodes(); - int iMax = children.getLength(); + /** + * Creates an Element in the XML Encryption specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInEncryptionSpace(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - for (int i = 0; i < iMax; i++) { - Node curr = children.item(i); + if ((xencPrefix == null) || (xencPrefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpecNS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpecNS, xencPrefix + ":" + elementName + ); + } - if (curr.getNodeType() == Node.TEXT_NODE) { - sb.append(((Text) curr).getData()); - } - } + /** + * Creates an Element in the XML Encryption 1.1 specification namespace. + * + * @param doc the factory Document + * @param elementName the local name of the Element + * @return the Element + */ + public static Element createElementInEncryption11Space(Document doc, String elementName) { + if (doc == null) { + throw new RuntimeException("Document is null"); + } - return sb.toString(); - } - - static Map namePrefixes=new HashMap(); - - /** - * Creates an Element in the XML Signature specification namespace. - * - * @param doc the factory Document - * @param elementName the local name of the Element - * @return the Element - */ - public static Element createElementInSignatureSpace(Document doc, - String elementName) { - - if (doc == null) { - throw new RuntimeException("Document is null"); - } - - if ((dsPrefix == null) || (dsPrefix.length() == 0)) { - return doc.createElementNS(Constants.SignatureSpecNS, elementName); - } - String namePrefix= namePrefixes.get(elementName); - if (namePrefix==null) { - StringBuffer tag=new StringBuffer(dsPrefix); - tag.append(':'); - tag.append(elementName); - namePrefix=tag.toString(); - namePrefixes.put(elementName,namePrefix); - } - return doc.createElementNS(Constants.SignatureSpecNS, namePrefix); - } + if ((xenc11Prefix == null) || (xenc11Prefix.length() == 0)) { + return doc.createElementNS(EncryptionConstants.EncryptionSpec11NS, elementName); + } + return + doc.createElementNS( + EncryptionConstants.EncryptionSpec11NS, xenc11Prefix + ":" + elementName + ); + } /** * Returns true if the element is in XML Signature namespace and the local @@ -290,10 +358,11 @@ public class XMLUtils { * * @param element * @param localName - * @return true if the element is in XML Signature namespace and the local name equals the supplied one + * @return true if the element is in XML Signature namespace and the local name equals + * the supplied one */ public static boolean elementIsInSignatureSpace(Element element, String localName) { - if (element == null) { + if (element == null){ return false; } @@ -301,48 +370,82 @@ public class XMLUtils { && element.getLocalName().equals(localName); } + /** + * Returns true if the element is in XML Signature 1.1 namespace and the local + * name equals the supplied one. + * + * @param element + * @param localName + * @return true if the element is in XML Signature namespace and the local name equals + * the supplied one + */ + public static boolean elementIsInSignature11Space(Element element, String localName) { + if (element == null) { + return false; + } + + return Constants.SignatureSpec11NS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } + /** * Returns true if the element is in XML Encryption namespace and the local * name equals the supplied one. * * @param element * @param localName - * @return true if the element is in XML Encryption namespace and the local name equals the supplied one + * @return true if the element is in XML Encryption namespace and the local name + * equals the supplied one */ public static boolean elementIsInEncryptionSpace(Element element, String localName) { - if (element == null) { + if (element == null){ return false; } return EncryptionConstants.EncryptionSpecNS.equals(element.getNamespaceURI()) && element.getLocalName().equals(localName); } - /** - * This method returns the owner document of a particular node. - * This method is necessary because it always returns a - * {@link Document}. {@link Node#getOwnerDocument} returns null - * if the {@link Node} is a {@link Document}. - * - * @param node - * @return the owner document of the node - */ - public static Document getOwnerDocument(Node node) { + /** + * Returns true if the element is in XML Encryption 1.1 namespace and the local + * name equals the supplied one. + * + * @param element + * @param localName + * @return true if the element is in XML Encryption 1.1 namespace and the local name + * equals the supplied one + */ + public static boolean elementIsInEncryption11Space(Element element, String localName) { + if (element == null){ + return false; + } + return EncryptionConstants.EncryptionSpec11NS.equals(element.getNamespaceURI()) + && element.getLocalName().equals(localName); + } - if (node.getNodeType() == Node.DOCUMENT_NODE) { - return (Document) node; - } - try { + /** + * This method returns the owner document of a particular node. + * This method is necessary because it always returns a + * {@link Document}. {@link Node#getOwnerDocument} returns null + * if the {@link Node} is a {@link Document}. + * + * @param node + * @return the owner document of the node + */ + public static Document getOwnerDocument(Node node) { + if (node.getNodeType() == Node.DOCUMENT_NODE) { + return (Document) node; + } + try { return node.getOwnerDocument(); - } catch (NullPointerException npe) { + } catch (NullPointerException npe) { throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + npe.getMessage() + "\""); - } - - } + } + } /** - * This method returns the first non-null owner document of the Node's in this Set. + * This method returns the first non-null owner document of the Nodes in this Set. * This method is necessary because it always returns a * {@link Document}. {@link Node#getOwnerDocument} returns null * if the {@link Node} is a {@link Document}. @@ -351,23 +454,23 @@ public class XMLUtils { * @return the owner document */ public static Document getOwnerDocument(Set xpathNodeSet) { - NullPointerException npe = null; - for (Node node : xpathNodeSet) { - int nodeType =node.getNodeType(); - if (nodeType == Node.DOCUMENT_NODE) { - return (Document) node; - } - try { - if (nodeType==Node.ATTRIBUTE_NODE) { + NullPointerException npe = null; + for (Node node : xpathNodeSet) { + int nodeType = node.getNodeType(); + if (nodeType == Node.DOCUMENT_NODE) { + return (Document) node; + } + try { + if (nodeType == Node.ATTRIBUTE_NODE) { return ((Attr)node).getOwnerElement().getOwnerDocument(); - } - return node.getOwnerDocument(); - } catch (NullPointerException e) { - npe = e; - } + } + return node.getOwnerDocument(); + } catch (NullPointerException e) { + npe = e; + } + } - } - throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + throw new NullPointerException(I18n.translate("endorsed.jdk1.4.0") + " Original message was \"" + (npe == null ? "" : npe.getMessage()) + "\""); } @@ -380,165 +483,161 @@ public class XMLUtils { * @param namespace * @return the element. */ - public static Element createDSctx(Document doc, String prefix, - String namespace) { + public static Element createDSctx(Document doc, String prefix, String namespace) { + if ((prefix == null) || (prefix.trim().length() == 0)) { + throw new IllegalArgumentException("You must supply a prefix"); + } - if ((prefix == null) || (prefix.trim().length() == 0)) { - throw new IllegalArgumentException("You must supply a prefix"); - } + Element ctx = doc.createElementNS(null, "namespaceContext"); - Element ctx = doc.createElementNS(null, "namespaceContext"); + ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), namespace); - ctx.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix.trim(), - namespace); - - return ctx; + return ctx; } - /** - * Method addReturnToElement - * - * @param e - */ - public static void addReturnToElement(Element e) { + /** + * Method addReturnToElement + * + * @param e + */ + public static void addReturnToElement(Element e) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.appendChild(doc.createTextNode("\n")); + } + } - if (!ignoreLineBreaks) { - Document doc = e.getOwnerDocument(); - e.appendChild(doc.createTextNode("\n")); - } - } + public static void addReturnToElement(Document doc, HelperNodeList nl) { + if (!ignoreLineBreaks) { + nl.appendChild(doc.createTextNode("\n")); + } + } - public static void addReturnToElement(Document doc, HelperNodeList nl) { - if (!ignoreLineBreaks) { - nl.appendChild(doc.createTextNode("\n")); - } - } + public static void addReturnBeforeChild(Element e, Node child) { + if (!ignoreLineBreaks) { + Document doc = e.getOwnerDocument(); + e.insertBefore(doc.createTextNode("\n"), child); + } + } - public static void addReturnBeforeChild(Element e, Node child) { - if (!ignoreLineBreaks) { - Document doc = e.getOwnerDocument(); - e.insertBefore(doc.createTextNode("\n"), child); - } - } + /** + * Method convertNodelistToSet + * + * @param xpathNodeSet + * @return the set with the nodelist + */ + public static Set convertNodelistToSet(NodeList xpathNodeSet) { + if (xpathNodeSet == null) { + return new HashSet(); + } - /** - * Method convertNodelistToSet - * - * @param xpathNodeSet - * @return the set with the nodelist - */ - public static Set convertNodelistToSet(NodeList xpathNodeSet) { + int length = xpathNodeSet.getLength(); + Set set = new HashSet(length); - if (xpathNodeSet == null) { - return new HashSet(); - } + for (int i = 0; i < length; i++) { + set.add(xpathNodeSet.item(i)); + } - int length = xpathNodeSet.getLength(); - Set set = new HashSet(length); + return set; + } - for (int i = 0; i < length; i++) { - set.add(xpathNodeSet.item(i)); - } + /** + * This method spreads all namespace attributes in a DOM document to their + * children. This is needed because the XML Signature XPath transform + * must evaluate the XPath against all nodes in the input, even against + * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are + * not fully visible in the Xalan XPath model, so we have to do this by + * hand in DOM spaces so that the nodes become visible in XPath space. + * + * @param doc + * @see + * Namespace axis resolution is not XPath compliant + */ + public static void circumventBug2650(Document doc) { - return set; - } + Element documentElement = doc.getDocumentElement(); + // if the document element has no xmlns definition, we add xmlns="" + Attr xmlnsAttr = + documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); - /** - * This method spreads all namespace attributes in a DOM document to their - * children. This is needed because the XML Signature XPath transform - * must evaluate the XPath against all nodes in the input, even against - * XPath namespace nodes. Through a bug in XalanJ2, the namespace nodes are - * not fully visible in the Xalan XPath model, so we have to do this by - * hand in DOM spaces so that the nodes become visible in XPath space. - * - * @param doc - * @see Namespace axis resolution is not XPath compliant - */ - public static void circumventBug2650(Document doc) { + if (xmlnsAttr == null) { + documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); + } - Element documentElement = doc.getDocumentElement(); + XMLUtils.circumventBug2650internal(doc); + } - // if the document element has no xmlns definition, we add xmlns="" - Attr xmlnsAttr = - documentElement.getAttributeNodeNS(Constants.NamespaceSpecNS, "xmlns"); - - if (xmlnsAttr == null) { - documentElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", ""); - } - - XMLUtils.circumventBug2650internal(doc); - } - - /** - * This is the work horse for {@link #circumventBug2650}. - * - * @param node - * @see Namespace axis resolution is not XPath compliant - */ - @SuppressWarnings("fallthrough") - private static void circumventBug2650internal(Node node) { - Node parent=null; - Node sibling=null; - final String namespaceNs=Constants.NamespaceSpecNS; - do { - switch (node.getNodeType()) { - case Node.ELEMENT_NODE : - Element element = (Element) node; - if (!element.hasChildNodes()) - break; - if (element.hasAttributes()) { - NamedNodeMap attributes = element.getAttributes(); - int attributesLength = attributes.getLength(); - - for (Node child = element.getFirstChild(); child!=null; - child=child.getNextSibling()) { - - if (child.getNodeType() != Node.ELEMENT_NODE) { - continue; + /** + * This is the work horse for {@link #circumventBug2650}. + * + * @param node + * @see + * Namespace axis resolution is not XPath compliant + */ + @SuppressWarnings("fallthrough") + private static void circumventBug2650internal(Node node) { + Node parent = null; + Node sibling = null; + final String namespaceNs = Constants.NamespaceSpecNS; + do { + switch (node.getNodeType()) { + case Node.ELEMENT_NODE : + Element element = (Element) node; + if (!element.hasChildNodes()) { + break; } - Element childElement = (Element) child; + if (element.hasAttributes()) { + NamedNodeMap attributes = element.getAttributes(); + int attributesLength = attributes.getLength(); - for (int i = 0; i < attributesLength; i++) { - Attr currentAttr = (Attr) attributes.item(i); - if (namespaceNs!=currentAttr.getNamespaceURI()) - continue; - if (childElement.hasAttributeNS(namespaceNs, - currentAttr.getLocalName())) { - continue; + for (Node child = element.getFirstChild(); child!=null; + child = child.getNextSibling()) { + + if (child.getNodeType() != Node.ELEMENT_NODE) { + continue; } - childElement.setAttributeNS(namespaceNs, - currentAttr.getName(), - currentAttr.getNodeValue()); - + Element childElement = (Element) child; + for (int i = 0; i < attributesLength; i++) { + Attr currentAttr = (Attr) attributes.item(i); + if (!namespaceNs.equals(currentAttr.getNamespaceURI())) { + continue; + } + if (childElement.hasAttributeNS(namespaceNs, + currentAttr.getLocalName())) { + continue; + } + childElement.setAttributeNS(namespaceNs, + currentAttr.getName(), + currentAttr.getNodeValue()); + } + } } - } - } - case Node.ENTITY_REFERENCE_NODE : - case Node.DOCUMENT_NODE : - parent=node; - sibling=node.getFirstChild(); - break; - } - while ((sibling==null) && (parent!=null)) { - sibling=parent.getNextSibling(); - parent=parent.getParentNode(); - }; - if (sibling==null) { - return; - } + case Node.ENTITY_REFERENCE_NODE : + case Node.DOCUMENT_NODE : + parent = node; + sibling = node.getFirstChild(); + break; + } + while ((sibling == null) && (parent != null)) { + sibling = parent.getNextSibling(); + parent = parent.getParentNode(); + } + if (sibling == null) { + return; + } - node=sibling; - sibling=node.getNextSibling(); - } while (true); - } + node = sibling; + sibling = node.getNextSibling(); + } while (true); + } /** * @param sibling * @param nodeName * @param number - * @return nodes with the constrain + * @return nodes with the constraint */ public static Element selectDsNode(Node sibling, String nodeName, int number) { while (sibling != null) { @@ -554,6 +653,26 @@ public class XMLUtils { return null; } + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constraint + */ + public static Element selectDs11Node(Node sibling, String nodeName, int number) { + while (sibling != null) { + if (Constants.SignatureSpec11NS.equals(sibling.getNamespaceURI()) + && sibling.getLocalName().equals(nodeName)) { + if (number == 0){ + return (Element)sibling; + } + number--; + } + sibling = sibling.getNextSibling(); + } + return null; + } + /** * @param sibling * @param nodeName @@ -574,42 +693,61 @@ public class XMLUtils { return null; } - /** - * @param sibling - * @param nodeName - * @param number - * @return nodes with the constrain - */ - public static Text selectDsNodeText(Node sibling, String nodeName, int number) { - Node n=selectDsNode(sibling,nodeName,number); - if (n==null) { - return null; + + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectDsNodeText(Node sibling, String nodeName, int number) { + Node n = selectDsNode(sibling,nodeName,number); + if (n == null) { + return null; } - n=n.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.TEXT_NODE) { - n=n.getNextSibling(); + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); } return (Text)n; - } + } - /** - * @param sibling - * @param uri - * @param nodeName - * @param number - * @return nodes with the constrain - */ - public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) { - Node n=selectNode(sibling,uri,nodeName,number); - if (n==null) { - return null; + /** + * @param sibling + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectDs11NodeText(Node sibling, String nodeName, int number) { + Node n = selectDs11Node(sibling,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); + } + return (Text)n; } - n=n.getFirstChild(); - while (n!=null && n.getNodeType()!=Node.TEXT_NODE) { - n=n.getNextSibling(); + + /** + * @param sibling + * @param uri + * @param nodeName + * @param number + * @return nodes with the constrain + */ + public static Text selectNodeText(Node sibling, String uri, String nodeName, int number) { + Node n = selectNode(sibling,uri,nodeName,number); + if (n == null) { + return null; + } + n = n.getFirstChild(); + while (n != null && n.getNodeType() != Node.TEXT_NODE) { + n = n.getNextSibling(); + } + return (Text)n; } - return (Text)n; - } /** * @param sibling @@ -638,16 +776,25 @@ public class XMLUtils { * @return nodes with the constrain */ public static Element[] selectDsNodes(Node sibling, String nodeName) { - return selectNodes(sibling,Constants.SignatureSpecNS, nodeName); + return selectNodes(sibling, Constants.SignatureSpecNS, nodeName); + } + + /** + * @param sibling + * @param nodeName + * @return nodes with the constrain + */ + public static Element[] selectDs11Nodes(Node sibling, String nodeName) { + return selectNodes(sibling, Constants.SignatureSpec11NS, nodeName); } /** * @param sibling * @param uri * @param nodeName - * @return nodes with the constrain + * @return nodes with the constraint */ - public static Element[] selectNodes(Node sibling, String uri, String nodeName) { + public static Element[] selectNodes(Node sibling, String uri, String nodeName) { List list = new ArrayList(); while (sibling != null) { if (sibling.getNamespaceURI() != null && sibling.getNamespaceURI().equals(uri) @@ -659,73 +806,117 @@ public class XMLUtils { return list.toArray(new Element[list.size()]); } - /** - * @param signatureElement - * @param inputSet - * @return nodes with the constrain - */ + /** + * @param signatureElement + * @param inputSet + * @return nodes with the constrain + */ public static Set excludeNodeFromSet(Node signatureElement, Set inputSet) { - Set resultSet = new HashSet(); - Iterator iterator = inputSet.iterator(); + Set resultSet = new HashSet(); + Iterator iterator = inputSet.iterator(); - while (iterator.hasNext()) { + while (iterator.hasNext()) { Node inputNode = iterator.next(); - if (!XMLUtils - .isDescendantOrSelf(signatureElement, inputNode)) { - resultSet.add(inputNode); + if (!XMLUtils.isDescendantOrSelf(signatureElement, inputNode)) { + resultSet.add(inputNode); } - } - return resultSet; - } + } + return resultSet; + } - /** - * Returns true if the descendantOrSelf is on the descendant-or-self axis - * of the context node. - * - * @param ctx - * @param descendantOrSelf - * @return true if the node is descendant - */ - static public boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) { + /** + * Method getStrFromNode + * + * @param xpathnode + * @return the string for the node. + */ + public static String getStrFromNode(Node xpathnode) { + if (xpathnode.getNodeType() == Node.TEXT_NODE) { + // we iterate over all siblings of the context node because eventually, + // the text is "polluted" with pi's or comments + StringBuilder sb = new StringBuilder(); - if (ctx == descendantOrSelf) { - return true; - } + for (Node currentSibling = xpathnode.getParentNode().getFirstChild(); + currentSibling != null; + currentSibling = currentSibling.getNextSibling()) { + if (currentSibling.getNodeType() == Node.TEXT_NODE) { + sb.append(((Text) currentSibling).getData()); + } + } - Node parent = descendantOrSelf; + return sb.toString(); + } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { + return ((Attr) xpathnode).getNodeValue(); + } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { + return ((ProcessingInstruction) xpathnode).getNodeValue(); + } - while (true) { - if (parent == null) { - return false; - } + return null; + } - if (parent == ctx) { + /** + * Returns true if the descendantOrSelf is on the descendant-or-self axis + * of the context node. + * + * @param ctx + * @param descendantOrSelf + * @return true if the node is descendant + */ + public static boolean isDescendantOrSelf(Node ctx, Node descendantOrSelf) { + if (ctx == descendantOrSelf) { return true; - } + } - if (parent.getNodeType() == Node.ATTRIBUTE_NODE) { - parent = ((Attr) parent).getOwnerElement(); - } else { - parent = parent.getParentNode(); - } - } - } + Node parent = descendantOrSelf; + + while (true) { + if (parent == null) { + return false; + } + + if (parent == ctx) { + return true; + } + + if (parent.getNodeType() == Node.ATTRIBUTE_NODE) { + parent = ((Attr) parent).getOwnerElement(); + } else { + parent = parent.getParentNode(); + } + } + } public static boolean ignoreLineBreaks() { return ignoreLineBreaks; } /** - * This method is a tree-search to help prevent against wrapping attacks. - * It checks that no two Elements have ID Attributes that match the "value" - * argument, if this is the case then "false" is returned. Note that a - * return value of "true" does not necessarily mean that a matching Element - * has been found, just that no wrapping attack has been detected. + * Returns the attribute value for the attribute with the specified name. + * Returns null if there is no such attribute, or + * the empty string if the attribute value is empty. + * + *

    This works around a limitation of the DOM + * Element.getAttributeNode method, which does not distinguish + * between an unspecified attribute and an attribute with a value of + * "" (it returns "" for both cases). + * + * @param elem the element containing the attribute + * @param name the name of the attribute + * @return the attribute value (may be null if unspecified) */ - public static boolean protectAgainstWrappingAttack(Node startNode, - String value) - { + public static String getAttributeValue(Element elem, String name) { + Attr attr = elem.getAttributeNodeNS(null, name); + return (attr == null) ? null : attr.getValue(); + } + + /** + * This method is a tree-search to help prevent against wrapping attacks. It checks that no + * two Elements have ID Attributes that match the "value" argument, if this is the case then + * "false" is returned. Note that a return value of "true" does not necessarily mean that + * a matching Element has been found, just that no wrapping attack has been detected. + */ + public static boolean protectAgainstWrappingAttack(Node startNode, String value) { Node startParent = startNode.getParentNode(); Node processedNode = null; Element foundElement = null; @@ -780,15 +971,13 @@ public class XMLUtils { } /** - * This method is a tree-search to help prevent against wrapping attacks. - * It checks that no other Element than the given "knownElement" argument - * has an ID attribute that matches the "value" argument, which is the ID - * value of "knownElement". If this is the case then "false" is returned. + * This method is a tree-search to help prevent against wrapping attacks. It checks that no other + * Element than the given "knownElement" argument has an ID attribute that matches the "value" + * argument, which is the ID value of "knownElement". If this is the case then "false" is returned. */ - public static boolean protectAgainstWrappingAttack(Node startNode, - Element knownElement, - String value) - { + public static boolean protectAgainstWrappingAttack( + Node startNode, Element knownElement, String value + ) { Node startParent = startNode.getParentNode(); Node processedNode = null; @@ -805,9 +994,7 @@ public class XMLUtils { if (attributes != null) { for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr)attributes.item(i); - if (attr.isId() && id.equals(attr.getValue()) - && se != knownElement) - { + if (attr.isId() && id.equals(attr.getValue()) && se != knownElement) { log.log(java.util.logging.Level.FINE, "Multiple elements with the same 'Id' attribute value!"); return false; } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java new file mode 100644 index 00000000000..d5b55bac3f8 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathAPI.java @@ -0,0 +1,66 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import javax.xml.transform.TransformerException; + +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An interface to abstract XPath evaluation + */ +public interface XPathAPI { + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException; + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException; + + /** + * Clear any context information from this object + */ + void clear(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java new file mode 100644 index 00000000000..3de6129b935 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFactory.java @@ -0,0 +1,71 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return an XPathAPI instance. If Xalan is available it returns XalanXPathAPI. If not, then + * it returns JDKXPathAPI. + */ +public abstract class XPathFactory { + + private static boolean xalanInstalled; + + static { + try { + Class funcTableClass = + ClassLoaderUtils.loadClass("com.sun.org.apache.xpath.internal.compiler.FunctionTable", XPathFactory.class); + if (funcTableClass != null) { + xalanInstalled = true; + } + } catch (Exception e) { + //ignore + } + } + + protected synchronized static boolean isXalanInstalled() { + return xalanInstalled; + } + + /** + * Get a new XPathFactory instance + */ + public static XPathFactory newInstance() { + if (!isXalanInstalled()) { + return new JDKXPathFactory(); + } + // Xalan is available + if (XalanXPathAPI.isInstalled()) { + return new XalanXPathFactory(); + } + // Some problem was encountered in fixing up the Xalan FunctionTable so fall back to the + // JDK implementation + return new JDKXPathFactory(); + } + + /** + * Get a new XPathAPI instance + */ + public abstract XPathAPI newXPathAPI(); + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java deleted file mode 100644 index dbee521c11e..00000000000 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XPathFuncHereAPI.java +++ /dev/null @@ -1,306 +0,0 @@ -/* - * reserved comment block - * DO NOT REMOVE OR ALTER! - */ -/* - * Copyright 1999-2004 The Apache Software Foundation. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * - */ -package com.sun.org.apache.xml.internal.security.utils; - - - -import javax.xml.transform.TransformerException; - -import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHereContext; -import com.sun.org.apache.xml.internal.utils.PrefixResolver; -import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; -import com.sun.org.apache.xpath.internal.XPath; -import com.sun.org.apache.xpath.internal.objects.XObject; -import org.w3c.dom.Attr; -import org.w3c.dom.Document; -import org.w3c.dom.Node; -import org.w3c.dom.NodeList; -import org.w3c.dom.ProcessingInstruction; -import org.w3c.dom.Text; -import org.w3c.dom.traversal.NodeIterator; - - - - -/** - * This class does the same as {@link com.sun.org.apache.xpath.internal.XPathAPI} except that the XPath strings - * are not supplied as Strings but as {@link Text}, {@link Attr}ibute or - * {ProcessingInstruction} nodes which contain the XPath string. This enables - * us to use the here() function. - *
    - * The methods in this class are convenience methods into the low-level XPath API. - * These functions tend to be a little slow, since a number of objects must be - * created for each evaluation. A faster way is to precompile the - * XPaths using the low-level API, and then just use the XPaths - * over and over. - * - * @author $Author: mullan $ - * @see XPath Specification - */ -public class XPathFuncHereAPI { - - /** - * Use an XPath string to select a single node. XPath namespace - * prefixes are resolved from the context node, which may not - * be what you want (see the next method). - * - * @param contextNode The node to start searching from. - * @param xpathnode A Node containing a valid XPath string. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public static Node selectSingleNode(Node contextNode, Node xpathnode) - throws TransformerException { - return selectSingleNode(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a single node. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return The first node found that matches the XPath, or null. - * - * @throws TransformerException - */ - public static Node selectSingleNode( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Have the XObject return its result as a NodeSetDTM. - NodeIterator nl = selectNodeIterator(contextNode, xpathnode, - namespaceNode); - - // Return the first node, or null - return nl.nextNode(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode) throws TransformerException { - return selectNodeIterator(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeIterator selectNodeIterator( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, namespaceNode); - - // Have the XObject return its result as a NodeSetDTM. - return list.nodeset(); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the contextNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeList selectNodeList(Node contextNode, Node xpathnode) - throws TransformerException { - return selectNodeList(contextNode, xpathnode, contextNode); - } - - /** - * Use an XPath string to select a nodelist. - * XPath namespace prefixes are resolved from the namespaceNode. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return A NodeIterator, should never be null. - * - * @throws TransformerException - */ - public static NodeList selectNodeList( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Execute the XPath, and have it return the result - XObject list = eval(contextNode, xpathnode, namespaceNode); - - // Return a NodeList. - return list.nodelist(); - } - - /** - * Evaluate XPath string to an XObject. Using this method, - * XPath namespace prefixes will be resolved from the namespaceNode. - * @param contextNode The node to start searching from. - * @param xpathnode - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval(Node contextNode, Node xpathnode) - throws TransformerException { - return eval(contextNode, xpathnode, contextNode); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval( - Node contextNode, Node xpathnode, Node namespaceNode) - throws TransformerException { - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - FuncHereContext xpathSupport = new FuncHereContext(xpathnode); - - // Create an object to resolve namespace prefixes. - // XPath namespaces are resolved from the input context node's document element - // if it is a root node, or else the current context node (for lack of a better - // resolution space, given the simplicity of this sample code). - PrefixResolverDefault prefixResolver = - new PrefixResolverDefault((namespaceNode.getNodeType() - == Node.DOCUMENT_NODE) - ? ((Document) namespaceNode) - .getDocumentElement() - : namespaceNode); - String str = getStrFromNode(xpathnode); - - // Create the XPath object. - XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - - // Execute the XPath, and have it return the result - // return xpath.execute(xpathSupport, contextNode, prefixResolver); - int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); - - return xpath.execute(xpathSupport, ctxtNode, prefixResolver); - } - - /** - * Evaluate XPath string to an XObject. - * XPath namespace prefixes are resolved from the namespaceNode. - * The implementation of this is a little slow, since it creates - * a number of objects each time it is called. This could be optimized - * to keep the same objects around, but then thread-safety issues would arise. - * - * @param contextNode The node to start searching from. - * @param xpathnode - * @param prefixResolver Will be called if the parser encounters namespace - * prefixes, to resolve the prefixes to URLs. - * @return An XObject, which can be used to obtain a string, number, nodelist, etc, should never be null. - * @see com.sun.org.apache.xpath.internal.objects.XObject - * @see com.sun.org.apache.xpath.internal.objects.XNull - * @see com.sun.org.apache.xpath.internal.objects.XBoolean - * @see com.sun.org.apache.xpath.internal.objects.XNumber - * @see com.sun.org.apache.xpath.internal.objects.XString - * @see com.sun.org.apache.xpath.internal.objects.XRTreeFrag - * - * @throws TransformerException - */ - public static XObject eval( - Node contextNode, Node xpathnode, PrefixResolver prefixResolver) - throws TransformerException { - - String str = getStrFromNode(xpathnode); - - // Since we don't have a XML Parser involved here, install some default support - // for things like namespaces, etc. - // (Changed from: XPathContext xpathSupport = new XPathContext(); - // because XPathContext is weak in a number of areas... perhaps - // XPathContext should be done away with.) - // Create the XPath object. - XPath xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); - - // Execute the XPath, and have it return the result - FuncHereContext xpathSupport = new FuncHereContext(xpathnode); - int ctxtNode = xpathSupport.getDTMHandleFromNode(contextNode); - - return xpath.execute(xpathSupport, ctxtNode, prefixResolver); - } - - /** - * Method getStrFromNode - * - * @param xpathnode - * @return the string from the node - */ - private static String getStrFromNode(Node xpathnode) { - - if (xpathnode.getNodeType() == Node.TEXT_NODE) { - return ((Text) xpathnode).getData(); - } else if (xpathnode.getNodeType() == Node.ATTRIBUTE_NODE) { - return ((Attr) xpathnode).getNodeValue(); - } else if (xpathnode.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { - return ((ProcessingInstruction) xpathnode).getNodeValue(); - } - - return ""; - } -} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java new file mode 100644 index 00000000000..f9fab3033d8 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathAPI.java @@ -0,0 +1,210 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + +import java.lang.reflect.Constructor; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; + +import javax.xml.transform.ErrorListener; +import javax.xml.transform.SourceLocator; +import javax.xml.transform.TransformerException; + +import com.sun.org.apache.xml.internal.security.transforms.implementations.FuncHere; +import com.sun.org.apache.xml.internal.utils.PrefixResolver; +import com.sun.org.apache.xml.internal.utils.PrefixResolverDefault; +import com.sun.org.apache.xpath.internal.Expression; +import com.sun.org.apache.xpath.internal.XPath; +import com.sun.org.apache.xpath.internal.XPathContext; +import com.sun.org.apache.xpath.internal.compiler.FunctionTable; +import com.sun.org.apache.xpath.internal.objects.XObject; +import org.w3c.dom.Document; +import org.w3c.dom.Node; +import org.w3c.dom.NodeList; + +/** + * An implementation of XPathAPI using Xalan. This supports the "here()" function defined in the digital + * signature spec. + */ +public class XalanXPathAPI implements XPathAPI { + + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(XalanXPathAPI.class.getName()); + + private String xpathStr = null; + + private XPath xpath = null; + + private static FunctionTable funcTable = null; + + private static boolean installed; + + private XPathContext context; + + static { + fixupFunctionTable(); + } + + + /** + * Use an XPath string to select a nodelist. + * XPath namespace prefixes are resolved from the namespaceNode. + * + * @param contextNode The node to start searching from. + * @param xpathnode + * @param str + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + * @return A NodeIterator, should never be null. + * + * @throws TransformerException + */ + public NodeList selectNodeList( + Node contextNode, Node xpathnode, String str, Node namespaceNode + ) throws TransformerException { + + // Execute the XPath, and have it return the result + XObject list = eval(contextNode, xpathnode, str, namespaceNode); + + // Return a NodeList. + return list.nodelist(); + } + + /** + * Evaluate an XPath string and return true if the output is to be included or not. + * @param contextNode The node to start searching from. + * @param xpathnode The XPath node + * @param str The XPath expression + * @param namespaceNode The node from which prefixes in the XPath will be resolved to namespaces. + */ + public boolean evaluate(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + XObject object = eval(contextNode, xpathnode, str, namespaceNode); + return object.bool(); + } + + /** + * Clear any context information from this object + */ + public void clear() { + xpathStr = null; + xpath = null; + context = null; + } + + public synchronized static boolean isInstalled() { + return installed; + } + + private XObject eval(Node contextNode, Node xpathnode, String str, Node namespaceNode) + throws TransformerException { + if (context == null) { + context = new XPathContext(xpathnode); + context.setSecureProcessing(true); + } + + // Create an object to resolve namespace prefixes. + // XPath namespaces are resolved from the input context node's document element + // if it is a root node, or else the current context node (for lack of a better + // resolution space, given the simplicity of this sample code). + Node resolverNode = + (namespaceNode.getNodeType() == Node.DOCUMENT_NODE) + ? ((Document) namespaceNode).getDocumentElement() : namespaceNode; + PrefixResolverDefault prefixResolver = new PrefixResolverDefault(resolverNode); + + if (!str.equals(xpathStr)) { + if (str.indexOf("here()") > 0) { + context.reset(); + } + xpath = createXPath(str, prefixResolver); + xpathStr = str; + } + + // Execute the XPath, and have it return the result + int ctxtNode = context.getDTMHandleFromNode(contextNode); + + return xpath.execute(context, ctxtNode, prefixResolver); + } + + private XPath createXPath(String str, PrefixResolver prefixResolver) throws TransformerException { + XPath xpath = null; + Class[] classes = new Class[]{String.class, SourceLocator.class, PrefixResolver.class, int.class, + ErrorListener.class, FunctionTable.class}; + Object[] objects = + new Object[]{str, null, prefixResolver, Integer.valueOf(XPath.SELECT), null, funcTable}; + try { + Constructor constructor = XPath.class.getConstructor(classes); + xpath = (XPath) constructor.newInstance(objects); + } catch (Exception ex) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, ex.getMessage(), ex); + } + } + if (xpath == null) { + xpath = new XPath(str, null, prefixResolver, XPath.SELECT, null); + } + return xpath; + } + + private synchronized static void fixupFunctionTable() { + installed = false; + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Registering Here function"); + } + /** + * Try to register our here() implementation as internal function. + */ + try { + Class[] args = {String.class, Expression.class}; + Method installFunction = FunctionTable.class.getMethod("installFunction", args); + if ((installFunction.getModifiers() & Modifier.STATIC) != 0) { + Object[] params = {"here", new FuncHere()}; + installFunction.invoke(null, params); + installed = true; + } + } catch (Exception ex) { + log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex); + } + if (!installed) { + try { + funcTable = new FunctionTable(); + Class[] args = {String.class, Class.class}; + Method installFunction = FunctionTable.class.getMethod("installFunction", args); + Object[] params = {"here", FuncHere.class}; + installFunction.invoke(funcTable, params); + installed = true; + } catch (Exception ex) { + log.log(java.util.logging.Level.FINE, "Error installing function using the static installFunction method", ex); + } + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + if (installed) { + log.log(java.util.logging.Level.FINE, "Registered class " + FuncHere.class.getName() + + " for XPath function 'here()' function in internal table"); + } else { + log.log(java.util.logging.Level.FINE, "Unable to register class " + FuncHere.class.getName() + + " for XPath function 'here()' function in internal table"); + } + } + } + +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java new file mode 100644 index 00000000000..e6ee959d750 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/XalanXPathFactory.java @@ -0,0 +1,37 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils; + + +/** + * A Factory to return a XalanXPathAPI instance. + */ +public class XalanXPathFactory extends XPathFactory { + + /** + * Get a new XPathAPI instance + */ + public XPathAPI newXPathAPI() { + return new XalanXPathAPI(); + } +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java index 67d635cb847..7570a019064 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolver.java @@ -85,8 +85,14 @@ public class ResourceResolver { * @throws ResourceResolverException */ public static final ResourceResolver getInstance( - Attr uri, String baseURI, boolean secureValidation + Attr uriAttr, String baseURI, boolean secureValidation ) throws ResourceResolverException { + ResourceResolverContext context = new ResourceResolverContext(uriAttr, baseURI, secureValidation); + return internalGetInstance(context); + } + + private static ResourceResolver internalGetInstance(ResourceResolverContext context) + throws ResourceResolverException { synchronized (resolverList) { for (ResourceResolver resolver : resolverList) { ResourceResolver resolverTmp = resolver; @@ -95,9 +101,9 @@ public class ResourceResolver { resolverTmp = new ResourceResolver(resolver.resolverSpi.getClass().newInstance()); } catch (InstantiationException e) { - throw new ResourceResolverException("", e, uri, baseURI); + throw new ResourceResolverException("", e, context.attr, context.baseUri); } catch (IllegalAccessException e) { - throw new ResourceResolverException("", e, uri, baseURI); + throw new ResourceResolverException("", e, context.attr, context.baseUri); } } @@ -107,15 +113,14 @@ public class ResourceResolver { ); } - resolverTmp.resolverSpi.secureValidation = secureValidation; - if ((resolverTmp != null) && resolverTmp.canResolve(uri, baseURI)) { + if ((resolverTmp != null) && resolverTmp.canResolve(context)) { // Check to see whether the Resolver is allowed - if (secureValidation + if (context.secureValidation && (resolverTmp.resolverSpi instanceof ResolverLocalFilesystem || resolverTmp.resolverSpi instanceof ResolverDirectHTTP)) { Object exArgs[] = { resolverTmp.resolverSpi.getClass().getName() }; throw new ResourceResolverException( - "signature.Reference.ForbiddenResolver", exArgs, uri, baseURI + "signature.Reference.ForbiddenResolver", exArgs, context.attr, context.baseUri ); } return resolverTmp; @@ -123,9 +128,10 @@ public class ResourceResolver { } } - Object exArgs[] = { ((uri != null) ? uri.getNodeValue() : "null"), baseURI }; + Object exArgs[] = { ((context.uriToResolve != null) + ? context.uriToResolve : "null"), context.baseUri }; - throw new ResourceResolverException("utils.resolver.noClass", exArgs, uri, baseURI); + throw new ResourceResolverException("utils.resolver.noClass", exArgs, context.attr, context.baseUri); } /** @@ -165,6 +171,8 @@ public class ResourceResolver { ); } + ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation); + // first check the individual Resolvers if (individualResolvers != null) { for (int i = 0; i < individualResolvers.size(); i++) { @@ -176,15 +184,14 @@ public class ResourceResolver { log.log(java.util.logging.Level.FINE, "check resolvability by class " + currentClass); } - resolver.resolverSpi.secureValidation = secureValidation; - if (resolver.canResolve(uri, baseURI)) { + if (resolver.canResolve(context)) { return resolver; } } } } - return getInstance(uri, baseURI, secureValidation); + return internalGetInstance(context); } /** @@ -269,6 +276,15 @@ public class ResourceResolver { } } + /** + * @deprecated New clients should use {@link #resolve(Attr, String, boolean)} + */ + @Deprecated + public XMLSignatureInput resolve(Attr uri, String baseURI) + throws ResourceResolverException { + return resolve(uri, baseURI, true); + } + /** * Method resolve * @@ -278,9 +294,10 @@ public class ResourceResolver { * * @throws ResourceResolverException */ - public XMLSignatureInput resolve(Attr uri, String baseURI) + public XMLSignatureInput resolve(Attr uri, String baseURI, boolean secureValidation) throws ResourceResolverException { - return resolverSpi.engineResolve(uri, baseURI); + ResourceResolverContext context = new ResourceResolverContext(uri, baseURI, secureValidation); + return resolverSpi.engineResolveURI(context); } /** @@ -338,7 +355,7 @@ public class ResourceResolver { * @param baseURI * @return true if it can resolve the uri */ - private boolean canResolve(Attr uri, String baseURI) { - return resolverSpi.engineCanResolve(uri, baseURI); + private boolean canResolve(ResourceResolverContext context) { + return this.resolverSpi.engineCanResolveURI(context); } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java new file mode 100644 index 00000000000..5b8a9ce13f6 --- /dev/null +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverContext.java @@ -0,0 +1,43 @@ +/* + * reserved comment block + * DO NOT REMOVE OR ALTER! + */ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package com.sun.org.apache.xml.internal.security.utils.resolver; + +import org.w3c.dom.Attr; + +public class ResourceResolverContext { + + public ResourceResolverContext(Attr attr, String baseUri, boolean secureValidation) { + this.attr = attr; + this.baseUri = baseUri; + this.secureValidation = secureValidation; + this.uriToResolve = attr != null ? attr.getValue() : null; + } + + public final String uriToResolve; + + public final boolean secureValidation; + + public final String baseUri; + + public final Attr attr; +} diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java index 5fa9ea35787..cf5c8d12ea2 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverException.java @@ -2,144 +2,137 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver; - - import com.sun.org.apache.xml.internal.security.exceptions.XMLSecurityException; import org.w3c.dom.Attr; - /** * This Exception is thrown if something related to the * {@link com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolver} goes wrong. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class ResourceResolverException extends XMLSecurityException { - /** - * - */ - private static final long serialVersionUID = 1L; - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Attr uri, String BaseURI) { + private static final long serialVersionUID = 1L; - super(_msgID); + private Attr uri = null; - this._uri = uri; - this._BaseURI = BaseURI; - } + private String baseURI = null; - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param exArgs - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Object exArgs[], Attr uri, - String BaseURI) { + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Attr uri, String baseURI) { + super(msgID); - super(_msgID, exArgs); + this.uri = uri; + this.baseURI = baseURI; + } - this._uri = uri; - this._BaseURI = BaseURI; - } + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param exArgs + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Object exArgs[], Attr uri, + String baseURI) { + super(msgID, exArgs); - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Exception _originalException, - Attr uri, String BaseURI) { + this.uri = uri; + this.baseURI = baseURI; + } - super(_msgID, _originalException); + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Exception originalException, + Attr uri, String baseURI) { + super(msgID, originalException); - this._uri = uri; - this._BaseURI = BaseURI; - } + this.uri = uri; + this.baseURI = baseURI; + } - /** - * Constructor ResourceResolverException - * - * @param _msgID - * @param exArgs - * @param _originalException - * @param uri - * @param BaseURI - */ - public ResourceResolverException(String _msgID, Object exArgs[], - Exception _originalException, Attr uri, - String BaseURI) { + /** + * Constructor ResourceResolverException + * + * @param msgID + * @param exArgs + * @param originalException + * @param uri + * @param baseURI + */ + public ResourceResolverException(String msgID, Object exArgs[], + Exception originalException, Attr uri, + String baseURI) { + super(msgID, exArgs, originalException); - super(_msgID, exArgs, _originalException); + this.uri = uri; + this.baseURI = baseURI; + } - this._uri = uri; - this._BaseURI = BaseURI; - } + /** + * + * @param uri + */ + public void setURI(Attr uri) { + this.uri = uri; + } - //J- - Attr _uri = null; - /** - * - * @param uri - */ - public void setURI(Attr uri) { - this._uri = uri; - } + /** + * + * @return the uri + */ + public Attr getURI() { + return this.uri; + } - /** - * - * @return the uri - */ - public Attr getURI() { - return this._uri; - } + /** + * + * @param baseURI + */ + public void setbaseURI(String baseURI) { + this.baseURI = baseURI; + } - String _BaseURI; + /** + * + * @return the baseURI + */ + public String getbaseURI() { + return this.baseURI; + } - /** - * - * @param BaseURI - */ - public void setBaseURI(String BaseURI) { - this._BaseURI = BaseURI; - } - - /** - * - * @return the basUri - */ - public String getBaseURI() { - return this._BaseURI; - } - //J+ } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java index e9ba6d13171..0ca4523600d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/ResourceResolverSpi.java @@ -2,192 +2,239 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver; - import java.util.HashMap; import java.util.Map; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import org.w3c.dom.Attr; - /** * During reference validation, we have to retrieve resources from somewhere. * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public abstract class ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResourceResolverSpi.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResourceResolverSpi.class.getName()); - /** Field _properties */ - protected java.util.Map _properties = null; + /** Field properties */ + protected java.util.Map properties = null; - protected boolean secureValidation; + /** + * Deprecated - used to carry state about whether resolution was being done in a secure fashion, + * but was not thread safe, so the resolution information is now passed as parameters to methods. + * + * @deprecated Secure validation flag is now passed to methods. + */ + @Deprecated + protected final boolean secureValidation = true; - /** - * This is the workhorse method used to resolve resources. - * - * @param uri - * @param BaseURI - * @return the resource wrapped arround a XMLSignatureInput - * - * @throws ResourceResolverException - */ - public abstract XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException; + /** + * This is the workhorse method used to resolve resources. + * + * @param uri + * @param BaseURI + * @return the resource wrapped around a XMLSignatureInput + * + * @throws ResourceResolverException + * + * @deprecated New clients should override {@link #engineResolveURI(ResourceResolverContext)} + */ + @Deprecated + public XMLSignatureInput engineResolve(Attr uri, String BaseURI) + throws ResourceResolverException { + throw new UnsupportedOperationException(); + } - /** - * Method engineSetProperty - * - * @param key - * @param value - */ - public void engineSetProperty(String key, String value) { - if (_properties==null) { - _properties=new HashMap(); - } - this._properties.put(key, value); - } + /** + * This is the workhorse method used to resolve resources. + * @param context Context to use to resolve resources. + * + * @return the resource wrapped around a XMLSignatureInput + * + * @throws ResourceResolverException + */ + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + // The default implementation, to preserve backwards compatibility in the + // test cases, calls the old resolver API. + return engineResolve(context.attr, context.baseUri); + } - /** - * Method engineGetProperty - * - * @param key - * @return the value of the property - */ - public String engineGetProperty(String key) { - if (_properties==null) { - return null; - } - return this._properties.get(key); - } + /** + * Method engineSetProperty + * + * @param key + * @param value + */ + public void engineSetProperty(String key, String value) { + if (properties == null) { + properties = new HashMap(); + } + properties.put(key, value); + } - /** - * - * @param properties - */ - public void engineAddProperies(Map properties) { - if (properties!=null) { - if (_properties==null) { - _properties=new HashMap(); - } - this._properties.putAll(properties); - } - } - /** - * Tells if the implementation does can be reused by several threads safely. - * It normally means that the implemantation does not have any member, or there is - * member change betwen engineCanResolve & engineResolve invocations. Or it mantians all - * member info in ThreadLocal methods. - */ - public boolean engineIsThreadSafe() { - return false; - } - /** - * This method helps the {@link ResourceResolver} to decide whether a - * {@link ResourceResolverSpi} is able to perform the requested action. - * - * @param uri - * @param BaseURI - * @return true if the engine can resolve the uri - */ - public abstract boolean engineCanResolve(Attr uri, String BaseURI); + /** + * Method engineGetProperty + * + * @param key + * @return the value of the property + */ + public String engineGetProperty(String key) { + if (properties == null) { + return null; + } + return properties.get(key); + } - /** - * Method engineGetPropertyKeys - * - * @return the property keys - */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } - - /** - * Method understandsProperty - * - * @param propertyToTest - * @return true if understands the property - */ - public boolean understandsProperty(String propertyToTest) { - - String[] understood = this.engineGetPropertyKeys(); - - if (understood != null) { - for (int i = 0; i < understood.length; i++) { - if (understood[i].equals(propertyToTest)) { - return true; + /** + * + * @param newProperties + */ + public void engineAddProperies(Map newProperties) { + if (newProperties != null && !newProperties.isEmpty()) { + if (properties == null) { + properties = new HashMap(); } - } - } + properties.putAll(newProperties); + } + } - return false; - } + /** + * Tells if the implementation does can be reused by several threads safely. + * It normally means that the implementation does not have any member, or there is + * member change between engineCanResolve & engineResolve invocations. Or it maintains all + * member info in ThreadLocal methods. + */ + public boolean engineIsThreadSafe() { + return false; + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + * @param uri + * @param BaseURI + * @return true if the engine can resolve the uri + * + * @deprecated See {@link #engineCanResolveURI(ResourceResolverContext)} + */ + @Deprecated + public boolean engineCanResolve(Attr uri, String BaseURI) { + // This method used to be abstract, so any calls to "super" are bogus. + throw new UnsupportedOperationException(); + } + + /** + * This method helps the {@link ResourceResolver} to decide whether a + * {@link ResourceResolverSpi} is able to perform the requested action. + * + *

    New clients should override this method, and not override {@link #engineCanResolve(Attr, String)} + *

    + * @param context Context in which to do resolution. + * @return true if the engine can resolve the uri + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + // To preserve backward compatibility with existing resolvers that might override the old method, + // call the old deprecated API. + return engineCanResolve( context.attr, context.baseUri ); + } + + /** + * Method engineGetPropertyKeys + * + * @return the property keys + */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } + + /** + * Method understandsProperty + * + * @param propertyToTest + * @return true if understands the property + */ + public boolean understandsProperty(String propertyToTest) { + String[] understood = this.engineGetPropertyKeys(); + + if (understood != null) { + for (int i = 0; i < understood.length; i++) { + if (understood[i].equals(propertyToTest)) { + return true; + } + } + } + + return false; + } - /** - * Fixes a platform dependent filename to standard URI form. - * - * @param str The string to fix. - * - * @return Returns the fixed URI string. - */ - public static String fixURI(String str) { + /** + * Fixes a platform dependent filename to standard URI form. + * + * @param str The string to fix. + * + * @return Returns the fixed URI string. + */ + public static String fixURI(String str) { - // handle platform dependent strings - str = str.replace(java.io.File.separatorChar, '/'); + // handle platform dependent strings + str = str.replace(java.io.File.separatorChar, '/'); - if (str.length() >= 4) { + if (str.length() >= 4) { - // str =~ /^\W:\/([^/])/ # to speak perl ;-)) - char ch0 = Character.toUpperCase(str.charAt(0)); - char ch1 = str.charAt(1); - char ch2 = str.charAt(2); - char ch3 = str.charAt(3); - boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z')) - && (ch1 == ':') && (ch2 == '/') - && (ch3 != '/')); - - if (isDosFilename) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); - } - } - - // Windows fix - if (str.length() >= 2) { - char ch1 = str.charAt(1); - - if (ch1 == ':') { + // str =~ /^\W:\/([^/])/ # to speak perl ;-)) char ch0 = Character.toUpperCase(str.charAt(0)); + char ch1 = str.charAt(1); + char ch2 = str.charAt(2); + char ch3 = str.charAt(3); + boolean isDosFilename = ((('A' <= ch0) && (ch0 <= 'Z')) + && (ch1 == ':') && (ch2 == '/') + && (ch3 != '/')); - if (('A' <= ch0) && (ch0 <= 'Z')) { - str = "/" + str; + if (isDosFilename && log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Found DOS filename: " + str); } - } - } + } - // done - return str; - } + // Windows fix + if (str.length() >= 2) { + char ch1 = str.charAt(1); + + if (ch1 == ':') { + char ch0 = Character.toUpperCase(str.charAt(0)); + + if (('A' <= ch0) && (ch0 <= 'Z')) { + str = "/" + str; + } + } + } + + // done + return str; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java index 0bd0c59120b..22aba4083b8 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverAnonymous.java @@ -2,21 +2,23 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; @@ -27,51 +29,56 @@ import java.io.IOException; import java.io.InputStream; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; /** - * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ - public class ResolverAnonymous extends ResourceResolverSpi { - private XMLSignatureInput _input = null; + private InputStream inStream = null; - /** - * @param filename + @Override + public boolean engineIsThreadSafe() { + return true; + } + + /** + * @param filename * @throws FileNotFoundException * @throws IOException */ - public ResolverAnonymous(String filename) throws FileNotFoundException, IOException { - this._input = new XMLSignatureInput(new FileInputStream(filename)); - } + public ResolverAnonymous(String filename) throws FileNotFoundException, IOException { + inStream = new FileInputStream(filename); + } - /** - * @param is + /** + * @param is */ - public ResolverAnonymous(InputStream is) { - this._input = new XMLSignatureInput(is); - } + public ResolverAnonymous(InputStream is) { + inStream = is; + } - /** @inheritDoc */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) { - return this._input; - } + /** @inheritDoc */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) { + return new XMLSignatureInput(inStream); + } - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - if (uri == null) { - return true; - } - return false; - } + /** + * @inheritDoc + */ + @Override + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return true; + } + return false; + } - /** @inheritDoc */ - public String[] engineGetPropertyKeys() { - return new String[0]; - } + /** @inheritDoc */ + public String[] engineGetPropertyKeys() { + return new String[0]; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java index 706cccc6a4d..cd0967215a7 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverDirectHTTP.java @@ -2,38 +2,42 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; +import java.net.InetSocketAddress; import java.net.MalformedURLException; +import java.net.Proxy; +import java.net.URISyntaxException; +import java.net.URI; import java.net.URL; import java.net.URLConnection; -import com.sun.org.apache.xml.internal.utils.URI; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.Base64; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; - /** * A simple ResourceResolver for HTTP requests. This class handles only 'pure' @@ -51,253 +55,219 @@ import org.w3c.dom.Attr; * resourceResolver.setProperty("http.proxy.password", "secretca"); *
    * - * - * @author $Author: mullan $ * @see Java Tip 42: Write Java apps that work with proxy-based firewalls * @see SUN J2SE docs for network properties * @see The JAVA FAQ Question 9.5: How do I make Java work with a proxy server? - * $todo$ the proxy behaviour seems not to work; if a on-existing proxy is set, it works ?!? */ public class ResolverDirectHTTP extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverDirectHTTP.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverDirectHTTP.class.getName()); - /** Field properties[] */ - private static final String properties[] = - { "http.proxy.host", "http.proxy.port", - "http.proxy.username", - "http.proxy.password", - "http.basic.username", - "http.basic.password" }; + /** Field properties[] */ + private static final String properties[] = { + "http.proxy.host", "http.proxy.port", + "http.proxy.username", "http.proxy.password", + "http.basic.username", "http.basic.password" + }; - /** Field HttpProxyHost */ - private static final int HttpProxyHost = 0; + /** Field HttpProxyHost */ + private static final int HttpProxyHost = 0; - /** Field HttpProxyPort */ - private static final int HttpProxyPort = 1; + /** Field HttpProxyPort */ + private static final int HttpProxyPort = 1; - /** Field HttpProxyUser */ - private static final int HttpProxyUser = 2; + /** Field HttpProxyUser */ + private static final int HttpProxyUser = 2; - /** Field HttpProxyPass */ - private static final int HttpProxyPass = 3; + /** Field HttpProxyPass */ + private static final int HttpProxyPass = 3; - /** Field HttpProxyUser */ - private static final int HttpBasicUser = 4; + /** Field HttpProxyUser */ + private static final int HttpBasicUser = 4; - /** Field HttpProxyPass */ - private static final int HttpBasicPass = 5; + /** Field HttpProxyPass */ + private static final int HttpBasicPass = 5; - public boolean engineIsThreadSafe() { - return true; - } - /** - * Method resolve - * - * @param uri - * @param BaseURI - * - * @throws ResourceResolverException - * @return - * $todo$ calculate the correct URI from the attribute and the BaseURI - */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException { + @Override + public boolean engineIsThreadSafe() { + return true; + } - try { - boolean useProxy = false; - String proxyHost = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyHost]); - String proxyPort = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPort]); + /** + * Method resolve + * + * @param uri + * @param baseURI + * + * @throws ResourceResolverException + * @return + * $todo$ calculate the correct URI from the attribute and the baseURI + */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + try { - if ((proxyHost != null) && (proxyPort != null)) { - useProxy = true; - } - - String oldProxySet = null; - String oldProxyHost = null; - String oldProxyPort = null; - // switch on proxy usage - if (useProxy) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "Use of HTTP proxy enabled: " + proxyHost + ":" - + proxyPort); - } - oldProxySet = System.getProperty("http.proxySet"); - oldProxyHost = System.getProperty("http.proxyHost"); - oldProxyPort = System.getProperty("http.proxyPort"); - System.setProperty("http.proxySet", "true"); - System.setProperty("http.proxyHost", proxyHost); - System.setProperty("http.proxyPort", proxyPort); - } - - boolean switchBackProxy = ((oldProxySet != null) - && (oldProxyHost != null) - && (oldProxyPort != null)); - - // calculate new URI - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); - - // if the URI contains a fragment, ignore it - URI uriNewNoFrag = new URI(uriNew); - - uriNewNoFrag.setFragment(null); - - URL url = new URL(uriNewNoFrag.toString()); - URLConnection urlConnection = url.openConnection(); - - { - - // set proxy pass - String proxyUser = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyUser]); - String proxyPass = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpProxyPass]); - - if ((proxyUser != null) && (proxyPass != null)) { - String password = proxyUser + ":" + proxyPass; - String encodedPassword = Base64.encode(password.getBytes()); - - // or was it Proxy-Authenticate ? - urlConnection.setRequestProperty("Proxy-Authorization", - encodedPassword); - } - } - - { + // calculate new URI + URI uriNew = getNewURI(context.uriToResolve, context.baseUri); + URL url = uriNew.toURL(); + URLConnection urlConnection; + urlConnection = openConnection(url); // check if Basic authentication is required String auth = urlConnection.getHeaderField("WWW-Authenticate"); - if (auth != null) { + if (auth != null && auth.startsWith("Basic")) { + // do http basic authentication + String user = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicUser]); + String pass = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpBasicPass]); - // do http basic authentication - if (auth.startsWith("Basic")) { - String user = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpBasicUser]); - String pass = - engineGetProperty(ResolverDirectHTTP - .properties[ResolverDirectHTTP.HttpBasicPass]); + if ((user != null) && (pass != null)) { + urlConnection = openConnection(url); - if ((user != null) && (pass != null)) { - urlConnection = url.openConnection(); + String password = user + ":" + pass; + String encodedPassword = Base64.encode(password.getBytes("ISO-8859-1")); - String password = user + ":" + pass; - String encodedPassword = - Base64.encode(password.getBytes()); - - // set authentication property in the http header - urlConnection.setRequestProperty("Authorization", - "Basic " - + encodedPassword); - } - } + // set authentication property in the http header + urlConnection.setRequestProperty("Authorization", + "Basic " + encodedPassword); + } } - } - String mimeType = urlConnection.getHeaderField("Content-Type"); - InputStream inputStream = urlConnection.getInputStream(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(); - byte buf[] = new byte[4096]; - int read = 0; - int summarized = 0; + String mimeType = urlConnection.getHeaderField("Content-Type"); + InputStream inputStream = urlConnection.getInputStream(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + byte buf[] = new byte[4096]; + int read = 0; + int summarized = 0; - while ((read = inputStream.read(buf)) >= 0) { - baos.write(buf, 0, read); + while ((read = inputStream.read(buf)) >= 0) { + baos.write(buf, 0, read); + summarized += read; + } - summarized += read; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " + uriNew.toString()); + } - log.log(java.util.logging.Level.FINE, "Fetched " + summarized + " bytes from URI " - + uriNew.toString()); + XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); - XMLSignatureInput result = new XMLSignatureInput(baos.toByteArray()); + result.setSourceURI(uriNew.toString()); + result.setMIMEType(mimeType); - // XMLSignatureInput result = new XMLSignatureInput(inputStream); - result.setSourceURI(uriNew.toString()); - result.setMIMEType(mimeType); + return result; + } catch (URISyntaxException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (MalformedURLException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (IOException ex) { + throw new ResourceResolverException("generic.EmptyMessage", ex, context.attr, context.baseUri); + } catch (IllegalArgumentException e) { + throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri); + } + } - // switch off proxy usage - if (useProxy && switchBackProxy) { - System.setProperty("http.proxySet", oldProxySet); - System.setProperty("http.proxyHost", oldProxyHost); - System.setProperty("http.proxyPort", oldProxyPort); - } + private URLConnection openConnection(URL url) throws IOException { - return result; - } catch (MalformedURLException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } catch (IOException ex) { - throw new ResourceResolverException("generic.EmptyMessage", ex, uri, - BaseURI); - } - } + String proxyHostProp = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyHost]); + String proxyPortProp = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPort]); + String proxyUser = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyUser]); + String proxyPass = + engineGetProperty(ResolverDirectHTTP.properties[ResolverDirectHTTP.HttpProxyPass]); - /** - * We resolve http URIs without fragment... - * - * @param uri - * @param BaseURI - * @return true if can be resolved - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - if (uri == null) { - log.log(java.util.logging.Level.FINE, "quick fail, uri == null"); + Proxy proxy = null; + if ((proxyHostProp != null) && (proxyPortProp != null)) { + int port = Integer.parseInt(proxyPortProp); + proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHostProp, port)); + } - return false; - } + URLConnection urlConnection; + if (proxy != null) { + urlConnection = url.openConnection(proxy); - String uriNodeValue = uri.getNodeValue(); + if ((proxyUser != null) && (proxyPass != null)) { + String password = proxyUser + ":" + proxyPass; + String authString = "Basic " + Base64.encode(password.getBytes("ISO-8859-1")); - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#')) { - log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); + urlConnection.setRequestProperty("Proxy-Authorization", authString); + } + } else { + urlConnection = url.openConnection(); + } - return false; - } + return urlConnection; + } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue); - } + /** + * We resolve http URIs without fragment... + * + * @param uri + * @param baseURI + * @return true if can be resolved + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "quick fail, uri == null"); + } + return false; + } - if ( uriNodeValue.startsWith("http:") || - (BaseURI!=null && BaseURI.startsWith("http:") )) { - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue); - } + if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#')) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "quick fail for empty URIs and local ones"); + } + return false; + } - return true; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve); + } - if (log.isLoggable(java.util.logging.Level.FINE)) { - log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + uriNodeValue); - } + if (context.uriToResolve.startsWith("http:") || + (context.baseUri != null && context.baseUri.startsWith("http:") )) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve); + } + return true; + } - return false; - } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can't resolve " + context.uriToResolve); + } - /** - * @inheritDoc - */ - public String[] engineGetPropertyKeys() { - return ResolverDirectHTTP.properties.clone(); - } + return false; + } - private URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { + /** + * @inheritDoc + */ + public String[] engineGetPropertyKeys() { + return ResolverDirectHTTP.properties.clone(); + } + + private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { + URI newUri = null; + if (baseURI == null || "".equals(baseURI)) { + newUri = new URI(uri); + } else { + newUri = new URI(baseURI).resolve(uri); + } + + // if the URI contains a fragment, ignore it + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; + } + return newUri; + } - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java index d2750c84903..49eb0407382 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverFragment.java @@ -2,148 +2,148 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; - - import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * This resolver is used for resolving same-document URIs like URI="" of URI="#id". * - * @author $Author: mullan $ + * @author $Author: coheigea $ * @see The Reference processing model in the XML Signature spec * @see Same-Document URI-References in the XML Signature spec * @see Section 4.2 of RFC 2396 */ public class ResolverFragment extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverFragment.class.getName()); - public boolean engineIsThreadSafe() { - return true; - } - /** - * Method engineResolve - * - * @inheritDoc - * @param uri - * @param baseURI - */ - public XMLSignatureInput engineResolve(Attr uri, String baseURI) - throws ResourceResolverException - { - String uriNodeValue = uri.getNodeValue(); - Document doc = uri.getOwnerElement().getOwnerDocument(); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverFragment.class.getName()); + + @Override + public boolean engineIsThreadSafe() { + return true; + } + + /** + * Method engineResolve + * + * @inheritDoc + * @param uri + * @param baseURI + */ + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + + Document doc = context.attr.getOwnerElement().getOwnerDocument(); Node selectedElem = null; - if (uriNodeValue.equals("")) { - - /* - * Identifies the node-set (minus any comment nodes) of the XML - * resource containing the signature - */ - - log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); + if (context.uriToResolve.equals("")) { + /* + * Identifies the node-set (minus any comment nodes) of the XML + * resource containing the signature + */ + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "ResolverFragment with empty URI (means complete document)"); + } selectedElem = doc; } else { - /* * URI="#chapter1" * Identifies a node-set containing the element with ID attribute * value 'chapter1' of the XML resource containing the signature. * XML Signature (and its applications) modify this node-set to - * include the element plus all descendents including namespaces and + * include the element plus all descendants including namespaces and * attributes -- but not comments. */ - String id = uriNodeValue.substring(1); + String id = context.uriToResolve.substring(1); selectedElem = doc.getElementById(id); if (selectedElem == null) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MissingID", exArgs, uri, baseURI); + "signature.Verification.MissingID", exArgs, context.attr, context.baseUri + ); } - if (secureValidation) { - Element start = uri.getOwnerDocument().getDocumentElement(); + if (context.secureValidation) { + Element start = context.attr.getOwnerDocument().getDocumentElement(); if (!XMLUtils.protectAgainstWrappingAttack(start, id)) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MultipleIDs", exArgs, - uri, baseURI); + "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri + ); } } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Try to catch an Element with ID " + id + " and Element was " + selectedElem); + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, + "Try to catch an Element with ID " + id + " and Element was " + selectedElem + ); + } } XMLSignatureInput result = new XMLSignatureInput(selectedElem); result.setExcludeComments(true); result.setMIMEType("text/xml"); - if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uri.getNodeValue())); + if (context.baseUri != null && context.baseUri.length() > 0) { + result.setSourceURI(context.baseUri.concat(context.uriToResolve)); } else { - result.setSourceURI(uri.getNodeValue()); + result.setSourceURI(context.uriToResolve); } return result; } - /** - * Method engineCanResolve - * @inheritDoc - * @param uri - * @param BaseURI - * - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { + /** + * Method engineCanResolve + * @inheritDoc + * @param uri + * @param baseURI + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Quick fail for null uri"); + } + return false; + } - if (uri == null) { - log.log(java.util.logging.Level.FINE, "Quick fail for null uri"); - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || - ( - (uriNodeValue.charAt(0)=='#') - && !((uriNodeValue.charAt(1)=='x') && uriNodeValue.startsWith("#xpointer(")) - ) - ){ - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + uriNodeValue + "\""); - return true; - } - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + uriNodeValue + "\""); - return false; - } + if (context.uriToResolve.equals("") || + ((context.uriToResolve.charAt(0) == '#') && !context.uriToResolve.startsWith("#xpointer(")) + ) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "State I can resolve reference: \"" + context.uriToResolve + "\""); + } + return true; + } + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Do not seem to be able to resolve reference: \"" + context.uriToResolve + "\""); + } + return false; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java index 07af53db296..c526286462d 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverLocalFilesystem.java @@ -2,156 +2,160 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; import java.io.FileInputStream; +import java.net.URI; +import java.net.URISyntaxException; -import com.sun.org.apache.xml.internal.utils.URI; import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; /** * A simple ResourceResolver for requests into the local filesystem. - * - * @author $Author: mullan $ */ public class ResolverLocalFilesystem extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverLocalFilesystem.class.getName()); + private static final int FILE_URI_LENGTH = "file:/".length(); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverLocalFilesystem.class.getName()); + + @Override public boolean engineIsThreadSafe() { - return true; - } - /** - * @inheritDoc - */ - public XMLSignatureInput engineResolve(Attr uri, String BaseURI) - throws ResourceResolverException { + return true; + } - try { - URI uriNew = getNewURI(uri.getNodeValue(), BaseURI); + /** + * @inheritDoc + */ + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { + try { + // calculate new URI + URI uriNew = getNewURI(context.uriToResolve, context.baseUri); + + String fileName = + ResolverLocalFilesystem.translateUriToFilename(uriNew.toString()); + FileInputStream inputStream = new FileInputStream(fileName); + XMLSignatureInput result = new XMLSignatureInput(inputStream); + + result.setSourceURI(uriNew.toString()); + + return result; + } catch (Exception e) { + throw new ResourceResolverException("generic.EmptyMessage", e, context.attr, context.baseUri); + } + } + + /** + * Method translateUriToFilename + * + * @param uri + * @return the string of the filename + */ + private static String translateUriToFilename(String uri) { + + String subStr = uri.substring(FILE_URI_LENGTH); + + if (subStr.indexOf("%20") > -1) { + int offset = 0; + int index = 0; + StringBuilder temp = new StringBuilder(subStr.length()); + do { + index = subStr.indexOf("%20",offset); + if (index == -1) { + temp.append(subStr.substring(offset)); + } else { + temp.append(subStr.substring(offset, index)); + temp.append(' '); + offset = index + 3; + } + } while(index != -1); + subStr = temp.toString(); + } + + if (subStr.charAt(1) == ':') { + // we're running M$ Windows, so this works fine + return subStr; + } + // we're running some UNIX, so we have to prepend a slash + return "/" + subStr; + } + + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + + if (context.uriToResolve.equals("") || (context.uriToResolve.charAt(0)=='#') || + context.uriToResolve.startsWith("http:")) { + return false; + } + + try { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + context.uriToResolve); + } + + if (context.uriToResolve.startsWith("file:") || context.baseUri.startsWith("file:")) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "I state that I can resolve " + context.uriToResolve); + } + return true; + } + } catch (Exception e) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, e.getMessage(), e); + } + } + + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "But I can't"); + } + + return false; + } + + private static URI getNewURI(String uri, String baseURI) throws URISyntaxException { + URI newUri = null; + if (baseURI == null || "".equals(baseURI)) { + newUri = new URI(uri); + } else { + newUri = new URI(baseURI).resolve(uri); + } // if the URI contains a fragment, ignore it - URI uriNewNoFrag = new URI(uriNew); - - uriNewNoFrag.setFragment(null); - - String fileName = - ResolverLocalFilesystem - .translateUriToFilename(uriNewNoFrag.toString()); - FileInputStream inputStream = new FileInputStream(fileName); - XMLSignatureInput result = new XMLSignatureInput(inputStream); - - result.setSourceURI(uriNew.toString()); - - return result; - } catch (Exception e) { - throw new ResourceResolverException("generic.EmptyMessage", e, uri, - BaseURI); - } - } - - private static int FILE_URI_LENGTH="file:/".length(); - /** - * Method translateUriToFilename - * - * @param uri - * @return the string of the filename - */ - private static String translateUriToFilename(String uri) { - - String subStr = uri.substring(FILE_URI_LENGTH); - - if (subStr.indexOf("%20") > -1) - { - int offset = 0; - int index = 0; - StringBuffer temp = new StringBuffer(subStr.length()); - do - { - index = subStr.indexOf("%20",offset); - if (index == -1) temp.append(subStr.substring(offset)); - else - { - temp.append(subStr.substring(offset,index)); - temp.append(' '); - offset = index+3; - } + if (newUri.getFragment() != null) { + URI uriNewNoFrag = + new URI(newUri.getScheme(), newUri.getSchemeSpecificPart(), null); + return uriNewNoFrag; } - while(index != -1); - subStr = temp.toString(); - } - - if (subStr.charAt(1) == ':') { - // we're running M$ Windows, so this works fine - return subStr; - } - // we're running some UNIX, so we have to prepend a slash - return "/" + subStr; - } - - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - return false; - } - - String uriNodeValue = uri.getNodeValue(); - - if (uriNodeValue.equals("") || (uriNodeValue.charAt(0)=='#') || - uriNodeValue.startsWith("http:")) { - return false; - } - - try { - //URI uriNew = new URI(new URI(BaseURI), uri.getNodeValue()); - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "I was asked whether I can resolve " + uriNodeValue/*uriNew.toString()*/); - - if ( uriNodeValue.startsWith("file:") || - BaseURI.startsWith("file:")/*uriNew.getScheme().equals("file")*/) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "I state that I can resolve " + uriNodeValue/*uriNew.toString()*/); - - return true; - } - } catch (Exception e) {} - - log.log(java.util.logging.Level.FINE, "But I can't"); - - return false; - } - - private static URI getNewURI(String uri, String BaseURI) - throws URI.MalformedURIException { - - if ((BaseURI == null) || "".equals(BaseURI)) { - return new URI(uri); - } - return new URI(new URI(BaseURI), uri); - } + return newUri; + } } diff --git a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java index 0f931f44193..345087bbcec 100644 --- a/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java +++ b/jdk/src/share/classes/com/sun/org/apache/xml/internal/security/utils/resolver/implementations/ResolverXPointer.java @@ -2,36 +2,35 @@ * reserved comment block * DO NOT REMOVE OR ALTER! */ -/* - * Copyright 1999-2004 The Apache Software Foundation. +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. + * http://www.apache.org/licenses/LICENSE-2.0 * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. */ package com.sun.org.apache.xml.internal.security.utils.resolver.implementations; - - import com.sun.org.apache.xml.internal.security.signature.XMLSignatureInput; import com.sun.org.apache.xml.internal.security.utils.XMLUtils; +import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverContext; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverException; import com.sun.org.apache.xml.internal.security.utils.resolver.ResourceResolverSpi; -import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; - /** * Handles barename XPointer Reference URIs. *
    @@ -45,15 +44,18 @@ import org.w3c.dom.Node; * nodes of the parse tree (all descendants, plus all attributes, * plus all namespaces nodes). * - * @author $Author: mullan $ + * @author $Author: coheigea $ */ public class ResolverXPointer extends ResourceResolverSpi { - /** {@link java.util.logging} logging facility */ - static java.util.logging.Logger log = - java.util.logging.Logger.getLogger( - ResolverXPointer.class.getName()); + /** {@link org.apache.commons.logging} logging facility */ + private static java.util.logging.Logger log = + java.util.logging.Logger.getLogger(ResolverXPointer.class.getName()); + private static final String XP = "#xpointer(id("; + private static final int XP_LENGTH = XP.length(); + + @Override public boolean engineIsThreadSafe() { return true; } @@ -61,139 +63,118 @@ public class ResolverXPointer extends ResourceResolverSpi { /** * @inheritDoc */ - public XMLSignatureInput engineResolve(Attr uri, String baseURI) - throws ResourceResolverException { + @Override + public XMLSignatureInput engineResolveURI(ResourceResolverContext context) + throws ResourceResolverException { Node resultNode = null; - Document doc = uri.getOwnerElement().getOwnerDocument(); + Document doc = context.attr.getOwnerElement().getOwnerDocument(); - String uriStr = uri.getNodeValue(); - if (isXPointerSlash(uriStr)) { + if (isXPointerSlash(context.uriToResolve)) { resultNode = doc; - - } else if (isXPointerId(uriStr)) { - String id = getXPointerId(uriStr); + } else if (isXPointerId(context.uriToResolve)) { + String id = getXPointerId(context.uriToResolve); resultNode = doc.getElementById(id); - if (secureValidation) { - Element start = uri.getOwnerDocument().getDocumentElement(); + if (context.secureValidation) { + Element start = context.attr.getOwnerDocument().getDocumentElement(); if (!XMLUtils.protectAgainstWrappingAttack(start, id)) { Object exArgs[] = { id }; throw new ResourceResolverException( - "signature.Verification.MultipleIDs", exArgs, - uri, baseURI); + "signature.Verification.MultipleIDs", exArgs, context.attr, context.baseUri + ); } } if (resultNode == null) { - Object exArgs[] = { id }; + Object exArgs[] = { id }; - throw new ResourceResolverException( - "signature.Verification.MissingID", exArgs, uri, baseURI); + throw new ResourceResolverException( + "signature.Verification.MissingID", exArgs, context.attr, context.baseUri + ); } } XMLSignatureInput result = new XMLSignatureInput(resultNode); result.setMIMEType("text/xml"); - if (baseURI != null && baseURI.length() > 0) { - result.setSourceURI(baseURI.concat(uri.getNodeValue())); + if (context.baseUri != null && context.baseUri.length() > 0) { + result.setSourceURI(context.baseUri.concat(context.uriToResolve)); } else { - result.setSourceURI(uri.getNodeValue()); + result.setSourceURI(context.uriToResolve); } return result; } - /** - * @inheritDoc - */ - public boolean engineCanResolve(Attr uri, String BaseURI) { - - if (uri == null) { - return false; - } - String uriStr =uri.getNodeValue(); - if (isXPointerSlash(uriStr) || isXPointerId(uriStr)) { - return true; - } - - return false; - } - - /** - * Method isXPointerSlash - * - * @param uri - * @return true if begins with xpointer - */ - private static boolean isXPointerSlash(String uri) { - - if (uri.equals("#xpointer(/)")) { - return true; - } - - return false; - } - - - private static final String XP="#xpointer(id("; - private static final int XP_LENGTH=XP.length(); - /** - * Method isXPointerId - * - * @param uri - * @return it it has an xpointer id - * - */ - private static boolean isXPointerId(String uri) { - - - if (uri.startsWith(XP) - && uri.endsWith("))")) { - String idPlusDelim = uri.substring(XP_LENGTH, - uri.length() - - 2); - - // log.log(java.util.logging.Level.FINE, "idPlusDelim=" + idPlusDelim); - int idLen=idPlusDelim.length() -1; - if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim - .charAt(idLen) == '"')) || ((idPlusDelim - .charAt(0) == '\'') && (idPlusDelim - .charAt(idLen) == '\''))) { - if (log.isLoggable(java.util.logging.Level.FINE)) - log.log(java.util.logging.Level.FINE, "Id=" - + idPlusDelim.substring(1, idLen)); - + /** + * @inheritDoc + */ + public boolean engineCanResolveURI(ResourceResolverContext context) { + if (context.uriToResolve == null) { + return false; + } + if (isXPointerSlash(context.uriToResolve) || isXPointerId(context.uriToResolve)) { return true; - } - } + } - return false; - } + return false; + } - /** - * Method getXPointerId - * - * @param uri - * @return xpointerId to search. - */ - private static String getXPointerId(String uri) { + /** + * Method isXPointerSlash + * + * @param uri + * @return true if begins with xpointer + */ + private static boolean isXPointerSlash(String uri) { + if (uri.equals("#xpointer(/)")) { + return true; + } + return false; + } - if (uri.startsWith(XP) - && uri.endsWith("))")) { - String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - - 2); - int idLen=idPlusDelim.length() -1; - if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim - .charAt(idLen) == '"')) || ((idPlusDelim - .charAt(0) == '\'') && (idPlusDelim - .charAt(idLen) == '\''))) { - return idPlusDelim.substring(1, idLen); - } - } + /** + * Method isXPointerId + * + * @param uri + * @return whether it has an xpointer id + */ + private static boolean isXPointerId(String uri) { + if (uri.startsWith(XP) && uri.endsWith("))")) { + String idPlusDelim = uri.substring(XP_LENGTH, uri.length() - 2); - return null; - } + int idLen = idPlusDelim.length() -1; + if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"')) + || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) { + if (log.isLoggable(java.util.logging.Level.FINE)) { + log.log(java.util.logging.Level.FINE, "Id = " + idPlusDelim.substring(1, idLen)); + } + return true; + } + } + + return false; + } + + /** + * Method getXPointerId + * + * @param uri + * @return xpointerId to search. + */ + private static String getXPointerId(String uri) { + if (uri.startsWith(XP) && uri.endsWith("))")) { + String idPlusDelim = uri.substring(XP_LENGTH,uri.length() - 2); + + int idLen = idPlusDelim.length() -1; + if (((idPlusDelim.charAt(0) == '"') && (idPlusDelim.charAt(idLen) == '"')) + || ((idPlusDelim.charAt(0) == '\'') && (idPlusDelim.charAt(idLen) == '\''))) { + return idPlusDelim.substring(1, idLen); + } + } + + return null; + } } diff --git a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java index 17bab9c9c70..93901d4b41f 100644 --- a/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java +++ b/jdk/src/share/classes/com/sun/security/sasl/util/AbstractSaslImpl.java @@ -252,13 +252,12 @@ public abstract class AbstractSaslImpl { /** - * Outputs a byte array and converts + * Outputs a byte array. Can be null. */ protected static final void traceOutput(String srcClass, String srcMethod, String traceTag, byte[] output) { - if (output != null) { - traceOutput(srcClass, srcMethod, traceTag, output, 0, output.length); - } + traceOutput(srcClass, srcMethod, traceTag, output, 0, + output == null ? 0 : output.length); } protected static final void traceOutput(String srcClass, String srcMethod, @@ -274,13 +273,20 @@ public abstract class AbstractSaslImpl { lev = Level.FINEST; } - ByteArrayOutputStream out = new ByteArrayOutputStream(len); - new HexDumpEncoder().encodeBuffer( - new ByteArrayInputStream(output, offset, len), out); + String content; + + if (output != null) { + ByteArrayOutputStream out = new ByteArrayOutputStream(len); + new HexDumpEncoder().encodeBuffer( + new ByteArrayInputStream(output, offset, len), out); + content = out.toString(); + } else { + content = "NULL"; + } // Message id supplied by caller as part of traceTag logger.logp(lev, srcClass, srcMethod, "{0} ( {1} ): {2}", - new Object[] {traceTag, new Integer(origlen), out.toString()}); + new Object[] {traceTag, new Integer(origlen), content}); } catch (Exception e) { logger.logp(Level.WARNING, srcClass, srcMethod, "SASLIMPL09:Error generating trace output: {0}", e); diff --git a/jdk/src/share/classes/java/io/BufferedReader.java b/jdk/src/share/classes/java/io/BufferedReader.java index ebf398078bf..98fe47c7a59 100644 --- a/jdk/src/share/classes/java/io/BufferedReader.java +++ b/jdk/src/share/classes/java/io/BufferedReader.java @@ -587,6 +587,6 @@ public class BufferedReader extends Reader { } } }; - return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED)); + return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iter, Spliterator.ORDERED), false); } } diff --git a/jdk/src/share/classes/java/io/DataInput.java b/jdk/src/share/classes/java/io/DataInput.java index 1480c9f0485..4dad59d55f3 100644 --- a/jdk/src/share/classes/java/io/DataInput.java +++ b/jdk/src/share/classes/java/io/DataInput.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -66,10 +66,10 @@ package java.io; * summary="Bit values and bytes"> * * - * Bit Values + * Bit Values * * - * Byte 1 + * Byte 1 * * * @@ -92,10 +92,10 @@ package java.io; * summary="Bit values and bytes"> * * - * + * * * - * + * *
    Bit ValuesBit Values
    Byte 1Byte 1 * * @@ -108,7 +108,7 @@ package java.io; * * * - * + * *
    Byte 2Byte 2 * * @@ -131,10 +131,10 @@ package java.io; * summary="Bit values and bytes"> * * - * + * * * - * + * *
    Bit ValuesBit Values
    Byte 1Byte 1 * * @@ -148,7 +148,7 @@ package java.io; * * * - * + * *
    Byte 2Byte 2 * * diff --git a/jdk/src/share/classes/java/io/File.java b/jdk/src/share/classes/java/io/File.java index 4bc75fe5099..6bab9bb21fe 100644 --- a/jdk/src/share/classes/java/io/File.java +++ b/jdk/src/share/classes/java/io/File.java @@ -1910,7 +1910,7 @@ public class File } String name = prefix + Long.toString(n) + suffix; File f = new File(dir, name); - if (!name.equals(f.getName())) + if (!name.equals(f.getName()) || f.isInvalid()) throw new IOException("Unable to create temporary file"); return f; } @@ -1996,19 +1996,26 @@ public class File File tmpdir = (directory != null) ? directory : TempDirectory.location(); + SecurityManager sm = System.getSecurityManager(); File f; - try { - do { - f = TempDirectory.generateFile(prefix, suffix, tmpdir); - } while (f.exists()); - if (!f.createNewFile()) - throw new IOException("Unable to create temporary file"); - } catch (SecurityException se) { - // don't reveal temporary directory location - if (directory == null) - throw new SecurityException("Unable to create temporary file"); - throw se; - } + do { + f = TempDirectory.generateFile(prefix, suffix, tmpdir); + + if (sm != null) { + try { + sm.checkWrite(f.getPath()); + } catch (SecurityException se) { + // don't reveal temporary directory location + if (directory == null) + throw new SecurityException("Unable to create temporary file"); + throw se; + } + } + } while ((fs.getBooleanAttributes(f) & FileSystem.BA_EXISTS) != 0); + + if (!fs.createFileExclusively(f.getPath())) + throw new IOException("Unable to create temporary file"); + return f; } diff --git a/jdk/src/share/classes/java/io/FileInputStream.java b/jdk/src/share/classes/java/io/FileInputStream.java index 90d1ad5cc3e..3e67fb85515 100644 --- a/jdk/src/share/classes/java/io/FileInputStream.java +++ b/jdk/src/share/classes/java/io/FileInputStream.java @@ -331,7 +331,7 @@ class FileInputStream extends InputStream * object associated with this file input stream. * *

    The initial {@link java.nio.channels.FileChannel#position() - * position} of the returned channel will be equal to the + * position} of the returned channel will be equal to the * number of bytes read from the file so far. Reading bytes from this * stream will increment the channel's position. Changing the channel's * position, either explicitly or by reading, will change this stream's diff --git a/jdk/src/share/classes/java/io/FileOutputStream.java b/jdk/src/share/classes/java/io/FileOutputStream.java index 928e4f3cf15..44f472870ec 100644 --- a/jdk/src/share/classes/java/io/FileOutputStream.java +++ b/jdk/src/share/classes/java/io/FileOutputStream.java @@ -358,10 +358,10 @@ class FileOutputStream extends OutputStream /** * Returns the unique {@link java.nio.channels.FileChannel FileChannel} - * object associated with this file output stream.

    + * object associated with this file output stream. * *

    The initial {@link java.nio.channels.FileChannel#position() - * position} of the returned channel will be equal to the + * position} of the returned channel will be equal to the * number of bytes written to the file so far unless this stream is in * append mode, in which case it will be equal to the size of the file. * Writing bytes to this stream will increment the channel's position diff --git a/jdk/src/share/classes/java/io/InputStreamReader.java b/jdk/src/share/classes/java/io/InputStreamReader.java index 1f6d5f6113b..e131dca304a 100644 --- a/jdk/src/share/classes/java/io/InputStreamReader.java +++ b/jdk/src/share/classes/java/io/InputStreamReader.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -33,7 +33,7 @@ import sun.nio.cs.StreamDecoder; /** * An InputStreamReader is a bridge from byte streams to character streams: It * reads bytes and decodes them into characters using a specified {@link - * java.nio.charset.Charset charset}. The charset that it uses + * java.nio.charset.Charset charset}. The charset that it uses * may be specified by name or may be given explicitly, or the platform's * default charset may be accepted. * @@ -101,7 +101,7 @@ public class InputStreamReader extends Reader { } /** - * Creates an InputStreamReader that uses the given charset.

    + * Creates an InputStreamReader that uses the given charset. * * @param in An InputStream * @param cs A charset @@ -117,7 +117,7 @@ public class InputStreamReader extends Reader { } /** - * Creates an InputStreamReader that uses the given charset decoder.

    + * Creates an InputStreamReader that uses the given charset decoder. * * @param in An InputStream * @param dec A charset decoder diff --git a/jdk/src/share/classes/java/io/OutputStreamWriter.java b/jdk/src/share/classes/java/io/OutputStreamWriter.java index b4e4b9e320b..5f7b9e34bca 100644 --- a/jdk/src/share/classes/java/io/OutputStreamWriter.java +++ b/jdk/src/share/classes/java/io/OutputStreamWriter.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1996, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1996, 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 @@ -33,7 +33,7 @@ import sun.nio.cs.StreamEncoder; /** * An OutputStreamWriter is a bridge from character streams to byte streams: * Characters written to it are encoded into bytes using a specified {@link - * java.nio.charset.Charset charset}. The charset that it uses + * java.nio.charset.Charset charset}. The charset that it uses * may be specified by name or may be given explicitly, or the platform's * default charset may be accepted. * @@ -86,7 +86,7 @@ public class OutputStreamWriter extends Writer { * * @param charsetName * The name of a supported - * {@link java.nio.charset.Charset
    charset} + * {@link java.nio.charset.Charset charset} * * @exception UnsupportedEncodingException * If the named encoding is not supported @@ -115,7 +115,7 @@ public class OutputStreamWriter extends Writer { } /** - * Creates an OutputStreamWriter that uses the given charset.

    + * Creates an OutputStreamWriter that uses the given charset. * * @param out * An OutputStream @@ -134,7 +134,7 @@ public class OutputStreamWriter extends Writer { } /** - * Creates an OutputStreamWriter that uses the given charset encoder.

    + * Creates an OutputStreamWriter that uses the given charset encoder. * * @param out * An OutputStream diff --git a/jdk/src/share/classes/java/io/PipedInputStream.java b/jdk/src/share/classes/java/io/PipedInputStream.java index 4ad8fbd81d8..af07de5b4e6 100644 --- a/jdk/src/share/classes/java/io/PipedInputStream.java +++ b/jdk/src/share/classes/java/io/PipedInputStream.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -39,7 +39,7 @@ package java.io; * The piped input stream contains a buffer, * decoupling read operations from write operations, * within limits. - * A pipe is said to be broken if a + * A pipe is said to be broken if a * thread that was providing data bytes to the connected * piped output stream is no longer alive. * @@ -193,7 +193,7 @@ public class PipedInputStream extends InputStream { * Receives a byte of data. This method will block if no input is * available. * @param b the byte being received - * @exception IOException If the pipe is broken, + * @exception IOException If the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. * @since JDK1.1 @@ -219,7 +219,7 @@ public class PipedInputStream extends InputStream { * @param b the buffer into which the data is received * @param off the start offset of the data * @param len the maximum number of bytes received - * @exception IOException If the pipe is broken, + * @exception IOException If the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed,or if an I/O error occurs. */ @@ -298,7 +298,7 @@ public class PipedInputStream extends InputStream { * stream is reached. * @exception IOException if the pipe is * {@link #connect(java.io.PipedOutputStream) unconnected}, - * broken, closed, + * broken, closed, * or if an I/O error occurs. */ public synchronized int read() throws IOException { @@ -361,7 +361,7 @@ public class PipedInputStream extends InputStream { * @exception IndexOutOfBoundsException If off is negative, * len is negative, or len is greater than * b.length - off - * @exception IOException if the pipe is broken, + * @exception IOException if the pipe is broken, * {@link #connect(java.io.PipedOutputStream) unconnected}, * closed, or if an I/O error occurs. */ @@ -419,7 +419,7 @@ public class PipedInputStream extends InputStream { * without blocking, or {@code 0} if this input stream has been * closed by invoking its {@link #close()} method, or if the pipe * is {@link #connect(java.io.PipedOutputStream) unconnected}, or - * broken. + * broken. * * @exception IOException if an I/O error occurs. * @since JDK1.0.2 diff --git a/jdk/src/share/classes/java/io/RandomAccessFile.java b/jdk/src/share/classes/java/io/RandomAccessFile.java index adccfbc757a..5e32ad5dba1 100644 --- a/jdk/src/share/classes/java/io/RandomAccessFile.java +++ b/jdk/src/share/classes/java/io/RandomAccessFile.java @@ -123,11 +123,11 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * write to, the file specified by the {@link File} argument. A new {@link * FileDescriptor} object is created to represent this file connection. * - *

    The mode argument specifies the access mode + *

    The mode argument specifies the access mode * in which the file is to be opened. The permitted values and their * meanings are: * - *

    + *
    * * * - *

    Value

    Meaning

    "r" Open for reading only. Invoking any of the write @@ -144,7 +144,7 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * Open for reading and writing, as with "rw", and also * require that every update to the file's content be written * synchronously to the underlying storage device.
    + *
    * * The "rws" and "rwd" modes work much like the {@link * java.nio.channels.FileChannel#force(boolean) force(boolean)} method of @@ -158,13 +158,13 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { * event of a system crash. If the file does not reside on a local device * then no such guarantee is made. * - *

    The "rwd" mode can be used to reduce the number of I/O + *

    The "rwd" mode can be used to reduce the number of I/O * operations performed. Using "rwd" only requires updates to the * file's content to be written to storage; using "rws" requires * updates to both the file's content and its metadata to be written, which * generally requires at least one more low-level I/O operation. * - *

    If there is a security manager, its {@code checkRead} method is + *

    If there is a security manager, its {@code checkRead} method is * called with the pathname of the {@code file} argument as its * argument to see if read access to the file is allowed. If the mode * allows writing, the security manager's {@code checkWrite} method is @@ -238,7 +238,7 @@ public class RandomAccessFile implements DataOutput, DataInput, Closeable { /** * Returns the opaque file descriptor object associated with this - * stream.

    + * stream. * * @return the file descriptor object associated with this stream. * @exception IOException if an I/O error occurs. diff --git a/jdk/src/share/classes/java/lang/CharSequence.java b/jdk/src/share/classes/java/lang/CharSequence.java index 30a23590875..ac80b22f066 100644 --- a/jdk/src/share/classes/java/lang/CharSequence.java +++ b/jdk/src/share/classes/java/lang/CharSequence.java @@ -60,7 +60,7 @@ public interface CharSequence { /** * Returns the length of this character sequence. The length is the number - * of 16-bit chars in the sequence.

    + * of 16-bit chars in the sequence. * * @return the number of chars in this sequence */ @@ -70,7 +70,7 @@ public interface CharSequence { * Returns the char value at the specified index. An index ranges from zero * to length() - 1. The first char value of the sequence is at * index zero, the next at index one, and so on, as for array - * indexing.

    + * indexing. * *

    If the char value specified by the index is a * surrogate, the surrogate @@ -92,7 +92,7 @@ public interface CharSequence { * ends with the char value at index end - 1. The length * (in chars) of the * returned sequence is end - start, so if start == end - * then an empty sequence is returned.

    + * then an empty sequence is returned. * * @param start the start index, inclusive * @param end the end index, exclusive @@ -109,7 +109,7 @@ public interface CharSequence { /** * Returns a string containing the characters in this sequence in the same * order as this sequence. The length of the string will be the length of - * this sequence.

    + * this sequence. * * @return a string consisting of exactly this sequence of characters */ @@ -156,7 +156,8 @@ public interface CharSequence { new CharIterator(), length(), Spliterator.ORDERED), - Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED); + Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, + false); } /** @@ -227,6 +228,7 @@ public interface CharSequence { Spliterators.spliteratorUnknownSize( new CodePointIterator(), Spliterator.ORDERED), - Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED); + Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED, + false); } } diff --git a/jdk/src/share/classes/java/lang/Character.java b/jdk/src/share/classes/java/lang/Character.java index e512e582612..41576cca8d8 100644 --- a/jdk/src/share/classes/java/lang/Character.java +++ b/jdk/src/share/classes/java/lang/Character.java @@ -54,7 +54,7 @@ import java.util.Locale; *
  • http://www.unicode.org * * - *

    Unicode Character Representations

    + *

    Unicode Character Representations

    * *

    The {@code char} data type (and therefore the value that a * {@code Character} object encapsulates) are based on the @@ -68,7 +68,7 @@ import java.util.Locale; * definition of the U+n notation in the Unicode * Standard.) * - *

    The set of characters from U+0000 to U+FFFF is + *

    The set of characters from U+0000 to U+FFFF is * sometimes referred to as the Basic Multilingual Plane (BMP). * Characters whose code points are greater * than U+FFFF are called supplementary characters. The Java @@ -4599,6 +4599,7 @@ class Character implements java.io.Serializable, Comparable { * * @since 1.8 * + * @param value The {@code char} for which to return a hash code. * @return a hash code value for a {@code char} value. */ public static int hashCode(char value) { @@ -6637,7 +6638,7 @@ class Character implements java.io.Serializable, Comparable { * Determines if the specified character is ISO-LATIN-1 white space. * This method returns {@code true} for the following five * characters only: - * + *
    * * * @@ -7174,6 +7175,7 @@ class Character implements java.io.Serializable, Comparable { * Returns the value obtained by reversing the order of the bytes in the * specified char value. * + * @param ch The {@code char} of which to reverse the byte order. * @return the value obtained by reversing (or, equivalently, swapping) * the bytes in the specified char value. * @since 1.5 diff --git a/jdk/src/share/classes/java/lang/Class.java b/jdk/src/share/classes/java/lang/Class.java index df4d457367d..2e47377996f 100644 --- a/jdk/src/share/classes/java/lang/Class.java +++ b/jdk/src/share/classes/java/lang/Class.java @@ -360,36 +360,24 @@ public final class Class implements java.io.Serializable, * any exception thrown by the constructor in a (checked) {@link * java.lang.reflect.InvocationTargetException}. * - * @return a newly allocated instance of the class represented by this - * object. - * @exception IllegalAccessException if the class or its nullary - * constructor is not accessible. - * @exception InstantiationException - * if this {@code Class} represents an abstract class, - * an interface, an array class, a primitive type, or void; - * or if the class has no nullary constructor; - * or if the instantiation fails for some other reason. - * @exception ExceptionInInitializerError if the initialization - * provoked by this method fails. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * creation of new instances of this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    - * + * @return a newly allocated instance of the class represented by this + * object. + * @throws IllegalAccessException if the class or its nullary + * constructor is not accessible. + * @throws InstantiationException + * if this {@code Class} represents an abstract class, + * an interface, an array class, a primitive type, or void; + * or if the class has no nullary constructor; + * or if the instantiation fails for some other reason. + * @throws ExceptionInInitializerError if the initialization + * provoked by this method fails. + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. */ @CallerSensitive public T newInstance() @@ -981,24 +969,27 @@ public final class Class implements java.io.Serializable, * * @return the immediately enclosing method of the underlying class, if * that class is a local or anonymous class; otherwise {@code null}. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: * - *
      + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies - * access to the methods within the enclosing class + *
        * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the enclosing class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of the enclosing class + *
      • the caller's class loader is not the same as the + * class loader of the enclosing class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the methods within the enclosing class * - *
      + *
    • the caller's class loader is not the same as or an + * ancestor of the class loader for the enclosing class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of the enclosing class + * + *
    * @since 1.5 */ @CallerSensitive @@ -1025,11 +1016,6 @@ public final class Class implements java.io.Serializable, // Perform access check Class enclosingCandidate = enclosingInfo.getEnclosingClass(); - // be very careful not to change the stack depth of this - // checkMemberAccess call for security reasons - // see java.lang.SecurityManager.checkMemberAccess - // - // Note that we need to do this on the enclosing class enclosingCandidate.checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); /* @@ -1137,24 +1123,26 @@ public final class Class implements java.io.Serializable, * * @return the immediately enclosing constructor of the underlying class, if * that class is a local or anonymous class; otherwise {@code null}. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(enclosingClass, Member.DECLARED)} denies - * access to the constructors within the enclosing class + *
      • the caller's class loader is not the same as the + * class loader of the enclosing class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the constructors within the enclosing class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the enclosing class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of the enclosing class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the enclosing class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of the enclosing class * - *
      + *
    * @since 1.5 */ @CallerSensitive @@ -1180,11 +1168,6 @@ public final class Class implements java.io.Serializable, // Perform access check Class enclosingCandidate = enclosingInfo.getEnclosingClass(); - // be very careful not to change the stack depth of this - // checkMemberAccess call for security reasons - // see java.lang.SecurityManager.checkMemberAccess - // - // Note that we need to do this on the enclosing class enclosingCandidate.checkMemberAccess(Member.DECLARED, Reflection.getCallerClass(), true); /* @@ -1457,25 +1440,14 @@ public final class Class implements java.io.Serializable, * class, or void. * * @return the array of {@code Class} objects representing the public - * members of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} method - * denies access to the classes within this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * members of this class + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1530,25 +1502,14 @@ public final class Class implements java.io.Serializable, *

    See The Java Language Specification, sections 8.2 and 8.3. * * @return the array of {@code Field} objects representing the - * public fields - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the fields within this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * public fields + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1579,25 +1540,14 @@ public final class Class implements java.io.Serializable, *

    See The Java Language Specification, sections 8.2 and 8.4. * * @return the array of {@code Method} objects representing the - * public methods of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the methods within this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * public methods of this class + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1626,25 +1576,14 @@ public final class Class implements java.io.Serializable, * {@code Constructor[]}. * * @return the array of {@code Constructor} objects representing the - * public constructors of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the constructors within this class - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * public constructors of this class + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1678,29 +1617,18 @@ public final class Class implements java.io.Serializable, *

    See The Java Language Specification, sections 8.2 and 8.3. * * @param name the field name - * @return the {@code Field} object of this class specified by - * {@code name} - * @exception NoSuchFieldException if a field with the specified name is - * not found. - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *

      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the field - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * @return the {@code Field} object of this class specified by + * {@code name} + * @throws NoSuchFieldException if a field with the specified name is + * not found. + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1762,28 +1690,17 @@ public final class Class implements java.io.Serializable, * @param name the name of the method * @param parameterTypes the list of parameters * @return the {@code Method} object that matches the specified - * {@code name} and {@code parameterTypes} - * @exception NoSuchMethodException if a matching method is not found - * or if the name is "<init>"or "<clinit>". - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the method - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * {@code name} and {@code parameterTypes} + * @throws NoSuchMethodException if a matching method is not found + * or if the name is "<init>"or "<clinit>". + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1816,26 +1733,15 @@ public final class Class implements java.io.Serializable, * * @param parameterTypes the parameter array * @return the {@code Constructor} object of the public constructor that - * matches the specified {@code parameterTypes} - * @exception NoSuchMethodException if a matching method is not found. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: - * - *
      - * - *
    • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.PUBLIC)} denies - * access to the constructor - * - *
    • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class - * - *
    + * matches the specified {@code parameterTypes} + * @throws NoSuchMethodException if a matching method is not found. + * @throws SecurityException + * If a security manager, s, is present and + * the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class. * * @since JDK1.1 */ @@ -1858,25 +1764,27 @@ public final class Class implements java.io.Serializable, * primitive type, an array class, or void. * * @return the array of {@code Class} objects representing all the - * declared members of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * declared members of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared classes within this class + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared classes within this class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -1899,26 +1807,28 @@ public final class Class implements java.io.Serializable, * *

    See The Java Language Specification, sections 8.2 and 8.3. * - * @return the array of {@code Field} objects representing all the - * declared fields of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the array of {@code Field} objects representing all the + * declared fields of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *

      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared fields within this class + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared fields within this class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -1945,26 +1855,28 @@ public final class Class implements java.io.Serializable, * *

    See The Java Language Specification, section 8.2. * - * @return the array of {@code Method} objects representing all the - * declared methods of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the array of {@code Method} objects representing all the + * declared methods of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *

      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared methods within this class + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared methods within this class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -1988,26 +1900,28 @@ public final class Class implements java.io.Serializable, * *

    See The Java Language Specification, section 8.2. * - * @return the array of {@code Constructor} objects representing all the - * declared constructors of this class - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the array of {@code Constructor} objects representing all the + * declared constructors of this class + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *

      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared constructors within this class + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared constructors within this class * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -2026,29 +1940,31 @@ public final class Class implements java.io.Serializable, * will not reflect the {@code length} field of an array class. * * @param name the name of the field - * @return the {@code Field} object for the specified field in this - * class - * @exception NoSuchFieldException if a field with the specified name is - * not found. - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the {@code Field} object for the specified field in this + * class + * @throws NoSuchFieldException if a field with the specified name is + * not found. + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared field + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared field * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -2080,28 +1996,30 @@ public final class Class implements java.io.Serializable, * * @param name the name of the method * @param parameterTypes the parameter array - * @return the {@code Method} object for the method of this class - * matching the specified name and parameters - * @exception NoSuchMethodException if a matching method is not found. - * @exception NullPointerException if {@code name} is {@code null} - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return the {@code Method} object for the method of this class + * matching the specified name and parameters + * @throws NoSuchMethodException if a matching method is not found. + * @throws NullPointerException if {@code name} is {@code null} + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared method + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared method * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -2129,27 +2047,29 @@ public final class Class implements java.io.Serializable, * include the explicit enclosing instance as the first parameter. * * @param parameterTypes the parameter array - * @return The {@code Constructor} object for the constructor with the - * specified parameter list - * @exception NoSuchMethodException if a matching method is not found. - * @exception SecurityException - * If a security manager, s, is present and any of the - * following conditions is met: + * @return The {@code Constructor} object for the constructor with the + * specified parameter list + * @throws NoSuchMethodException if a matching method is not found. + * @throws SecurityException + * If a security manager, s, is present and any of the + * following conditions is met: * - *
      + *
        * - *
      • invocation of - * {@link SecurityManager#checkMemberAccess - * s.checkMemberAccess(this, Member.DECLARED)} denies - * access to the declared constructor + *
      • the caller's class loader is not the same as the + * class loader of this class and invocation of + * {@link SecurityManager#checkPermission + * s.checkPermission} method with + * {@code RuntimePermission("accessDeclaredMembers")} + * denies access to the declared constructor * - *
      • the caller's class loader is not the same as or an - * ancestor of the class loader for the current class and - * invocation of {@link SecurityManager#checkPackageAccess - * s.checkPackageAccess()} denies access to the package - * of this class + *
      • the caller's class loader is not the same as or an + * ancestor of the class loader for the current class and + * invocation of {@link SecurityManager#checkPackageAccess + * s.checkPackageAccess()} denies access to the package + * of this class * - *
      + *
    * * @since JDK1.1 */ @@ -2306,14 +2226,6 @@ public final class Class implements java.io.Serializable, */ static native Class getPrimitiveClass(String name); - private static boolean isCheckMemberAccessOverridden(SecurityManager smgr) { - if (smgr.getClass() == SecurityManager.class) return false; - - Class[] paramTypes = new Class[] {Class.class, int.class}; - return smgr.getClass().getMethod0("checkMemberAccess", paramTypes). - getDeclaringClass() != SecurityManager.class; - } - /* * Check if client is allowed to access members. If access is denied, * throw a SecurityException. @@ -2326,19 +2238,17 @@ public final class Class implements java.io.Serializable, private void checkMemberAccess(int which, Class caller, boolean checkProxyInterfaces) { final SecurityManager s = System.getSecurityManager(); if (s != null) { + /* Default policy allows access to all {@link Member#PUBLIC} members, + * as well as access to classes that have the same class loader as the caller. + * In all other cases, it requires RuntimePermission("accessDeclaredMembers") + * permission. + */ final ClassLoader ccl = ClassLoader.getClassLoader(caller); final ClassLoader cl = getClassLoader0(); - if (!isCheckMemberAccessOverridden(s)) { - // Inlined SecurityManager.checkMemberAccess - if (which != Member.PUBLIC) { - if (ccl != cl) { - s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); - } + if (which != Member.PUBLIC) { + if (ccl != cl) { + s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); } - } else { - // Don't refactor; otherwise break the stack depth for - // checkMemberAccess of subclasses of SecurityManager as specified. - s.checkMemberAccess(this, which); } this.checkPackageAccess(ccl, checkProxyInterfaces); } @@ -2397,6 +2307,45 @@ public final class Class implements java.io.Serializable, return name; } + /** + * Atomic operations support. + */ + private static class Atomic { + // initialize Unsafe machinery here, since we need to call Class.class instance method + // and have to avoid calling it in the static initializer of the Class class... + private static final Unsafe unsafe = Unsafe.getUnsafe(); + // offset of Class.reflectionData instance field + private static final long reflectionDataOffset; + // offset of Class.annotationType instance field + private static final long annotationTypeOffset; + + static { + Field[] fields = Class.class.getDeclaredFields0(false); // bypass caches + reflectionDataOffset = objectFieldOffset(fields, "reflectionData"); + annotationTypeOffset = objectFieldOffset(fields, "annotationType"); + } + + private static long objectFieldOffset(Field[] fields, String fieldName) { + Field field = searchFields(fields, fieldName); + if (field == null) { + throw new Error("No " + fieldName + " field found in java.lang.Class"); + } + return unsafe.objectFieldOffset(field); + } + + static boolean casReflectionData(Class clazz, + SoftReference> oldData, + SoftReference> newData) { + return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData); + } + + static boolean casAnnotationType(Class clazz, + AnnotationType oldType, + AnnotationType newType) { + return unsafe.compareAndSwapObject(clazz, annotationTypeOffset, oldType, newType); + } + } + /** * Reflection support. */ @@ -2423,29 +2372,6 @@ public final class Class implements java.io.Serializable, ReflectionData(int redefinedCount) { this.redefinedCount = redefinedCount; } - - // initialize Unsafe machinery here, since we need to call Class.class instance method - // and have to avoid calling it in the static initializer of the Class class... - private static final Unsafe unsafe; - // offset of Class.reflectionData instance field - private static final long reflectionDataOffset; - - static { - unsafe = Unsafe.getUnsafe(); - // bypass caches - Field reflectionDataField = searchFields(Class.class.getDeclaredFields0(false), - "reflectionData"); - if (reflectionDataField == null) { - throw new Error("No reflectionData field found in java.lang.Class"); - } - reflectionDataOffset = unsafe.objectFieldOffset(reflectionDataField); - } - - static boolean compareAndSwap(Class clazz, - SoftReference> oldData, - SoftReference> newData) { - return unsafe.compareAndSwapObject(clazz, reflectionDataOffset, oldData, newData); - } } private volatile transient SoftReference> reflectionData; @@ -2477,7 +2403,7 @@ public final class Class implements java.io.Serializable, while (true) { ReflectionData rd = new ReflectionData<>(classRedefinedCount); // try to CAS it... - if (ReflectionData.compareAndSwap(this, oldReflectionData, new SoftReference<>(rd))) { + if (Atomic.casReflectionData(this, oldReflectionData, new SoftReference<>(rd))) { return rd; } // else retry @@ -2520,7 +2446,7 @@ public final class Class implements java.io.Serializable, } // Annotations handling - private native byte[] getRawAnnotations(); + native byte[] getRawAnnotations(); // Since 1.8 native byte[] getRawTypeAnnotations(); static byte[] getExecutableTypeAnnotationBytes(Executable ex) { @@ -3380,10 +3306,11 @@ public final class Class implements java.io.Serializable, // Annotation types cache their internal (AnnotationType) form - private AnnotationType annotationType; + @SuppressWarnings("UnusedDeclaration") + private volatile transient AnnotationType annotationType; - void setAnnotationType(AnnotationType type) { - annotationType = type; + boolean casAnnotationType(AnnotationType oldType, AnnotationType newType) { + return Atomic.casAnnotationType(this, oldType, newType); } AnnotationType getAnnotationType() { diff --git a/jdk/src/share/classes/java/lang/ClassLoader.java b/jdk/src/share/classes/java/lang/ClassLoader.java index f26eafd980a..c3f2aa20458 100644 --- a/jdk/src/share/classes/java/lang/ClassLoader.java +++ b/jdk/src/share/classes/java/lang/ClassLoader.java @@ -157,7 +157,7 @@ import sun.security.util.SecurityConstants; * } * * - *

    Binary names

    + *

    Binary names

    * *

    Any class name provided as a {@link String} parameter to methods in * ClassLoader must be a binary name as defined by @@ -342,7 +342,7 @@ public abstract class ClassLoader { * #loadClass(String, boolean)} method. It is invoked by the Java virtual * machine to resolve class references. Invoking this method is equivalent * to invoking {@link #loadClass(String, boolean) loadClass(name, - * false)}.

    + * false)}. * * @param name * The binary name of the class @@ -441,7 +441,7 @@ public abstract class ClassLoader { * behaves as follows. If this ClassLoader object is registered as * parallel capable, the method returns a dedicated object associated * with the specified class name. Otherwise, the method returns this - * ClassLoader object.

    + * ClassLoader object. * * @param className * The name of the to-be-loaded class @@ -506,7 +506,7 @@ public abstract class ClassLoader { * follow the delegation model for loading classes, and will be invoked by * the {@link #loadClass loadClass} method after checking the * parent class loader for the requested class. The default implementation - * throws a ClassNotFoundException.

    + * throws a ClassNotFoundException. * * @param name * The binary name of the class @@ -772,16 +772,16 @@ public abstract class ClassLoader { * bBuffer, pd) yields exactly the same * result as the statements * - *
    + *

    * ...
    - * byte[] temp = new byte[
    bBuffer.{@link + * byte[] temp = new byte[bBuffer.{@link * java.nio.ByteBuffer#remaining remaining}()];
    - *
    bBuffer.{@link java.nio.ByteBuffer#get(byte[]) + * bBuffer.{@link java.nio.ByteBuffer#get(byte[]) * get}(temp);
    * return {@link #defineClass(String, byte[], int, int, ProtectionDomain) - *
    cl.defineClass}(name, temp, 0, - * temp.length, pd);
    - *

    + * cl.defineClass}(name, temp, 0, + * temp.length, pd);
    + *

    * * @param name * The expected binary name. of the class, or @@ -940,7 +940,6 @@ public abstract class ClassLoader { * already been linked, then this method simply returns. Otherwise, the * class is linked as described in the "Execution" chapter of * The Java™ Language Specification. - *

    * * @param c * The class to link @@ -1012,7 +1011,7 @@ public abstract class ClassLoader { * Returns the class with the given binary name if this * loader has been recorded by the Java virtual machine as an initiating * loader of a class with that binary name. Otherwise - * null is returned.

    + * null is returned. * * @param name * The binary name of the class @@ -1032,7 +1031,7 @@ public abstract class ClassLoader { /** * Sets the signers of a class. This should be invoked after defining a - * class.

    + * class. * * @param c * The Class object @@ -1125,7 +1124,7 @@ public abstract class ClassLoader { /** * Finds the resource with the given name. Class loader implementations - * should override this method to specify where to find resources.

    + * should override this method to specify where to find resources. * * @param name * The resource name @@ -1143,7 +1142,7 @@ public abstract class ClassLoader { * Returns an enumeration of {@link java.net.URL URL} objects * representing all the resources with the given name. Class loader * implementations should override this method to specify where to load - * resources from.

    + * resources from. * * @param name * The resource name @@ -1161,14 +1160,16 @@ public abstract class ClassLoader { } /** - * Registers the caller as parallel capable.

    + * Registers the caller as parallel capable. * The registration succeeds if and only if all of the following - * conditions are met:
    - * 1. no instance of the caller has been created

    - * 2. all of the super classes (except class Object) of the caller are - * registered as parallel capable

    - * Note that once a class loader is registered as parallel capable, there - * is no way to change it back.

    + * conditions are met: + *
      + *
    1. no instance of the caller has been created
    2. + *
    3. all of the super classes (except class Object) of the caller are + * registered as parallel capable
    4. + *
    + *

    Note that once a class loader is registered as parallel capable, there + * is no way to change it back.

    * * @return true if the caller is successfully registered as * parallel capable and false if otherwise. @@ -1185,7 +1186,7 @@ public abstract class ClassLoader { /** * Find a resource of the specified name from the search path used to load * classes. This method locates the resource through the system class - * loader (see {@link #getSystemClassLoader()}).

    + * loader (see {@link #getSystemClassLoader()}). * * @param name * The resource name @@ -1292,7 +1293,7 @@ public abstract class ClassLoader { /** * Open for reading, a resource of the specified name from the search path * used to load classes. This method locates the resource through the - * system class loader (see {@link #getSystemClassLoader()}).

    + * system class loader (see {@link #getSystemClassLoader()}). * * @param name * The resource name @@ -1515,7 +1516,7 @@ public abstract class ClassLoader { * class loaders to define the packages for their classes. Packages must * be created before the class is defined, and package names must be * unique within a class loader and cannot be redefined or changed once - * created.

    + * created. * * @param name * The package name @@ -1572,7 +1573,7 @@ public abstract class ClassLoader { /** * Returns a Package that has been defined by this class loader - * or any of its ancestors.

    + * or any of its ancestors. * * @param name * The package name @@ -1609,7 +1610,7 @@ public abstract class ClassLoader { /** * Returns all of the Packages defined by this class loader and - * its ancestors.

    + * its ancestors. * * @return The array of Package objects defined by this * ClassLoader @@ -1646,7 +1647,7 @@ public abstract class ClassLoader { * method to locate the native libraries that belong to classes loaded with * this class loader. If this method returns null, the VM * searches the library along the path specified as the - * "java.library.path" property.

    + * "java.library.path" property. * * @param libname * The library name @@ -1966,7 +1967,7 @@ public abstract class ClassLoader { * in the future will have assertions enabled or disabled by default. * This setting may be overridden on a per-package or per-class basis by * invoking {@link #setPackageAssertionStatus(String, boolean)} or {@link - * #setClassAssertionStatus(String, boolean)}.

    + * #setClassAssertionStatus(String, boolean)}. * * @param enabled * true if classes loaded by this class loader will @@ -2068,7 +2069,6 @@ public abstract class ClassLoader { * status settings associated with the class loader. This method is * provided so that class loaders can be made to ignore any command line or * persistent assertion status settings and "start with a clean slate." - *

    * * @since 1.4 */ diff --git a/jdk/src/share/classes/java/lang/Double.java b/jdk/src/share/classes/java/lang/Double.java index 113cdf81a4c..1b1aece8122 100644 --- a/jdk/src/share/classes/java/lang/Double.java +++ b/jdk/src/share/classes/java/lang/Double.java @@ -256,7 +256,7 @@ public final class Double extends Number implements Comparable { * * *
    {@code '\t'} {@code U+0009}{@code HORIZONTAL TABULATION}
    {@code '\n'} {@code U+000A}
    - * + * * * * diff --git a/jdk/src/share/classes/java/lang/Float.java b/jdk/src/share/classes/java/lang/Float.java index 2f2b6b22444..e130e92314e 100644 --- a/jdk/src/share/classes/java/lang/Float.java +++ b/jdk/src/share/classes/java/lang/Float.java @@ -258,7 +258,7 @@ public final class Float extends Number implements Comparable { * * *

    Examples

    Examples
    Floating-point ValueHexadecimal String
    {@code 1.0} {@code 0x1.0p0}
    {@code -1.0} {@code -0x1.0p0}
    - * + * * * * diff --git a/jdk/src/share/classes/java/lang/Iterable.java b/jdk/src/share/classes/java/lang/Iterable.java index 8d46dbfe5ff..fe9086f6874 100644 --- a/jdk/src/share/classes/java/lang/Iterable.java +++ b/jdk/src/share/classes/java/lang/Iterable.java @@ -26,6 +26,8 @@ package java.lang; import java.util.Iterator; import java.util.Objects; +import java.util.Spliterator; +import java.util.Spliterators; import java.util.function.Consumer; /** @@ -72,5 +74,30 @@ public interface Iterable { action.accept(t); } } + + /** + * Creates a {@link Spliterator} over the elements described by this + * {@code Iterable}. + * + * @implSpec + * The default implementation creates an + * early-binding + * spliterator from the iterable's {@code Iterator}. The spliterator + * inherits the fail-fast properties of the iterable's iterator. + * + * @implNote + * The default implementation should usually be overridden. The + * spliterator returned by the default implementation has poor splitting + * capabilities, is unsized, and does not report any spliterator + * characteristics. Implementing classes can nearly always provide a + * better implementation. + * + * @return a {@code Spliterator} over the elements described by this + * {@code Iterable}. + * @since 1.8 + */ + default Spliterator spliterator() { + return Spliterators.spliteratorUnknownSize(iterator(), 0); + } } diff --git a/jdk/src/share/classes/java/lang/ProcessBuilder.java b/jdk/src/share/classes/java/lang/ProcessBuilder.java index b467f45c351..0cb7febe533 100644 --- a/jdk/src/share/classes/java/lang/ProcessBuilder.java +++ b/jdk/src/share/classes/java/lang/ProcessBuilder.java @@ -65,7 +65,7 @@ import java.util.Map; * working directory of the current process, usually the directory * named by the system property {@code user.dir}. * - *
  • a source of standard input. + *
  • a source of standard input. * By default, the subprocess reads input from a pipe. Java code * can access this pipe via the output stream returned by * {@link Process#getOutputStream()}. However, standard input may @@ -81,7 +81,7 @@ import java.util.Map; * * *
  • a destination for standard output - * and standard error. By default, the subprocess writes standard + * and standard error. By default, the subprocess writes standard * output and standard error to pipes. Java code can access these pipes * via the input streams returned by {@link Process#getInputStream()} and * {@link Process#getErrorStream()}. However, standard output and @@ -554,6 +554,7 @@ public final class ProcessBuilder * Redirect.from(file).type() == Redirect.Type.READ * } * + * @param file The {@code File} for the {@code Redirect}. * @throws NullPointerException if the specified file is null * @return a redirect to read from the specified file */ @@ -580,6 +581,7 @@ public final class ProcessBuilder * Redirect.to(file).type() == Redirect.Type.WRITE * } * + * @param file The {@code File} for the {@code Redirect}. * @throws NullPointerException if the specified file is null * @return a redirect to write to the specified file */ @@ -610,6 +612,7 @@ public final class ProcessBuilder * Redirect.appendTo(file).type() == Redirect.Type.APPEND * } * + * @param file The {@code File} for the {@code Redirect}. * @throws NullPointerException if the specified file is null * @return a redirect to append to the specified file */ diff --git a/jdk/src/share/classes/java/lang/Runtime.java b/jdk/src/share/classes/java/lang/Runtime.java index 5ff1aac0bce..9e53dc939ec 100644 --- a/jdk/src/share/classes/java/lang/Runtime.java +++ b/jdk/src/share/classes/java/lang/Runtime.java @@ -661,7 +661,7 @@ public class Runtime { /** * Returns the maximum amount of memory that the Java virtual machine will * attempt to use. If there is no inherent limit then the value {@link - * java.lang.Long#MAX_VALUE} will be returned.

    + * java.lang.Long#MAX_VALUE} will be returned. * * @return the maximum amount of memory that the virtual machine will * attempt to use, measured in bytes diff --git a/jdk/src/share/classes/java/lang/SecurityManager.java b/jdk/src/share/classes/java/lang/SecurityManager.java index ca187630528..34be905bd02 100644 --- a/jdk/src/share/classes/java/lang/SecurityManager.java +++ b/jdk/src/share/classes/java/lang/SecurityManager.java @@ -1675,10 +1675,18 @@ class SecurityManager { * permission to access members. * @exception NullPointerException if the clazz argument is * null. + * + * @deprecated This method relies on the caller being at a stack depth + * of 4 which is error-prone and cannot be enforced by the runtime. + * Users of this method should instead invoke {@link #checkPermission} + * directly. This method will be changed in a future release + * to check the permission {@code java.security.AllPermission}. + * * @see java.lang.reflect.Member * @since JDK1.1 * @see #checkPermission(java.security.Permission) checkPermission */ + @Deprecated @CallerSensitive public void checkMemberAccess(Class clazz, int which) { if (clazz == null) { diff --git a/jdk/src/share/classes/java/lang/System.java b/jdk/src/share/classes/java/lang/System.java index 52a5e0de823..79eb6434433 100644 --- a/jdk/src/share/classes/java/lang/System.java +++ b/jdk/src/share/classes/java/lang/System.java @@ -1220,12 +1220,15 @@ public final class System { public sun.reflect.ConstantPool getConstantPool(Class klass) { return klass.getConstantPool(); } - public void setAnnotationType(Class klass, AnnotationType type) { - klass.setAnnotationType(type); + public boolean casAnnotationType(Class klass, AnnotationType oldType, AnnotationType newType) { + return klass.casAnnotationType(oldType, newType); } public AnnotationType getAnnotationType(Class klass) { return klass.getAnnotationType(); } + public byte[] getRawClassAnnotations(Class klass) { + return klass.getRawAnnotations(); + } public byte[] getRawClassTypeAnnotations(Class klass) { return klass.getRawTypeAnnotations(); } diff --git a/jdk/src/share/classes/java/lang/Thread.java b/jdk/src/share/classes/java/lang/Thread.java index eb89670d149..d8a9ee2a582 100644 --- a/jdk/src/share/classes/java/lang/Thread.java +++ b/jdk/src/share/classes/java/lang/Thread.java @@ -865,8 +865,8 @@ class Thread implements Runnable { * will receive an {@link InterruptedException}. * *

    If this thread is blocked in an I/O operation upon an {@link - * java.nio.channels.InterruptibleChannel interruptible - * channel} then the channel will be closed, the thread's interrupt + * java.nio.channels.InterruptibleChannel InterruptibleChannel} + * then the channel will be closed, the thread's interrupt * status will be set, and the thread will receive a {@link * java.nio.channels.ClosedByInterruptException}. * @@ -1883,6 +1883,7 @@ class Thread implements Runnable { * there is no default. * @since 1.5 * @see #setDefaultUncaughtExceptionHandler + * @return the default uncaught exception handler for all threads */ public static UncaughtExceptionHandler getDefaultUncaughtExceptionHandler(){ return defaultUncaughtExceptionHandler; @@ -1895,6 +1896,7 @@ class Thread implements Runnable { * ThreadGroup object is returned, unless this thread * has terminated, in which case null is returned. * @since 1.5 + * @return the uncaught exception handler for this thread */ public UncaughtExceptionHandler getUncaughtExceptionHandler() { return uncaughtExceptionHandler != null ? diff --git a/jdk/src/share/classes/java/lang/ThreadLocal.java b/jdk/src/share/classes/java/lang/ThreadLocal.java index b337fc5f2e6..91d3df940d6 100644 --- a/jdk/src/share/classes/java/lang/ThreadLocal.java +++ b/jdk/src/share/classes/java/lang/ThreadLocal.java @@ -131,12 +131,13 @@ public class ThreadLocal { * Creates a thread local variable. The initial value of the variable is * determined by invoking the {@code get} method on the {@code Supplier}. * + * @param the type of the thread local's value * @param supplier the supplier to be used to determine the initial value * @return a new thread local variable * @throws NullPointerException if the specified supplier is null * @since 1.8 */ - public static ThreadLocal withInitial(Supplier supplier) { + public static ThreadLocal withInitial(Supplier supplier) { return new SuppliedThreadLocal<>(supplier); } diff --git a/jdk/src/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java b/jdk/src/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java index 892a9dd5316..79b3b69fcf3 100644 --- a/jdk/src/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java +++ b/jdk/src/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java @@ -24,24 +24,23 @@ */ package java.lang.invoke; -import java.io.Serializable; -import java.lang.reflect.Method; -import java.lang.reflect.Modifier; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; import sun.invoke.util.Wrapper; -import static sun.invoke.util.Wrapper.*; + +import static sun.invoke.util.Wrapper.forPrimitiveType; +import static sun.invoke.util.Wrapper.forWrapperType; +import static sun.invoke.util.Wrapper.isWrapperType; /** - * Abstract implementation of a lambda metafactory which provides parameter unrolling and input validation. + * Abstract implementation of a lambda metafactory which provides parameter + * unrolling and input validation. * * @see LambdaMetafactory */ /* package */ abstract class AbstractValidatingLambdaMetafactory { /* - * For context, the comments for the following fields are marked in quotes with their values, given this program: + * For context, the comments for the following fields are marked in quotes + * with their values, given this program: * interface II { Object foo(T x); } * interface JJ extends II { } * class CC { String impl(int i) { return "impl:"+i; }} @@ -54,9 +53,7 @@ import static sun.invoke.util.Wrapper.*; final Class targetClass; // The class calling the meta-factory via invokedynamic "class X" final MethodType invokedType; // The type of the invoked method "(CC)II" final Class samBase; // The type of the returned instance "interface JJ" - final MethodHandle samMethod; // Raw method handle for the functional interface method - final MethodHandleInfo samInfo; // Info about the SAM method handle "MethodHandleInfo[9 II.foo(Object)Object]" - final Class samClass; // Interface containing the SAM method "interface II" + final String samMethodName; // Name of the SAM method "foo" final MethodType samMethodType; // Type of the SAM method "(Object)Object" final MethodHandle implMethod; // Raw method handle for the implementation method final MethodHandleInfo implInfo; // Info about the implementation method handle "MethodHandleInfo[5 CC.impl(int)String]" @@ -67,44 +64,64 @@ import static sun.invoke.util.Wrapper.*; final MethodType instantiatedMethodType; // Instantiated erased functional interface method type "(Integer)Object" final boolean isSerializable; // Should the returned instance be serializable final Class[] markerInterfaces; // Additional marker interfaces to be implemented + final MethodType[] additionalBridges; // Signatures of additional methods to bridge /** * Meta-factory constructor. * - * @param caller Stacked automatically by VM; represents a lookup context with the accessibility privileges - * of the caller. - * @param invokedType Stacked automatically by VM; the signature of the invoked method, which includes the - * expected static type of the returned lambda object, and the static types of the captured - * arguments for the lambda. In the event that the implementation method is an instance method, - * the first argument in the invocation signature will correspond to the receiver. - * @param samMethod The primary method in the functional interface to which the lambda or method reference is - * being converted, represented as a method handle. - * @param implMethod The implementation method which should be called (with suitable adaptation of argument - * types, return types, and adjustment for captured arguments) when methods of the resulting - * functional interface instance are invoked. - * @param instantiatedMethodType The signature of the primary functional interface method after type variables - * are substituted with their instantiation from the capture site + * @param caller Stacked automatically by VM; represents a lookup context + * with the accessibility privileges of the caller. + * @param invokedType Stacked automatically by VM; the signature of the + * invoked method, which includes the expected static + * type of the returned lambda object, and the static + * types of the captured arguments for the lambda. In + * the event that the implementation method is an + * instance method, the first argument in the invocation + * signature will correspond to the receiver. + * @param samMethodName Name of the method in the functional interface to + * which the lambda or method reference is being + * converted, represented as a String. + * @param samMethodType Type of the method in the functional interface to + * which the lambda or method reference is being + * converted, represented as a MethodType. + * @param implMethod The implementation method which should be called + * (with suitable adaptation of argument types, return + * types, and adjustment for captured arguments) when + * methods of the resulting functional interface instance + * are invoked. + * @param instantiatedMethodType The signature of the primary functional + * interface method after type variables are + * substituted with their instantiation from + * the capture site + * @param isSerializable Should the lambda be made serializable? If set, + * either the target type or one of the additional SAM + * types must extend {@code Serializable}. + * @param markerInterfaces Additional interfaces which the lambda object + * should implement. + * @param additionalBridges Method types for additional signatures to be + * bridged to the implementation method * @throws ReflectiveOperationException - * @throws LambdaConversionException If any of the meta-factory protocol invariants are violated + * @throws LambdaConversionException If any of the meta-factory protocol + * invariants are violated */ AbstractValidatingLambdaMetafactory(MethodHandles.Lookup caller, MethodType invokedType, - MethodHandle samMethod, + String samMethodName, + MethodType samMethodType, MethodHandle implMethod, MethodType instantiatedMethodType, - int flags, - Class[] markerInterfaces) + boolean isSerializable, + Class[] markerInterfaces, + MethodType[] additionalBridges) throws ReflectiveOperationException, LambdaConversionException { this.targetClass = caller.lookupClass(); this.invokedType = invokedType; this.samBase = invokedType.returnType(); - this.samMethod = samMethod; - this.samInfo = new MethodHandleInfo(samMethod); - this.samClass = samInfo.getDeclaringClass(); - this.samMethodType = samInfo.getMethodType(); + this.samMethodName = samMethodName; + this.samMethodType = samMethodType; this.implMethod = implMethod; this.implInfo = new MethodHandleInfo(implMethod); @@ -118,32 +135,24 @@ import static sun.invoke.util.Wrapper.*; implKind == MethodHandleInfo.REF_invokeInterface; this.implDefiningClass = implInfo.getDeclaringClass(); this.implMethodType = implInfo.getMethodType(); - this.instantiatedMethodType = instantiatedMethodType; + this.isSerializable = isSerializable; + this.markerInterfaces = markerInterfaces; + this.additionalBridges = additionalBridges; - if (!samClass.isInterface()) { + if (!samBase.isInterface()) { throw new LambdaConversionException(String.format( "Functional interface %s is not an interface", - samClass.getName())); + samBase.getName())); } - boolean foundSerializableSupertype = Serializable.class.isAssignableFrom(samBase); for (Class c : markerInterfaces) { if (!c.isInterface()) { throw new LambdaConversionException(String.format( "Marker interface %s is not an interface", c.getName())); } - foundSerializableSupertype |= Serializable.class.isAssignableFrom(c); } - this.isSerializable = ((flags & LambdaMetafactory.FLAG_SERIALIZABLE) != 0) - || foundSerializableSupertype; - - if (isSerializable && !foundSerializableSupertype) { - markerInterfaces = Arrays.copyOf(markerInterfaces, markerInterfaces.length + 1); - markerInterfaces[markerInterfaces.length-1] = Serializable.class; - } - this.markerInterfaces = markerInterfaces; } /** @@ -153,20 +162,14 @@ import static sun.invoke.util.Wrapper.*; * functional interface * @throws ReflectiveOperationException */ - abstract CallSite buildCallSite() throws ReflectiveOperationException, LambdaConversionException; + abstract CallSite buildCallSite() + throws ReflectiveOperationException, LambdaConversionException; /** * Check the meta-factory arguments for errors * @throws LambdaConversionException if there are improper conversions */ void validateMetafactoryArgs() throws LambdaConversionException { - // Check target type is a subtype of class where SAM method is defined - if (!samClass.isAssignableFrom(samBase)) { - throw new LambdaConversionException( - String.format("Invalid target type %s for lambda conversion; not a subtype of functional interface %s", - samBase.getName(), samClass.getName())); - } - switch (implKind) { case MethodHandleInfo.REF_invokeInterface: case MethodHandleInfo.REF_invokeVirtual: @@ -265,9 +268,9 @@ import static sun.invoke.util.Wrapper.*; } /** - * Check type adaptability - * @param fromType - * @param toType + * Check type adaptability for parameter types. + * @param fromType Type to convert from + * @param toType Type to convert to * @param strict If true, do strict checks, else allow that fromType may be parameterized * @return True if 'fromType' can be passed to an argument of 'toType' */ @@ -299,15 +302,14 @@ import static sun.invoke.util.Wrapper.*; } } else { // both are reference types: fromType should be a superclass of toType. - return strict? toType.isAssignableFrom(fromType) : true; + return !strict || toType.isAssignableFrom(fromType); } } } /** - * Check type adaptability for return types -- special handling of void type) and parameterized fromType - * @param fromType - * @param toType + * Check type adaptability for return types -- + * special handling of void type) and parameterized fromType * @return True if 'fromType' can be converted to 'toType' */ private boolean isAdaptableToAsReturn(Class fromType, Class toType) { @@ -338,89 +340,4 @@ import static sun.invoke.util.Wrapper.*; } ***********************/ - /** - * Find the functional interface method and corresponding abstract methods - * which should be bridged. The functional interface method and those to be - * bridged will have the same name and number of parameters. Check for - * matching default methods (non-abstract), the VM will create bridges for - * default methods; We don't have enough readily available type information - * to distinguish between where the functional interface method should be - * bridged and where the default method should be bridged; This situation is - * flagged. - */ - class MethodAnalyzer { - private final Method[] methods = samBase.getMethods(); - - private Method samMethod = null; - private final List methodsToBridge = new ArrayList<>(methods.length); - private boolean conflictFoundBetweenDefaultAndBridge = false; - - MethodAnalyzer() { - String samMethodName = samInfo.getName(); - Class[] samParamTypes = samMethodType.parameterArray(); - int samParamLength = samParamTypes.length; - Class samReturnType = samMethodType.returnType(); - Class objectClass = Object.class; - List defaultMethods = new ArrayList<>(methods.length); - - for (Method m : methods) { - if (m.getName().equals(samMethodName) && m.getDeclaringClass() != objectClass) { - Class[] mParamTypes = m.getParameterTypes(); - if (mParamTypes.length == samParamLength) { - // Method matches name and parameter length -- and is not Object - if (Modifier.isAbstract(m.getModifiers())) { - // Method is abstract - if (m.getReturnType().equals(samReturnType) - && Arrays.equals(mParamTypes, samParamTypes)) { - // Exact match, this is the SAM method signature - samMethod = m; - } else if (!hasMatchingBridgeSignature(m)) { - // Record bridges, exclude methods with duplicate signatures - methodsToBridge.add(m); - } - } else { - // Record default methods for conflict testing - defaultMethods.add(m); - } - } - } - } - for (Method dm : defaultMethods) { - if (hasMatchingBridgeSignature(dm)) { - conflictFoundBetweenDefaultAndBridge = true; - break; - } - } - } - - Method getSamMethod() { - return samMethod; - } - - List getMethodsToBridge() { - return methodsToBridge; - } - - boolean conflictFoundBetweenDefaultAndBridge() { - return conflictFoundBetweenDefaultAndBridge; - } - - /** - * Search the list of previously found bridge methods to determine if there is a method with the same signature - * (return and parameter types) as the specified method. - * - * @param m The method to match - * @return True if the method was found, False otherwise - */ - private boolean hasMatchingBridgeSignature(Method m) { - Class[] ptypes = m.getParameterTypes(); - Class rtype = m.getReturnType(); - for (Method md : methodsToBridge) { - if (md.getReturnType().equals(rtype) && Arrays.equals(ptypes, md.getParameterTypes())) { - return true; - } - } - return false; - } - } } diff --git a/jdk/src/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java b/jdk/src/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java index 0b6f4016b1d..f74678e1bae 100644 --- a/jdk/src/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java +++ b/jdk/src/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java @@ -25,22 +25,26 @@ package java.lang.invoke; -import java.lang.reflect.Constructor; -import java.lang.reflect.Method; -import java.security.ProtectionDomain; -import java.util.concurrent.atomic.AtomicInteger; import jdk.internal.org.objectweb.asm.*; -import static jdk.internal.org.objectweb.asm.Opcodes.*; import sun.misc.Unsafe; + +import java.lang.reflect.Constructor; import java.security.AccessController; import java.security.PrivilegedAction; +import java.security.ProtectionDomain; +import java.util.concurrent.atomic.AtomicInteger; + +import static jdk.internal.org.objectweb.asm.Opcodes.*; /** - * Lambda metafactory implementation which dynamically creates an inner-class-like class per lambda callsite. + * Lambda metafactory implementation which dynamically creates an + * inner-class-like class per lambda callsite. * * @see LambdaMetafactory */ /* package */ final class InnerClassLambdaMetafactory extends AbstractValidatingLambdaMetafactory { + private static final Unsafe UNSAFE = Unsafe.getUnsafe(); + private static final int CLASSFILE_VERSION = 51; private static final String METHOD_DESCRIPTOR_VOID = Type.getMethodDescriptor(Type.VOID_TYPE); private static final String NAME_MAGIC_ACCESSOR_IMPL = "java/lang/invoke/MagicLambdaImpl"; @@ -54,7 +58,7 @@ import java.security.PrivilegedAction; private static final String DESCR_CTOR_SERIALIZED_LAMBDA = MethodType.methodType(void.class, Class.class, - int.class, String.class, String.class, String.class, + String.class, String.class, String.class, int.class, String.class, String.class, String.class, String.class, Object[].class).toMethodDescriptorString(); @@ -77,36 +81,56 @@ import java.security.PrivilegedAction; private final Type[] instantiatedArgumentTypes; // ASM types for the functional interface arguments /** - * General meta-factory constructor, standard cases and allowing for uncommon options such as serialization. + * General meta-factory constructor, supporting both standard cases and + * allowing for uncommon options such as serialization or bridging. * - * @param caller Stacked automatically by VM; represents a lookup context with the accessibility privileges - * of the caller. - * @param invokedType Stacked automatically by VM; the signature of the invoked method, which includes the - * expected static type of the returned lambda object, and the static types of the captured - * arguments for the lambda. In the event that the implementation method is an instance method, - * the first argument in the invocation signature will correspond to the receiver. - * @param samMethod The primary method in the functional interface to which the lambda or method reference is - * being converted, represented as a method handle. - * @param implMethod The implementation method which should be called (with suitable adaptation of argument - * types, return types, and adjustment for captured arguments) when methods of the resulting - * functional interface instance are invoked. - * @param instantiatedMethodType The signature of the primary functional interface method after type variables - * are substituted with their instantiation from the capture site - * @param flags A bitmask containing flags that may influence the translation of this lambda expression. Defined - * fields include FLAG_SERIALIZABLE. - * @param markerInterfaces Additional interfaces which the lambda object should implement. + * @param caller Stacked automatically by VM; represents a lookup context + * with the accessibility privileges of the caller. + * @param invokedType Stacked automatically by VM; the signature of the + * invoked method, which includes the expected static + * type of the returned lambda object, and the static + * types of the captured arguments for the lambda. In + * the event that the implementation method is an + * instance method, the first argument in the invocation + * signature will correspond to the receiver. + * @param samMethodName Name of the method in the functional interface to + * which the lambda or method reference is being + * converted, represented as a String. + * @param samMethodType Type of the method in the functional interface to + * which the lambda or method reference is being + * converted, represented as a MethodType. + * @param implMethod The implementation method which should be called (with + * suitable adaptation of argument types, return types, + * and adjustment for captured arguments) when methods of + * the resulting functional interface instance are invoked. + * @param instantiatedMethodType The signature of the primary functional + * interface method after type variables are + * substituted with their instantiation from + * the capture site + * @param isSerializable Should the lambda be made serializable? If set, + * either the target type or one of the additional SAM + * types must extend {@code Serializable}. + * @param markerInterfaces Additional interfaces which the lambda object + * should implement. + * @param additionalBridges Method types for additional signatures to be + * bridged to the implementation method * @throws ReflectiveOperationException - * @throws LambdaConversionException If any of the meta-factory protocol invariants are violated + * @throws LambdaConversionException If any of the meta-factory protocol + * invariants are violated */ public InnerClassLambdaMetafactory(MethodHandles.Lookup caller, MethodType invokedType, - MethodHandle samMethod, + String samMethodName, + MethodType samMethodType, MethodHandle implMethod, MethodType instantiatedMethodType, - int flags, - Class[] markerInterfaces) + boolean isSerializable, + Class[] markerInterfaces, + MethodType[] additionalBridges) throws ReflectiveOperationException, LambdaConversionException { - super(caller, invokedType, samMethod, implMethod, instantiatedMethodType, flags, markerInterfaces); + super(caller, invokedType, samMethodName, samMethodType, + implMethod, instantiatedMethodType, + isSerializable, markerInterfaces, additionalBridges); implMethodClassName = implDefiningClass.getName().replace('.', '/'); implMethodName = implInfo.getName(); implMethodDesc = implMethodType.toMethodDescriptorString(); @@ -124,7 +148,8 @@ import java.security.PrivilegedAction; for (int i = 0; i < argTypes.length; i++) { argNames[i] = "arg$" + (i + 1); } - instantiatedArgumentTypes = Type.getArgumentTypes(instantiatedMethodType.toMethodDescriptorString()); + instantiatedArgumentTypes = Type.getArgumentTypes( + instantiatedMethodType.toMethodDescriptorString()); } /** @@ -136,7 +161,8 @@ import java.security.PrivilegedAction; * @return a CallSite, which, when invoked, will return an instance of the * functional interface * @throws ReflectiveOperationException - * @throws LambdaConversionException If properly formed functional interface is not found + * @throws LambdaConversionException If properly formed functional interface + * is not found */ @Override CallSite buildCallSite() throws ReflectiveOperationException, LambdaConversionException { @@ -167,8 +193,8 @@ import java.security.PrivilegedAction; } else { return new ConstantCallSite( MethodHandles.Lookup.IMPL_LOOKUP - .findConstructor(innerClass, constructorType) - .asType(constructorType.changeReturnType(samBase))); + .findConstructor(innerClass, constructorType) + .asType(constructorType.changeReturnType(samBase))); } } @@ -176,13 +202,20 @@ import java.security.PrivilegedAction; * Generate a class file which implements the functional * interface, define and return the class. * + * @implNote The class that is generated does not include signature + * information for exceptions that may be present on the SAM method. + * This is to reduce classfile size, and is harmless as checked exceptions + * are erased anyway, no one will ever compile against this classfile, + * and we make no guarantees about the reflective properties of lambda + * objects. + * * @return a Class which implements the functional interface - * @throws LambdaConversionException If properly formed functional interface is not found + * @throws LambdaConversionException If properly formed functional interface + * is not found */ private Class spinInnerClass() throws LambdaConversionException { - String samName = samBase.getName().replace('.', '/'); String[] interfaces = new String[markerInterfaces.length + 1]; - interfaces[0] = samName; + interfaces[0] = samBase.getName().replace('.', '/'); for (int i=0; i) Unsafe.getUnsafe().defineClass(lambdaClassName, classBytes, 0, classBytes.length, - loader, pd); + return UNSAFE.defineClass(lambdaClassName, + classBytes, 0, classBytes.length, + loader, pd); } /** @@ -258,19 +293,23 @@ import java.security.PrivilegedAction; */ private void generateConstructor() { // Generate constructor - MethodVisitor ctor = cw.visitMethod(ACC_PRIVATE, NAME_CTOR, constructorDesc, null, null); + MethodVisitor ctor = cw.visitMethod(ACC_PRIVATE, NAME_CTOR, + constructorDesc, null, null); ctor.visitCode(); ctor.visitVarInsn(ALOAD, 0); - ctor.visitMethodInsn(INVOKESPECIAL, NAME_MAGIC_ACCESSOR_IMPL, NAME_CTOR, METHOD_DESCRIPTOR_VOID); + ctor.visitMethodInsn(INVOKESPECIAL, NAME_MAGIC_ACCESSOR_IMPL, NAME_CTOR, + METHOD_DESCRIPTOR_VOID); int lvIndex = 0; for (int i = 0; i < argTypes.length; i++) { ctor.visitVarInsn(ALOAD, 0); ctor.visitVarInsn(argTypes[i].getOpcode(ILOAD), lvIndex + 1); lvIndex += argTypes[i].getSize(); - ctor.visitFieldInsn(PUTFIELD, lambdaClassName, argNames[i], argTypes[i].getDescriptor()); + ctor.visitFieldInsn(PUTFIELD, lambdaClassName, argNames[i], + argTypes[i].getDescriptor()); } ctor.visitInsn(RETURN); - ctor.visitMaxs(-1, -1); // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored + // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored + ctor.visitMaxs(-1, -1); ctor.visitEnd(); } @@ -279,18 +318,18 @@ import java.security.PrivilegedAction; */ private void generateWriteReplace() { TypeConvertingMethodAdapter mv - = new TypeConvertingMethodAdapter(cw.visitMethod(ACC_PRIVATE + ACC_FINAL, - NAME_METHOD_WRITE_REPLACE, DESCR_METHOD_WRITE_REPLACE, - null, null)); + = new TypeConvertingMethodAdapter( + cw.visitMethod(ACC_PRIVATE + ACC_FINAL, + NAME_METHOD_WRITE_REPLACE, DESCR_METHOD_WRITE_REPLACE, + null, null)); mv.visitCode(); mv.visitTypeInsn(NEW, NAME_SERIALIZED_LAMBDA); - mv.visitInsn(DUP);; + mv.visitInsn(DUP); mv.visitLdcInsn(Type.getType(targetClass)); - mv.visitLdcInsn(samInfo.getReferenceKind()); mv.visitLdcInsn(invokedType.returnType().getName().replace('.', '/')); - mv.visitLdcInsn(samInfo.getName()); - mv.visitLdcInsn(samInfo.getMethodType().toMethodDescriptorString()); + mv.visitLdcInsn(samMethodName); + mv.visitLdcInsn(samMethodType.toMethodDescriptorString()); mv.visitLdcInsn(implInfo.getReferenceKind()); mv.visitLdcInsn(implInfo.getDeclaringClass().getName().replace('.', '/')); mv.visitLdcInsn(implInfo.getName()); @@ -303,35 +342,19 @@ import java.security.PrivilegedAction; mv.visitInsn(DUP); mv.iconst(i); mv.visitVarInsn(ALOAD, 0); - mv.visitFieldInsn(GETFIELD, lambdaClassName, argNames[i], argTypes[i].getDescriptor()); + mv.visitFieldInsn(GETFIELD, lambdaClassName, argNames[i], + argTypes[i].getDescriptor()); mv.boxIfTypePrimitive(argTypes[i]); mv.visitInsn(AASTORE); } mv.visitMethodInsn(INVOKESPECIAL, NAME_SERIALIZED_LAMBDA, NAME_CTOR, DESCR_CTOR_SERIALIZED_LAMBDA); mv.visitInsn(ARETURN); - mv.visitMaxs(-1, -1); // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored + // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored + mv.visitMaxs(-1, -1); mv.visitEnd(); } - /** - * Generate a method which calls the lambda implementation method, - * converting arguments, as needed. - * @param m The method whose signature should be generated - * @param isBridge True if this methods should be flagged as a bridge - */ - private void generateForwardingMethod(Method m, boolean isBridge) { - Class[] exceptionTypes = m.getExceptionTypes(); - String[] exceptionNames = new String[exceptionTypes.length]; - for (int i = 0; i < exceptionTypes.length; i++) { - exceptionNames[i] = exceptionTypes[i].getName().replace('.', '/'); - } - String methodDescriptor = Type.getMethodDescriptor(m); - int access = isBridge? ACC_PUBLIC | ACC_BRIDGE : ACC_PUBLIC; - MethodVisitor mv = cw.visitMethod(access, m.getName(), methodDescriptor, null, exceptionNames); - new ForwardingMethodGenerator(mv).generate(m); - } - /** * This class generates a method body which calls the lambda implementation * method, converting arguments, as needed. @@ -342,36 +365,39 @@ import java.security.PrivilegedAction; super(mv); } - void generate(Method m) throws InternalError { + void generate(String methodDescriptor) { visitCode(); if (implKind == MethodHandleInfo.REF_newInvokeSpecial) { visitTypeInsn(NEW, implMethodClassName); - visitInsn(DUP);; + visitInsn(DUP); } for (int i = 0; i < argTypes.length; i++) { visitVarInsn(ALOAD, 0); - visitFieldInsn(GETFIELD, lambdaClassName, argNames[i], argTypes[i].getDescriptor()); + visitFieldInsn(GETFIELD, lambdaClassName, argNames[i], + argTypes[i].getDescriptor()); } - convertArgumentTypes(Type.getArgumentTypes(m)); + convertArgumentTypes(Type.getArgumentTypes(methodDescriptor)); // Invoke the method we want to forward to visitMethodInsn(invocationOpcode(), implMethodClassName, implMethodName, implMethodDesc); // Convert the return value (if any) and return it - // Note: if adapting from non-void to void, the 'return' instruction will pop the unneeded result - Type samReturnType = Type.getReturnType(m); + // Note: if adapting from non-void to void, the 'return' + // instruction will pop the unneeded result + Type samReturnType = Type.getReturnType(methodDescriptor); convertType(implMethodReturnType, samReturnType, samReturnType); visitInsn(samReturnType.getOpcode(Opcodes.IRETURN)); - - visitMaxs(-1, -1); // Maxs computed by ClassWriter.COMPUTE_MAXS, these arguments ignored + // Maxs computed by ClassWriter.COMPUTE_MAXS,these arguments ignored + visitMaxs(-1, -1); visitEnd(); } private void convertArgumentTypes(Type[] samArgumentTypes) { int lvIndex = 0; - boolean samIncludesReceiver = implIsInstanceMethod && argTypes.length == 0; + boolean samIncludesReceiver = implIsInstanceMethod && + argTypes.length == 0; int samReceiverLength = samIncludesReceiver ? 1 : 0; if (samIncludesReceiver) { // push receiver @@ -395,7 +421,9 @@ import java.security.PrivilegedAction; } private void convertType(Type argType, Type targetType, Type functionalType) { - convertType(argType.getDescriptor(), targetType.getDescriptor(), functionalType.getDescriptor()); + convertType(argType.getDescriptor(), + targetType.getDescriptor(), + functionalType.getDescriptor()); } private int invocationOpcode() throws InternalError { diff --git a/jdk/src/share/classes/java/lang/invoke/LambdaMetafactory.java b/jdk/src/share/classes/java/lang/invoke/LambdaMetafactory.java index e03dda002d1..87c7923d9ba 100644 --- a/jdk/src/share/classes/java/lang/invoke/LambdaMetafactory.java +++ b/jdk/src/share/classes/java/lang/invoke/LambdaMetafactory.java @@ -25,6 +25,9 @@ package java.lang.invoke; +import java.io.Serializable; +import java.util.Arrays; + /** *

    Bootstrap methods for converting lambda expressions and method references to functional interface objects.

    * @@ -44,16 +47,11 @@ package java.lang.invoke; * *

    When parameterized types are used, the instantiated type of the functional interface method may be different * from that in the functional interface. For example, consider - * interface I<T> { int m(T x); } if this functional interface type is used in a lambda - * I<Byte> v = ..., we need both the actual functional interface method which has the signature - * (Object)int and the erased instantiated type of the functional interface method (or simply + * {@code interface I { int m(T x); }} if this functional interface type is used in a lambda + * {@code I; v = ...}, we need both the actual functional interface method which has the signature + * {@code (Object)int} and the erased instantiated type of the functional interface method (or simply * instantiated method type), which has signature - * (Byte)int. - * - *

    While functional interfaces only have a single abstract method from the language perspective (concrete - * methods in Object are and default methods may be present), at the bytecode level they may actually have multiple - * methods because of the need for bridge methods. Invoking any of these methods on the lambda object will result - * in invoking the implementation method. + * {@code (Byte)int}. * *

    The argument list of the implementation method and the argument list of the functional interface method(s) * may differ in several ways. The implementation methods may have additional arguments to accommodate arguments @@ -137,108 +135,147 @@ package java.lang.invoke; *

  • *

    Examples

    Examples
    Floating-point ValueHexadecimal String
    {@code 1.0} {@code 0x1.0p0}
    {@code -1.0} {@code -0x1.0p0}
    * - * The default bootstrap ({@link #metaFactory}) represents the common cases and uses an optimized protocol. - * Alternate bootstraps (e.g., {@link #altMetaFactory}) exist to support uncommon cases such as serialization + * The default bootstrap ({@link #metafactory}) represents the common cases and uses an optimized protocol. + * Alternate bootstraps (e.g., {@link #altMetafactory}) exist to support uncommon cases such as serialization * or additional marker superinterfaces. * */ public class LambdaMetafactory { - /** Flag for alternate metafactories indicating the lambda object is must to be serializable */ + /** Flag for alternate metafactories indicating the lambda object is + * must to be serializable */ public static final int FLAG_SERIALIZABLE = 1 << 0; /** - * Flag for alternate metafactories indicating the lambda object implements other marker interfaces + * Flag for alternate metafactories indicating the lambda object implements + * other marker interfaces * besides Serializable */ public static final int FLAG_MARKERS = 1 << 1; + /** + * Flag for alternate metafactories indicating the lambda object requires + * additional bridge methods + */ + public static final int FLAG_BRIDGES = 1 << 2; + private static final Class[] EMPTY_CLASS_ARRAY = new Class[0]; + private static final MethodType[] EMPTY_MT_ARRAY = new MethodType[0]; /** - * Standard meta-factory for conversion of lambda expressions or method references to functional interfaces. + * Standard meta-factory for conversion of lambda expressions or method + * references to functional interfaces. * - * @param caller Stacked automatically by VM; represents a lookup context with the accessibility privileges - * of the caller. - * @param invokedName Stacked automatically by VM; the name of the invoked method as it appears at the call site. - * Currently unused. - * @param invokedType Stacked automatically by VM; the signature of the invoked method, which includes the - * expected static type of the returned lambda object, and the static types of the captured - * arguments for the lambda. In the event that the implementation method is an instance method, - * the first argument in the invocation signature will correspond to the receiver. - * @param samMethod The primary method in the functional interface to which the lambda or method reference is - * being converted, represented as a method handle. - * @param implMethod The implementation method which should be called (with suitable adaptation of argument - * types, return types, and adjustment for captured arguments) when methods of the resulting - * functional interface instance are invoked. - * @param instantiatedMethodType The signature of the primary functional interface method after type variables - * are substituted with their instantiation from the capture site - * @return a CallSite, which, when invoked, will return an instance of the functional interface - * @throws ReflectiveOperationException if the caller is not able to reconstruct one of the method handles - * @throws LambdaConversionException If any of the meta-factory protocol invariants are violated + * @param caller Stacked automatically by VM; represents a lookup context + * with the accessibility privileges of the caller. + * @param invokedName Stacked automatically by VM; the name of the invoked + * method as it appears at the call site. + * Used as the name of the functional interface method + * to which the lambda or method reference is being + * converted. + * @param invokedType Stacked automatically by VM; the signature of the + * invoked method, which includes the expected static + * type of the returned lambda object, and the static + * types of the captured arguments for the lambda. + * In the event that the implementation method is an + * instance method, the first argument in the invocation + * signature will correspond to the receiver. + * @param samMethodType MethodType of the method in the functional interface + * to which the lambda or method reference is being + * converted, represented as a MethodType. + * @param implMethod The implementation method which should be called + * (with suitable adaptation of argument types, return + * types, and adjustment for captured arguments) when + * methods of the resulting functional interface instance + * are invoked. + * @param instantiatedMethodType The signature of the primary functional + * interface method after type variables + * are substituted with their instantiation + * from the capture site + * @return a CallSite, which, when invoked, will return an instance of the + * functional interface + * @throws ReflectiveOperationException if the caller is not able to + * reconstruct one of the method handles + * @throws LambdaConversionException If any of the meta-factory protocol + * invariants are violated */ - public static CallSite metaFactory(MethodHandles.Lookup caller, + public static CallSite metafactory(MethodHandles.Lookup caller, String invokedName, MethodType invokedType, - MethodHandle samMethod, + MethodType samMethodType, MethodHandle implMethod, MethodType instantiatedMethodType) throws ReflectiveOperationException, LambdaConversionException { AbstractValidatingLambdaMetafactory mf; - mf = new InnerClassLambdaMetafactory(caller, invokedType, samMethod, implMethod, instantiatedMethodType, - 0, EMPTY_CLASS_ARRAY); + mf = new InnerClassLambdaMetafactory(caller, invokedType, + invokedName, samMethodType, + implMethod, instantiatedMethodType, + false, EMPTY_CLASS_ARRAY, EMPTY_MT_ARRAY); mf.validateMetafactoryArgs(); return mf.buildCallSite(); } /** - * Alternate meta-factory for conversion of lambda expressions or method references to functional interfaces, - * which supports serialization and other uncommon options. + * Alternate meta-factory for conversion of lambda expressions or method + * references to functional interfaces, which supports serialization and + * other uncommon options. * * The declared argument list for this method is: * - * CallSite altMetaFactory(MethodHandles.Lookup caller, + * CallSite altMetafactory(MethodHandles.Lookup caller, * String invokedName, * MethodType invokedType, * Object... args) * * but it behaves as if the argument list is: * - * CallSite altMetaFactory(MethodHandles.Lookup caller, + * CallSite altMetafactory(MethodHandles.Lookup caller, * String invokedName, * MethodType invokedType, - * MethodHandle samMethod + * MethodType samMethodType * MethodHandle implMethod, * MethodType instantiatedMethodType, * int flags, * int markerInterfaceCount, // IF flags has MARKERS set * Class... markerInterfaces // IF flags has MARKERS set + * int bridgeCount, // IF flags has BRIDGES set + * MethodType... bridges // IF flags has BRIDGES set * ) * * - * @param caller Stacked automatically by VM; represents a lookup context with the accessibility privileges - * of the caller. - * @param invokedName Stacked automatically by VM; the name of the invoked method as it appears at the call site. - * Currently unused. - * @param invokedType Stacked automatically by VM; the signature of the invoked method, which includes thefu - * expected static type of the returned lambda object, and the static types of the captured - * arguments for the lambda. In the event that the implementation method is an instance method, - * the first argument in the invocation signature will correspond to the receiver. - * @param args argument to pass, flags, marker interface count, and marker interfaces as described above - * @return a CallSite, which, when invoked, will return an instance of the functional interface - * @throws ReflectiveOperationException if the caller is not able to reconstruct one of the method handles - * @throws LambdaConversionException If any of the meta-factory protocol invariants are violated + * @param caller Stacked automatically by VM; represents a lookup context + * with the accessibility privileges of the caller. + * @param invokedName Stacked automatically by VM; the name of the invoked + * method as it appears at the call site. + * Used as the name of the functional interface method + * to which the lambda or method reference is being + * converted. + * @param invokedType Stacked automatically by VM; the signature of the + * invoked method, which includes the expected static + * type of the returned lambda object, and the static + * types of the captured arguments for the lambda. + * In the event that the implementation method is an + * instance method, the first argument in the invocation + * signature will correspond to the receiver. + * @param args flags and optional arguments, as described above + * @return a CallSite, which, when invoked, will return an instance of the + * functional interface + * @throws ReflectiveOperationException if the caller is not able to + * reconstruct one of the method handles + * @throws LambdaConversionException If any of the meta-factory protocol + * invariants are violated */ - public static CallSite altMetaFactory(MethodHandles.Lookup caller, + public static CallSite altMetafactory(MethodHandles.Lookup caller, String invokedName, MethodType invokedType, Object... args) throws ReflectiveOperationException, LambdaConversionException { - MethodHandle samMethod = (MethodHandle)args[0]; + MethodType samMethodType = (MethodType)args[0]; MethodHandle implMethod = (MethodHandle)args[1]; MethodType instantiatedMethodType = (MethodType)args[2]; int flags = (Integer) args[3]; Class[] markerInterfaces; + MethodType[] bridges; int argIndex = 4; if ((flags & FLAG_MARKERS) != 0) { int markerCount = (Integer) args[argIndex++]; @@ -248,9 +285,33 @@ public class LambdaMetafactory { } else markerInterfaces = EMPTY_CLASS_ARRAY; - AbstractValidatingLambdaMetafactory mf; - mf = new InnerClassLambdaMetafactory(caller, invokedType, samMethod, implMethod, instantiatedMethodType, - flags, markerInterfaces); + if ((flags & FLAG_BRIDGES) != 0) { + int bridgeCount = (Integer) args[argIndex++]; + bridges = new MethodType[bridgeCount]; + System.arraycopy(args, argIndex, bridges, 0, bridgeCount); + argIndex += bridgeCount; + } + else + bridges = EMPTY_MT_ARRAY; + + boolean foundSerializableSupertype = Serializable.class.isAssignableFrom(invokedType.returnType()); + for (Class c : markerInterfaces) + foundSerializableSupertype |= Serializable.class.isAssignableFrom(c); + boolean isSerializable = ((flags & LambdaMetafactory.FLAG_SERIALIZABLE) != 0) + || foundSerializableSupertype; + + if (isSerializable && !foundSerializableSupertype) { + markerInterfaces = Arrays.copyOf(markerInterfaces, markerInterfaces.length + 1); + markerInterfaces[markerInterfaces.length-1] = Serializable.class; + } + + AbstractValidatingLambdaMetafactory mf + = new InnerClassLambdaMetafactory(caller, invokedType, + invokedName, samMethodType, + implMethod, + instantiatedMethodType, + isSerializable, + markerInterfaces, bridges); mf.validateMetafactoryArgs(); return mf.buildCallSite(); } diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java index 8efbda80614..04eda964966 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandleImpl.java @@ -747,7 +747,8 @@ import static java.lang.invoke.MethodHandles.Lookup.IMPL_LOOKUP; GuardWithCatch gguard = new GuardWithCatch(gtarget, exType, gcatcher); if (gtarget == null || gcatcher == null) throw new InternalError(); MethodHandle ginvoker = GuardWithCatch.VARARGS_INVOKE.bindReceiver(gguard); - return makeCollectArguments(ginvoker, ValueConversions.varargsArray(nargs), 0, false); + MethodHandle gcollect = makeCollectArguments(ginvoker, ValueConversions.varargsArray(nargs), 0, false); + return makePairwiseConvert(gcollect, type, 2); } } diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java index 3bf24bc8503..78b01215636 100644 --- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java +++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java @@ -41,6 +41,7 @@ import sun.reflect.misc.ReflectUtil; import sun.security.util.SecurityConstants; import static java.lang.invoke.MethodHandleStatics.*; import static java.lang.invoke.MethodHandleNatives.Constants.*; +import sun.security.util.SecurityConstants; /** * This class consists exclusively of static methods that operate on or return @@ -305,36 +306,30 @@ public class MethodHandles { * * If a security manager is present, member lookups are subject to * additional checks. - * From one to four calls are made to the security manager. + * From one to three calls are made to the security manager. * Any of these calls can refuse access by throwing a * {@link java.lang.SecurityException SecurityException}. * Define {@code smgr} as the security manager, + * {@code lookc} as the lookup class of the current lookup object, * {@code refc} as the containing class in which the member * is being sought, and {@code defc} as the class in which the * member is actually defined. + * The value {@code lookc} is defined as not present + * if the current lookup object does not have + * {@linkplain java.lang.invoke.MethodHandles.Lookup#PRIVATE private access}. * The calls are made according to the following rules: *

      - *
    • In all cases, {@link SecurityManager#checkMemberAccess - * smgr.checkMemberAccess(refc, Member.PUBLIC)} is called. - *
    • If the class loader of the lookup class is not + *
    • If {@code lookc} is not present, or if its class loader is not * the same as or an ancestor of the class loader of {@code refc}, * then {@link SecurityManager#checkPackageAccess * smgr.checkPackageAccess(refcPkg)} is called, * where {@code refcPkg} is the package of {@code refc}. + *
    • If the retrieved member is not public and + * {@code lookc} is not present, then + * {@link SecurityManager#checkPermission smgr.checkPermission} + * with {@code RuntimePermission("accessDeclaredMembers")} is called. *
    • If the retrieved member is not public, - * {@link SecurityManager#checkMemberAccess - * smgr.checkMemberAccess(defc, Member.DECLARED)} is called. - * (Note that {@code defc} might be the same as {@code refc}.) - * The default implementation of this security manager method - * inspects the stack to determine the original caller of - * the reflective request (such as {@code findStatic}), - * and performs additional permission checks if the - * class loader of {@code defc} differs from the class - * loader of the class from which the reflective request came. - *
    • If the retrieved member is not public, - * and if {@code defc} and {@code refc} are in different class loaders, - * and if the class loader of the lookup class is not - * the same as or an ancestor of the class loader of {@code defc}, + * and if {@code defc} and {@code refc} are different, * then {@link SecurityManager#checkPackageAccess * smgr.checkPackageAccess(defcPkg)} is called, * where {@code defcPkg} is the package of {@code defc}. @@ -1053,22 +1048,6 @@ return mh1; return (allowedModes & PRIVATE) != 0; } - /** - * Determine whether a security manager has an overridden - * SecurityManager.checkMemberAccess method. - */ - private boolean isCheckMemberAccessOverridden(SecurityManager sm) { - final Class cls = sm.getClass(); - if (cls == SecurityManager.class) return false; - - try { - return cls.getMethod("checkMemberAccess", Class.class, int.class). - getDeclaringClass() != SecurityManager.class; - } catch (NoSuchMethodException e) { - throw new InternalError("should not reach here"); - } - } - /** * Perform necessary access checks. * Determines a trustable caller class to compare with refc, the symbolic reference class. @@ -1079,45 +1058,22 @@ return mh1; if (smgr == null) return; if (allowedModes == TRUSTED) return; - final boolean overridden = isCheckMemberAccessOverridden(smgr); // Step 1: - { - // Default policy is to allow Member.PUBLIC; no need to check - // permission if SecurityManager is the default implementation - final int which = Member.PUBLIC; - final Class clazz = refc; - if (overridden) { - // Don't refactor; otherwise break the stack depth for - // checkMemberAccess of subclasses of SecurityManager as specified. - smgr.checkMemberAccess(clazz, which); - } - } - - // Step 2: if (!isFullPowerLookup() || !VerifyAccess.classLoaderIsAncestor(lookupClass, refc)) { ReflectUtil.checkPackageAccess(refc); } - // Step 3: + // Step 2: if (m.isPublic()) return; Class defc = m.getDeclaringClass(); { - // Inline SecurityManager.checkMemberAccess - final int which = Member.DECLARED; - final Class clazz = defc; - if (!overridden) { - if (!isFullPowerLookup()) { - smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); - } - } else { - // Don't refactor; otherwise break the stack depth for - // checkMemberAccess of subclasses of SecurityManager as specified. - smgr.checkMemberAccess(clazz, which); + if (!isFullPowerLookup()) { + smgr.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION); } } - // Step 4: + // Step 3: if (defc != refc) { ReflectUtil.checkPackageAccess(defc); } diff --git a/jdk/src/share/classes/java/lang/invoke/SerializedLambda.java b/jdk/src/share/classes/java/lang/invoke/SerializedLambda.java index 558fa5ab6ee..a775fc43e34 100644 --- a/jdk/src/share/classes/java/lang/invoke/SerializedLambda.java +++ b/jdk/src/share/classes/java/lang/invoke/SerializedLambda.java @@ -44,7 +44,6 @@ public final class SerializedLambda implements Serializable { private final String functionalInterfaceClass; private final String functionalInterfaceMethodName; private final String functionalInterfaceMethodSignature; - private final int functionalInterfaceMethodKind; private final String implClass; private final String implMethodName; private final String implMethodSignature; @@ -53,28 +52,32 @@ public final class SerializedLambda implements Serializable { private final Object[] capturedArgs; /** - * Create a {@code SerializedLambda} from the low-level information present at the lambda factory site. + * Create a {@code SerializedLambda} from the low-level information present + * at the lambda factory site. * * @param capturingClass The class in which the lambda expression appears - * @param functionalInterfaceMethodKind Method handle kind (see {@link MethodHandleInfo}) for the - * functional interface method handle present at the lambda factory site - * @param functionalInterfaceClass Name, in slash-delimited form, for the functional interface class present at the - * lambda factory site - * @param functionalInterfaceMethodName Name of the primary method for the functional interface present at the + * @param functionalInterfaceClass Name, in slash-delimited form, of static + * type of the returned lambda object + * @param functionalInterfaceMethodName Name of the functional interface + * method for the present at the * lambda factory site - * @param functionalInterfaceMethodSignature Signature of the primary method for the functional interface present - * at the lambda factory site + * @param functionalInterfaceMethodSignature Signature of the functional + * interface method present at + * the lambda factory site * @param implMethodKind Method handle kind for the implementation method - * @param implClass Name, in slash-delimited form, for the class holding the implementation method + * @param implClass Name, in slash-delimited form, for the class holding + * the implementation method * @param implMethodName Name of the implementation method * @param implMethodSignature Signature of the implementation method - * @param instantiatedMethodType The signature of the primary functional interface method after type variables - * are substituted with their instantiation from the capture site - * @param capturedArgs The dynamic arguments to the lambda factory site, which represent variables captured by + * @param instantiatedMethodType The signature of the primary functional + * interface method after type variables + * are substituted with their instantiation + * from the capture site + * @param capturedArgs The dynamic arguments to the lambda factory site, + * which represent variables captured by * the lambda */ public SerializedLambda(Class capturingClass, - int functionalInterfaceMethodKind, String functionalInterfaceClass, String functionalInterfaceMethodName, String functionalInterfaceMethodSignature, @@ -85,7 +88,6 @@ public final class SerializedLambda implements Serializable { String instantiatedMethodType, Object[] capturedArgs) { this.capturingClass = capturingClass; - this.functionalInterfaceMethodKind = functionalInterfaceMethodKind; this.functionalInterfaceClass = functionalInterfaceClass; this.functionalInterfaceMethodName = functionalInterfaceMethodName; this.functionalInterfaceMethodSignature = functionalInterfaceMethodSignature; @@ -106,10 +108,10 @@ public final class SerializedLambda implements Serializable { } /** - * Get the name of the functional interface class to which this + * Get the name of the invoked type to which this * lambda has been converted - * @return the name of the functional interface this lambda has - * been converted to + * @return the name of the functional interface class to which + * this lambda has been converted */ public String getFunctionalInterfaceClass() { return functionalInterfaceClass; @@ -134,17 +136,6 @@ public final class SerializedLambda implements Serializable { return functionalInterfaceMethodSignature; } - /** - * Get the method handle kind (see {@link MethodHandleInfo}) of - * the primary method for the functional interface to which this - * lambda has been converted - * @return the method handle kind of the primary method of - * functional interface - */ - public int getFunctionalInterfaceMethodKind() { - return functionalInterfaceMethodKind; - } - /** * Get the name of the class containing the implementation * method. @@ -234,11 +225,17 @@ public final class SerializedLambda implements Serializable { @Override public String toString() { - return String.format("SerializedLambda[capturingClass=%s, functionalInterfaceMethod=%s %s.%s:%s, " + - "implementation=%s %s.%s:%s, instantiatedMethodType=%s, numCaptured=%d]", - capturingClass, MethodHandleInfo.getReferenceKindString(functionalInterfaceMethodKind), - functionalInterfaceClass, functionalInterfaceMethodName, functionalInterfaceMethodSignature, - MethodHandleInfo.getReferenceKindString(implMethodKind), implClass, implMethodName, - implMethodSignature, instantiatedMethodType, capturedArgs.length); + String implKind=MethodHandleInfo.getReferenceKindString(implMethodKind); + return String.format("SerializedLambda[%s=%s, %s=%s.%s:%s, " + + "%s=%s %s.%s:%s, %s=%s, %s=%d]", + "capturingClass", capturingClass, + "functionalInterfaceMethod", functionalInterfaceClass, + functionalInterfaceMethodName, + functionalInterfaceMethodSignature, + "implementation", + implKind, + implClass, implMethodName, implMethodSignature, + "instantiatedMethodType", instantiatedMethodType, + "numCaptured", capturedArgs.length); } } diff --git a/jdk/src/share/classes/java/lang/management/LockInfo.java b/jdk/src/share/classes/java/lang/management/LockInfo.java index 4c05ee84f0c..b08bc046c33 100644 --- a/jdk/src/share/classes/java/lang/management/LockInfo.java +++ b/jdk/src/share/classes/java/lang/management/LockInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -42,7 +42,7 @@ import sun.management.LockInfoCompositeData; * {@link ReentrantReadWriteLock ReentrantReadWriteLock} are * two examples of ownable synchronizers provided by the platform. * - *

      MXBean Mapping

      + *

      MXBean Mapping

      * LockInfo is mapped to a {@link CompositeData CompositeData} * as specified in the {@link #from from} method. * @@ -105,7 +105,7 @@ public class LockInfo { * given {@code CompositeData}. * The given {@code CompositeData} must contain the following attributes: *
      - * + *
      * * * diff --git a/jdk/src/share/classes/java/lang/management/ManagementFactory.java b/jdk/src/share/classes/java/lang/management/ManagementFactory.java index 384cf4cda06..6e00706ccd0 100644 --- a/jdk/src/share/classes/java/lang/management/ManagementFactory.java +++ b/jdk/src/share/classes/java/lang/management/ManagementFactory.java @@ -61,7 +61,7 @@ import sun.management.ManagementFactoryHelper; * the management interface of a component of the Java virtual * machine. *

      - *

      Platform MXBeans

      + *

      Platform MXBeans

      *

      * A platform MXBean is a managed bean that * conforms to the JMX @@ -87,7 +87,7 @@ import sun.management.ManagementFactoryHelper; * *

      * An application can access a platform MXBean in the following ways: - *

      1. Direct access to an MXBean interface
      + *

      1. Direct access to an MXBean interface

      *
      *
        *
      • Get an MXBean instance by calling the @@ -107,7 +107,7 @@ import sun.management.ManagementFactoryHelper; * an MXBean of another running virtual machine. *
      • *
      - *
      2. Indirect access to an MXBean interface via MBeanServer
      + *

      2. Indirect access to an MXBean interface via MBeanServer

      *
        *
      • Go through the platform {@code MBeanServer} to access MXBeans * locally or a specific MBeanServerConnection to access @@ -135,7 +135,7 @@ import sun.management.ManagementFactoryHelper; * interfaces: * *
        - *
      Attribute NameType
      + *
      * * * @@ -178,7 +178,7 @@ import sun.management.ManagementFactoryHelper; * the following management interfaces. * *
      - *
      Management InterfaceObjectName
      + *
      * * * @@ -195,7 +195,7 @@ import sun.management.ManagementFactoryHelper; * A Java virtual machine may have one or more instances of the following * management interfaces. *
      - *
      Management InterfaceObjectName
      + *
      * * * @@ -561,6 +561,12 @@ public class ManagementFactory { * in the format of {@link ObjectName ObjectName}. * @param mxbeanInterface the MXBean interface to be implemented * by the proxy. + * @param an {@code mxbeanInterface} type parameter + * + * @return a proxy for a platform MXBean interface of a + * given MXBean name + * that forwards its method calls through the given + * MBeanServerConnection, or {@code null} if not exist. * * @throws IllegalArgumentException if *
        @@ -635,6 +641,7 @@ public class ManagementFactory { * @param mxbeanInterface a management interface for a platform * MXBean with one single instance in the Java virtual machine * if implemented. + * @param an {@code mxbeanInterface} type parameter * * @return the platform MXBean that implements * {@code mxbeanInterface}, or {@code null} if not exist. @@ -670,6 +677,7 @@ public class ManagementFactory { * * @param mxbeanInterface a management interface for a platform * MXBean + * @param an {@code mxbeanInterface} type parameter * * @return the list of platform MXBeans that implement * {@code mxbeanInterface}. @@ -707,6 +715,7 @@ public class ManagementFactory { * @param mxbeanInterface a management interface for a platform * MXBean with one single instance in the Java virtual machine * being monitored, if implemented. + * @param an {@code mxbeanInterface} type parameter * * @return the platform MXBean proxy for * forwarding the method calls of the {@code mxbeanInterface} @@ -750,6 +759,7 @@ public class ManagementFactory { * @param connection the {@code MBeanServerConnection} to forward to. * @param mxbeanInterface a management interface for a platform * MXBean + * @param an {@code mxbeanInterface} type parameter * * @return the list of platform MXBean proxies for * forwarding the method calls of the {@code mxbeanInterface} diff --git a/jdk/src/share/classes/java/lang/management/MemoryMXBean.java b/jdk/src/share/classes/java/lang/management/MemoryMXBean.java index a18748991c1..356873d842c 100644 --- a/jdk/src/share/classes/java/lang/management/MemoryMXBean.java +++ b/jdk/src/share/classes/java/lang/management/MemoryMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -49,11 +49,11 @@ import javax.management.openmbean.CompositeData; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

        Memory

        + *

        Memory

        * The memory system of the Java virtual machine manages * the following kinds of memory: * - *

        1. Heap

        + *

        1. Heap

        * The Java virtual machine has a heap that is the runtime * data area from which memory for all class instances and arrays * are allocated. It is created at the Java virtual machine start-up. @@ -63,7 +63,7 @@ import javax.management.openmbean.CompositeData; *

        The heap may be of a fixed size or may be expanded and shrunk. * The memory for the heap does not need to be contiguous. * - *

        2. Non-Heap Memory

        + *

        2. Non-Heap Memory

        * The Java virtual machine manages memory other than the heap * (referred as non-heap memory). * @@ -87,7 +87,7 @@ import javax.management.openmbean.CompositeData; * machine code translated from the Java virtual machine code for * high performance. * - *

        Memory Pools and Memory Managers

        + *

        Memory Pools and Memory Managers

        * {@link MemoryPoolMXBean Memory pools} and * {@link MemoryManagerMXBean memory managers} are the abstract entities * that monitor and manage the memory system @@ -105,7 +105,7 @@ import javax.management.openmbean.CompositeData; * add or remove memory managers during execution. * A memory pool can be managed by more than one memory manager. * - *

        Memory Usage Monitoring

        + *

        Memory Usage Monitoring

        * * Memory usage is a very important monitoring attribute for the memory system. * The memory usage, for example, could indicate: @@ -131,7 +131,7 @@ import javax.management.openmbean.CompositeData; * certain threshold. It is not intended for an application to detect * and recover from a low memory condition. * - *

        Notifications

        + *

        Notifications

        * *

        This MemoryMXBean is a * {@link javax.management.NotificationEmitter NotificationEmitter} @@ -169,7 +169,7 @@ import javax.management.openmbean.CompositeData; * MemoryNotificationInfo}. * *


        - *

        NotificationEmitter

        + *

        NotificationEmitter

        * The MemoryMXBean object returned by * {@link ManagementFactory#getMemoryMXBean} implements * the {@link javax.management.NotificationEmitter NotificationEmitter} diff --git a/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java b/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java index 3b0b156ee30..0c45555ee2e 100644 --- a/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java +++ b/jdk/src/share/classes/java/lang/management/MemoryNotificationInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -212,7 +212,7 @@ public class MemoryNotificationInfo { * The given CompositeData must contain * the following attributes: *
        - *
      Management InterfaceObjectName
      + *
      * * * diff --git a/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java b/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java index bcd7c5559b0..82aa1fcda87 100644 --- a/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java +++ b/jdk/src/share/classes/java/lang/management/MemoryPoolMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -49,7 +49,7 @@ package java.lang.management; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

      Memory Type

      + *

      Memory Type

      *

      The Java virtual machine has a heap for object allocation and also * maintains non-heap memory for the method area and the Java virtual * machine execution. The Java virtual machine can have one or more @@ -60,7 +60,7 @@ package java.lang.management; *

    • {@link MemoryType#NON_HEAP non-heap}
    • * * - *

      Memory Usage Monitoring

      + *

      Memory Usage Monitoring

      * * A memory pool has the following attributes: *
        @@ -71,7 +71,7 @@ package java.lang.management; * (only supported by some garbage-collected memory pools) *
      * - *

      1. Memory Usage

      + *

      1. Memory Usage

      * * The {@link #getUsage} method provides an estimate * of the current usage of a memory pool. @@ -86,14 +86,14 @@ package java.lang.management; * the current memory usage. An implementation should document when * this is the case. * - *

      2. Peak Memory Usage

      + *

      2. Peak Memory Usage

      * * The Java virtual machine maintains the peak memory usage of a memory * pool since the virtual machine was started or the peak was reset. * The peak memory usage is returned by the {@link #getPeakUsage} method * and reset by calling the {@link #resetPeakUsage} method. * - *

      3. Usage Threshold

      + *

      3. Usage Threshold

      * * Each memory pool has a manageable attribute * called the usage threshold which has a default value supplied @@ -304,7 +304,7 @@ package java.lang.management; * * * - *

      4. Collection Usage Threshold

      + *

      4. Collection Usage Threshold

      * * Collection usage threshold is a manageable attribute only applicable * to some garbage-collected memory pools. diff --git a/jdk/src/share/classes/java/lang/management/MemoryUsage.java b/jdk/src/share/classes/java/lang/management/MemoryUsage.java index 4dc23c0fe46..bbb75a26484 100644 --- a/jdk/src/share/classes/java/lang/management/MemoryUsage.java +++ b/jdk/src/share/classes/java/lang/management/MemoryUsage.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -36,8 +36,7 @@ import sun.management.MemoryUsageCompositeData; * the heap or non-heap memory of the Java virtual machine as a whole. * *

      A MemoryUsage object contains four values: - *

        - *
      Attribute NameType
      + *
      * * * * *
      init represents the initial amount of memory (in bytes) that @@ -78,7 +77,6 @@ import sun.management.MemoryUsageCompositeData; *
      - *
    * * Below is a picture showing an example of a memory pool: *

    @@ -98,7 +96,7 @@ import sun.management.MemoryUsageCompositeData; * max * * - *

    MXBean Mapping

    + *

    MXBean Mapping

    * MemoryUsage is mapped to a {@link CompositeData CompositeData} * with attributes as specified in the {@link #from from} method. * @@ -254,7 +252,7 @@ public class MemoryUsage { * must contain the following attributes: *

    *

    - * + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/MonitorInfo.java b/jdk/src/share/classes/java/lang/management/MonitorInfo.java index 658be133fda..e97a3173b9e 100644 --- a/jdk/src/share/classes/java/lang/management/MonitorInfo.java +++ b/jdk/src/share/classes/java/lang/management/MonitorInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -32,7 +32,7 @@ import sun.management.MonitorInfoCompositeData; * Information about an object monitor lock. An object monitor is locked * when entering a synchronization block or method on that object. * - *

    MXBean Mapping

    + *

    MXBean Mapping

    * MonitorInfo is mapped to a {@link CompositeData CompositeData} * with attributes as specified in * the {@link #from from} method. @@ -106,7 +106,7 @@ public class MonitorInfo extends LockInfo { * * mapped type for the {@link LockInfo} class: *
    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java b/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java index e4142d3e439..0e680fdf04e 100644 --- a/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java +++ b/jdk/src/share/classes/java/lang/management/RuntimeMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -272,7 +272,7 @@ public interface RuntimeMXBean extends PlatformManagedObject { * *

    * MBeanServer access:
    - * The mapped type of List is String[]. + * The mapped type of {@code List} is String[]. * * @return a list of String objects; each element * is an argument passed to the Java virtual machine. @@ -312,7 +312,7 @@ public interface RuntimeMXBean extends PlatformManagedObject { * {@link javax.management.openmbean.TabularData TabularData} * with two items in each row as follows: *

    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/ThreadInfo.java b/jdk/src/share/classes/java/lang/management/ThreadInfo.java index 676b698f5a2..e6f80b2eb23 100644 --- a/jdk/src/share/classes/java/lang/management/ThreadInfo.java +++ b/jdk/src/share/classes/java/lang/management/ThreadInfo.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -33,13 +33,13 @@ import static java.lang.Thread.State.*; /** * Thread information. ThreadInfo contains the information * about a thread including: - *

    General thread information

    + *

    General thread information

    *
      *
    • Thread ID.
    • *
    • Name of the thread.
    • *
    * - *

    Execution information

    + *

    Execution information

    *
      *
    • Thread state.
    • *
    • The object upon which the thread is blocked due to: @@ -652,7 +652,7 @@ public class ThreadInfo { * The given CompositeData must contain the following attributes * unless otherwise specified below: *
      - *
    Item NameItem Type
    + *
    * * * @@ -722,7 +722,7 @@ public class ThreadInfo { * Each element is a CompositeData representing * StackTraceElement containing the following attributes: *
    - *
    Attribute NameType
    + *
    * * * diff --git a/jdk/src/share/classes/java/lang/management/ThreadMXBean.java b/jdk/src/share/classes/java/lang/management/ThreadMXBean.java index 30251d51f60..02a87dcf6d3 100644 --- a/jdk/src/share/classes/java/lang/management/ThreadMXBean.java +++ b/jdk/src/share/classes/java/lang/management/ThreadMXBean.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2003, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2003, 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 @@ -49,7 +49,7 @@ import java.util.Map; * It can be obtained by calling the * {@link PlatformManagedObject#getObjectName} method. * - *

    Thread ID

    + *

    Thread ID

    * Thread ID is a positive long value returned by calling the * {@link java.lang.Thread#getId} method for a thread. * The thread ID is unique during its lifetime. When a thread @@ -58,7 +58,7 @@ import java.util.Map; *

    Some methods in this interface take a thread ID or an array * of thread IDs as the input parameter and return per-thread information. * - *

    Thread CPU time

    + *

    Thread CPU time

    * A Java virtual machine implementation may support measuring * the CPU time for the current thread, for any thread, or for no threads. * @@ -83,7 +83,7 @@ import java.util.Map; * Enabling thread CPU measurement could be expensive in some * Java virtual machine implementations. * - *

    Thread Contention Monitoring

    + *

    Thread Contention Monitoring

    * Some Java virtual machines may support thread contention monitoring. * When thread contention monitoring is enabled, the accumulated elapsed * time that the thread has blocked for synchronization or waited for @@ -96,7 +96,7 @@ import java.util.Map; * {@link #setThreadContentionMonitoringEnabled} method can be used to enable * thread contention monitoring. * - *

    Synchronization Information and Deadlock Detection

    + *

    Synchronization Information and Deadlock Detection

    * Some Java virtual machines may support monitoring of * {@linkplain #isObjectMonitorUsageSupported object monitor usage} and * {@linkplain #isSynchronizerUsageSupported ownable synchronizer usage}. diff --git a/jdk/src/share/classes/java/lang/ref/Reference.java b/jdk/src/share/classes/java/lang/ref/Reference.java index bc24e9df026..1cdeefd992b 100644 --- a/jdk/src/share/classes/java/lang/ref/Reference.java +++ b/jdk/src/share/classes/java/lang/ref/Reference.java @@ -89,7 +89,7 @@ public abstract class Reference { private T referent; /* Treated specially by GC */ - ReferenceQueue queue; + volatile ReferenceQueue queue; /* When active: NULL * pending: this @@ -225,9 +225,7 @@ public abstract class Reference { * been enqueued */ public boolean isEnqueued() { - synchronized (this) { - return (this.next != null && this.queue == ReferenceQueue.ENQUEUED); - } + return (this.queue == ReferenceQueue.ENQUEUED); } /** diff --git a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java index 00ca9b3e0ed..a2fad1cbce3 100644 --- a/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java +++ b/jdk/src/share/classes/java/lang/ref/ReferenceQueue.java @@ -55,25 +55,29 @@ public class ReferenceQueue { private long queueLength = 0; boolean enqueue(Reference r) { /* Called only by Reference class */ - synchronized (r) { - if (r.queue == ENQUEUED) return false; - synchronized (lock) { - r.queue = ENQUEUED; - r.next = (head == null) ? r : head; - head = r; - queueLength++; - if (r instanceof FinalReference) { - sun.misc.VM.addFinalRefCount(1); - } - lock.notifyAll(); - return true; + synchronized (lock) { + // Check that since getting the lock this reference hasn't already been + // enqueued (and even then removed) + ReferenceQueue queue = r.queue; + if ((queue == NULL) || (queue == ENQUEUED)) { + return false; } + assert queue == this; + r.queue = ENQUEUED; + r.next = (head == null) ? r : head; + head = r; + queueLength++; + if (r instanceof FinalReference) { + sun.misc.VM.addFinalRefCount(1); + } + lock.notifyAll(); + return true; } } private Reference reallyPoll() { /* Must hold lock */ - if (head != null) { - Reference r = head; + Reference r = head; + if (r != null) { head = (r.next == r) ? null : r.next; r.queue = NULL; r.next = r; diff --git a/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java b/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java index 6bc894efaba..50a7e6af904 100644 --- a/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java +++ b/jdk/src/share/classes/java/lang/reflect/AnnotatedElement.java @@ -32,49 +32,101 @@ import java.lang.annotation.AnnotationFormatError; * Represents an annotated element of the program currently running in this * VM. This interface allows annotations to be read reflectively. All * annotations returned by methods in this interface are immutable and - * serializable. It is permissible for the caller to modify the - * arrays returned by accessors for array-valued enum members; it will - * have no affect on the arrays returned to other callers. + * serializable. The arrays returned by methods of this interface may be modified + * by callers without affecting the arrays returned to other callers. * *

    The {@link #getAnnotationsByType(Class)} and {@link * #getDeclaredAnnotationsByType(Class)} methods support multiple - * annotations of the same type on an element. If the argument to either method - * is a repeatable annotation type (JLS 9.6), then the method will "look - * through" a container annotation (JLS 9.7) which was generated at - * compile-time to wrap multiple annotations of the argument type. + * annotations of the same type on an element. If the argument to + * either method is a repeatable annotation type (JLS 9.6), then the + * method will "look through" a container annotation (JLS 9.7), if + * present, and return any annotations inside the container. Container + * annotations may be generated at compile-time to wrap multiple + * annotations of the argument type. * - *

    The terms directly present and present are used - * throughout this interface to describe precisely which annotations are - * returned by methods: + *

    The terms directly present, indirectly present, + * present, and associated are used throughout this + * interface to describe precisely which annotations are returned by + * methods: * *

      - *
    • An annotation A is directly present on an element E if E is - * associated with a RuntimeVisibleAnnotations or - * RuntimeVisibleParameterAnnotations attribute, and: + * + *
    • An annotation A is directly present on an + * element E if E has a {@code + * RuntimeVisibleAnnotations} or {@code + * RuntimeVisibleParameterAnnotations} or {@code + * RuntimeVisibleTypeAnnotations} attribute, and the attribute + * contains A. + * + *
    • An annotation A is indirectly present on an + * element E if E has a {@code RuntimeVisibleAnnotations} or + * {@code RuntimeVisibleParameterAnnotations} or {@code RuntimeVisibleTypeAnnotations} + * attribute, and A 's type is repeatable, and the attribute contains + * exactly one annotation whose value element contains A and whose + * type is the containing annotation type of A 's type. + * + *
    • An annotation A is present on an element E if either: * *
        - *
      • for an invocation of {@code get[Declared]Annotation(Class)} or - * {@code get[Declared]Annotations()}, the attribute contains A. * - *
      • for an invocation of {@code get[Declared]AnnotationsByType(Class)}, the - * attribute either contains A or, if the type of A is repeatable, contains - * exactly one annotation whose value element contains A and whose type is the - * containing annotation type of A's type (JLS 9.6). + *
      • A is directly present on E; or + * + *
      • No annotation of A 's type is directly present on + * E, and E is a class, and A 's type is + * inheritable, and A is present on the superclass of E. + * *
      * - *

      - *

    • An annotation A is present on an element E if either: + *
    • An annotation A is associated with an element E + * if either: * *
        - *
      • A is directly present on E; or * - *
      • A is not directly present on E, and E is a class, and A's type - * is inheritable (JLS 9.6.3.3), and A is present on the superclass of - * E. + *
      • A is directly or indirectly present on E; or + * + *
      • No annotation of A 's type is directly or indirectly + * present on E, and E is a class, and A's type + * is inheritable, and A is associated with the superclass of + * E. + * *
      * *
    * + *

    The table below summarizes which kind of annotation presence + * different methods in this interface examine. + * + *

    Attribute NameType
    + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
    Overview of kind of presence detected by different AnnotatedElement methods
    Kind of Presence
    MethodDirectly PresentIndirectly PresentPresentAssociated
    {@code T}{@link #getAnnotation(Class) getAnnotation(Class<T>)} + * X
    {@code Annotation[]}{@link #getAnnotations getAnnotations()} + * X
    {@code T[]}{@link #getAnnotationsByType(Class) getAnnotationsByType(Class<T>)} + * X
    {@code T}{@link #getDeclaredAnnotation(Class) getDeclaredAnnotation(Class<T>)} + * X
    {@code Annotation[]}{@link #getDeclaredAnnotations getDeclaredAnnotations()} + * X
    {@code T[]}{@link #getDeclaredAnnotationsByType(Class) getDeclaredAnnotationsByType(Class<T>)} + * XX
    + * + *

    For an invocation of {@code get[Declared]AnnotationsByType( Class < + * T >)}, the order of annotations which are directly or indirectly + * present on an element E is computed as if indirectly present + * annotations on E are directly present on E in place + * of their container annotation, in the order in which they appear in + * the value element of the container annotation. + *

    If an annotation returned by a method in this interface contains * (directly or indirectly) a {@link Class}-valued member referring to * a class that is not accessible in this VM, attempting to read the class @@ -85,10 +137,11 @@ import java.lang.annotation.AnnotationFormatError; * a {@link EnumConstantNotPresentException} if the enum constant in the * annotation is no longer present in the enum type. * - *

    Attempting to read annotations of a repeatable annotation type T - * that are contained in an annotation whose type is not, in fact, the - * containing annotation type of T, will result in an {@link - * AnnotationFormatError}. + *

    If an annotation type T is (meta-)annotated with an + * {@code @Repeatable} annotation whose value element indicates a type + * TC, but TC does not declare a {@code value()} method + * with a return type of T{@code []}, then an exception of type + * {@link java.lang.annotation.AnnotationFormatError} is thrown. * *

    Finally, attempting to read a member whose definition has evolved * incompatibly will result in a {@link @@ -106,7 +159,7 @@ import java.lang.annotation.AnnotationFormatError; public interface AnnotatedElement { /** * Returns true if an annotation for the specified type - * is present on this element, else false. This method + * is present on this element, else false. This method * is designed primarily for convenient access to marker annotations. * *

    The truth value returned by this method is equivalent to: @@ -128,7 +181,7 @@ public interface AnnotatedElement { /** * Returns this element's annotation for the specified type if - * such an annotation is present, else null. + * such an annotation is present, else null. * * @param the type of the annotation to query for and return if present * @param annotationClass the Class object corresponding to the @@ -146,6 +199,20 @@ public interface AnnotatedElement { * If there are no annotations present on this element, the return * value is an array of length 0. * + * The caller of this method is free to modify the returned array; it will + * have no effect on the arrays returned to other callers. + * + * @return annotations present on this element + * @since 1.5 + */ + Annotation[] getAnnotations(); + + /** + * Returns annotations that are associated with this element. + * + * If there are no annotations associated with this element, the return + * value is an array of length 0. + * * The difference between this method and {@link #getAnnotation(Class)} * is that this method detects if its argument is a repeatable * annotation type (JLS 9.6), and if so, attempts to find one or @@ -159,65 +226,54 @@ public interface AnnotatedElement { * @param annotationClass the Class object corresponding to the * annotation type * @return all this element's annotations for the specified annotation type if - * present on this element, else an array of length zero + * associated with this element, else an array of length zero * @throws NullPointerException if the given annotation class is null * @since 1.8 */ T[] getAnnotationsByType(Class annotationClass); - /** - * Returns annotations that are present on this element. - * - * If there are no annotations present on this element, the return - * value is an array of length 0. - * - * The caller of this method is free to modify the returned array; it will - * have no effect on the arrays returned to other callers. - * - * @return annotations present on this element - * @since 1.5 - */ - Annotation[] getAnnotations(); - /** * Returns this element's annotation for the specified type if - * such an annotation is present, else null. + * such an annotation is directly present, else null. * * This method ignores inherited annotations. (Returns null if no * annotations are directly present on this element.) * - * @param the type of the annotation to query for and return if present + * @param the type of the annotation to query for and return if directly present * @param annotationClass the Class object corresponding to the * annotation type * @return this element's annotation for the specified annotation type if - * present on this element, else null + * directly present on this element, else null * @throws NullPointerException if the given annotation class is null * @since 1.8 */ T getDeclaredAnnotation(Class annotationClass); /** - * Returns annotations that are directly present on this element. - * This method ignores inherited annotations. + * Returns this element's annotation(s) for the specified type if + * such annotations are either directly present or + * indirectly present. This method ignores inherited + * annotations. * - * If there are no annotations directly present on this element, - * the return value is an array of length 0. + * If there are no specified annotations directly or indirectly + * present on this element, the return value is an array of length + * 0. * * The difference between this method and {@link * #getDeclaredAnnotation(Class)} is that this method detects if its * argument is a repeatable annotation type (JLS 9.6), and if so, * attempts to find one or more annotations of that type by "looking - * through" a container annotation. + * through" a container annotation if one is present. * * The caller of this method is free to modify the returned array; it will * have no effect on the arrays returned to other callers. * * @param the type of the annotation to query for and return - * if directly present + * if directly or indirectly present * @param annotationClass the Class object corresponding to the * annotation type * @return all this element's annotations for the specified annotation type if - * present on this element, else an array of length zero + * directly or indirectly present on this element, else an array of length zero * @throws NullPointerException if the given annotation class is null * @since 1.8 */ diff --git a/jdk/src/share/classes/java/lang/reflect/Executable.java b/jdk/src/share/classes/java/lang/reflect/Executable.java index 2501fd68d5d..aa8820fd2d7 100644 --- a/jdk/src/share/classes/java/lang/reflect/Executable.java +++ b/jdk/src/share/classes/java/lang/reflect/Executable.java @@ -326,8 +326,12 @@ public abstract class Executable extends AccessibleObject tmp = getParameters0(); // If we get back nothing, then synthesize parameters - if (tmp == null) + if (tmp == null) { + hasRealParameterData = false; tmp = synthesizeAllParams(); + } else { + hasRealParameterData = true; + } parameters = tmp; } @@ -335,6 +339,16 @@ public abstract class Executable extends AccessibleObject return tmp; } + boolean hasRealParameterData() { + // If this somehow gets called before parameters gets + // initialized, force it into existence. + if (parameters == null) { + privateGetParameters(); + } + return hasRealParameterData; + } + + private transient volatile boolean hasRealParameterData; private transient volatile Parameter[] parameters; private native Parameter[] getParameters0(); diff --git a/jdk/src/share/classes/java/lang/reflect/Member.java b/jdk/src/share/classes/java/lang/reflect/Member.java index 5d3ab3dd8b3..a539cb54614 100644 --- a/jdk/src/share/classes/java/lang/reflect/Member.java +++ b/jdk/src/share/classes/java/lang/reflect/Member.java @@ -42,14 +42,12 @@ interface Member { /** * Identifies the set of all public members of a class or interface, * including inherited members. - * @see java.lang.SecurityManager#checkMemberAccess */ public static final int PUBLIC = 0; /** * Identifies the set of declared members of a class or interface. * Inherited members are not included. - * @see java.lang.SecurityManager#checkMemberAccess */ public static final int DECLARED = 1; diff --git a/jdk/src/share/classes/java/lang/reflect/Parameter.java b/jdk/src/share/classes/java/lang/reflect/Parameter.java index 20969347255..f49c1daa436 100644 --- a/jdk/src/share/classes/java/lang/reflect/Parameter.java +++ b/jdk/src/share/classes/java/lang/reflect/Parameter.java @@ -94,6 +94,19 @@ public final class Parameter implements AnnotatedElement { return executable.hashCode() ^ index; } + /** + * Returns true if the parameter has a name according to the class + * file; returns false otherwise. Whether a parameter has a name + * is determined by the {@literal MethodParameters} attribute of + * the method which declares the parameter. + * + * @return true if and only if the parameter has a name according + * to the class file. + */ + public boolean isNamePresent() { + return executable.hasRealParameterData(); + } + /** * Returns a string describing this parameter. The format is the * modifiers for the parameter, if any, in canonical order as @@ -149,11 +162,15 @@ public final class Parameter implements AnnotatedElement { /** * Returns the name of the parameter. If the parameter's name is - * defined in a class file, then that name will be returned by - * this method. Otherwise, this method will synthesize a name of - * the form argN, where N is the index of the parameter. + * {@linkplain isNamePresent() present}, then this method returns + * the name provided by the class file. Otherwise, this method + * synthesizes a name of the form argN, where N is the index of + * the parameter in the descriptor of the method which declares + * the parameter. * - * @return the name of the parameter + * @return The name of the parameter, either provided by the class + * file or synthesized if the class file does not provide + * a name. */ public String getName() { // Note: empty strings as paramete names are now outlawed. diff --git a/jdk/src/share/classes/java/math/BigDecimal.java b/jdk/src/share/classes/java/math/BigDecimal.java index 944f8a79fbe..1a7ca811226 100644 --- a/jdk/src/share/classes/java/math/BigDecimal.java +++ b/jdk/src/share/classes/java/math/BigDecimal.java @@ -2592,14 +2592,18 @@ public class BigDecimal extends Number implements Comparable { * the {@code BigDecimal} value {@code 600.0}, which has * [{@code BigInteger}, {@code scale}] components equals to * [6000, 1], yields {@code 6E2} with [{@code BigInteger}, - * {@code scale}] components equals to [6, -2] + * {@code scale}] components equals to [6, -2]. If + * this BigDecimal is numerically equal to zero, then + * {@code BigDecimal.ZERO} is returned. * * @return a numerically equal {@code BigDecimal} with any * trailing zeros removed. * @since 1.5 */ public BigDecimal stripTrailingZeros() { - if(intCompact!=INFLATED) { + if (intCompact == 0 || (intVal != null && intVal.signum() == 0)) { + return BigDecimal.ZERO; + } else if (intCompact != INFLATED) { return createAndStripZerosToMatchScale(intCompact, scale, Long.MIN_VALUE); } else { return createAndStripZerosToMatchScale(intVal, scale, Long.MIN_VALUE); diff --git a/jdk/src/share/classes/java/net/CookieStore.java b/jdk/src/share/classes/java/net/CookieStore.java index a8232d2930c..89b9c41dd01 100644 --- a/jdk/src/share/classes/java/net/CookieStore.java +++ b/jdk/src/share/classes/java/net/CookieStore.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2005, 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 @@ -75,6 +75,8 @@ public interface CookieStore { * @return an immutable list of HttpCookie, * return empty list if no cookies match the given URI * + * @param uri the uri associated with the cookies to be returned + * * @throws NullPointerException if uri is null * * @see #add diff --git a/jdk/src/share/classes/java/net/HttpURLPermission.java b/jdk/src/share/classes/java/net/HttpURLPermission.java index 55d37fda8ca..4e038bc739e 100644 --- a/jdk/src/share/classes/java/net/HttpURLPermission.java +++ b/jdk/src/share/classes/java/net/HttpURLPermission.java @@ -47,6 +47,7 @@ import java.security.Permission; * in {@link java.io.FilePermission}. There are three different ways * as the following examples show: * + * * * * @@ -57,7 +58,7 @@ import java.security.Permission; * which only differ in the final path component, represented by the '*'. * * - * *
    URL Examples
    Example urlDescription
    http://www.oracle.com/a/b/c.htmlA url which identifies a specific (single) resource
    http://www.oracle.com/a/b/- + *
    http://www.oracle.com/a/b/-The '-' character refers to all resources recursively below the * preceding path (eg. http://www.oracle.com/a/b/c/d/e.html matches this * example). @@ -164,6 +165,8 @@ public final class HttpURLPermission extends Permission { * methods and request headers by invoking the two argument * constructor as follows: HttpURLPermission(url, "*:*") * + * @param url the url string + * * @throws IllegalArgumentException if url does not result in a valid {@link URI} */ public HttpURLPermission(String url) { @@ -204,11 +207,10 @@ public final class HttpURLPermission extends Permission { *
  • if the path or paths specified by p's url are contained in the * set of paths specified by this's url, then return true *
  • otherwise, return false
  • - * - *

    - * Some examples of how paths are matched are shown below: - *

    - * + * + *

    Some examples of how paths are matched are shown below: + *

    + * * * * diff --git a/jdk/src/share/classes/java/net/Inet4Address.java b/jdk/src/share/classes/java/net/Inet4Address.java index 529257fa90d..6c59a692f82 100644 --- a/jdk/src/share/classes/java/net/Inet4Address.java +++ b/jdk/src/share/classes/java/net/Inet4Address.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -36,7 +36,7 @@ import java.io.ObjectStreamException; * and RFC 2365: * Administratively Scoped IP Multicast * - *

    Textual representation of IP addresses

    + *

    Textual representation of IP addresses

    * * Textual representation of IPv4 address used as input to methods * takes one of the following forms: diff --git a/jdk/src/share/classes/java/net/Inet6Address.java b/jdk/src/share/classes/java/net/Inet6Address.java index 4a2d4e22473..169a180de11 100644 --- a/jdk/src/share/classes/java/net/Inet6Address.java +++ b/jdk/src/share/classes/java/net/Inet6Address.java @@ -35,7 +35,7 @@ import java.util.Enumeration; * Defined by * RFC 2373: IP Version 6 Addressing Architecture. * - *

    Textual representation of IP addresses

    + *

    Textual representation of IP addresses

    * * Textual representation of IPv6 address used as input to methods * takes one of the following forms: @@ -156,7 +156,7 @@ import java.util.Enumeration; * system. Usually, the numeric values can be determined through administration * tools on the system. Each interface may have multiple values, one for each * scope. If the scope is unspecified, then the default value used is zero. - *

  • As a string. This must be the exact string that is returned by + *
  • As a string. This must be the exact string that is returned by * {@link java.net.NetworkInterface#getName()} for the particular interface in * question. When an Inet6Address is created in this way, the numeric scope-id * is determined at the time the object is created by querying the relevant diff --git a/jdk/src/share/classes/java/net/InetAddress.java b/jdk/src/share/classes/java/net/InetAddress.java index 1154c9a80f4..aa5ef16705d 100644 --- a/jdk/src/share/classes/java/net/InetAddress.java +++ b/jdk/src/share/classes/java/net/InetAddress.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 1995, 2012, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 1995, 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 @@ -65,7 +65,7 @@ import sun.net.spi.nameservice.*; * with a host name or whether it has already done reverse host name * resolution). * - *

    Address types

    + *

    Address types

    * *
  • Examples of Path Matching
    this's pathp's pathmatch
    /a/b/a/byes
    /a/b/*/a/b/cyes
    * @@ -165,7 +165,6 @@ import sun.net.spi.nameservice.*; *

    * A value of -1 indicates "cache forever". * - *

    *

    networkaddress.cache.negative.ttl (default: 10)
    *
    Indicates the caching policy for un-successful name lookups * from the name service. The value is specified as as integer to diff --git a/jdk/src/share/classes/java/net/ProtocolFamily.java b/jdk/src/share/classes/java/net/ProtocolFamily.java index c6aa95b1861..5d02326db18 100644 --- a/jdk/src/share/classes/java/net/ProtocolFamily.java +++ b/jdk/src/share/classes/java/net/ProtocolFamily.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -34,6 +34,8 @@ package java.net; public interface ProtocolFamily { /** * Returns the name of the protocol family. + * + * @return the name of the protocol family */ String name(); } diff --git a/jdk/src/share/classes/java/net/SocketOption.java b/jdk/src/share/classes/java/net/SocketOption.java index cfa4616bcef..2ccf57f5f33 100644 --- a/jdk/src/share/classes/java/net/SocketOption.java +++ b/jdk/src/share/classes/java/net/SocketOption.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2007, 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 @@ -45,11 +45,15 @@ public interface SocketOption { /** * Returns the name of the socket option. + * + * @return the name of the socket option */ String name(); /** * Returns the type of the socket option value. + * + * @return the type of the socket option value */ Class type(); } diff --git a/jdk/src/share/classes/java/net/URI.java b/jdk/src/share/classes/java/net/URI.java index ed90f090c29..643c8af8a71 100644 --- a/jdk/src/share/classes/java/net/URI.java +++ b/jdk/src/share/classes/java/net/URI.java @@ -1,5 +1,5 @@ /* - * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved. + * Copyright (c) 2000, 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 @@ -61,13 +61,13 @@ import java.lang.NullPointerException; // for javadoc * and relativizing URI instances. Instances of this class are immutable. * * - *

    URI syntax and components

    + *

    URI syntax and components

    * * At the highest level a URI reference (hereinafter simply "URI") in string * form has the syntax * *
    - * [scheme:]scheme-specific-part[#fragment] + * [scheme:]scheme-specific-part[#fragment] *
    * * where square brackets [...] delineate optional components and the characters @@ -334,14 +334,14 @@ import java.lang.NullPointerException; // for javadoc * *
      * - *
    • The {@link #URI(java.lang.String) single-argument - * constructor} requires any illegal characters in its argument to be + *

    • The {@linkplain #URI(java.lang.String) single-argument + * constructor} requires any illegal characters in its argument to be * quoted and preserves any escaped octets and other characters that * are present.

    • * - *
    • The {@link + *

    • The {@linkplain * #URI(java.lang.String,java.lang.String,java.lang.String,int,java.lang.String,java.lang.String,java.lang.String) - * multi-argument constructors} quote illegal characters as + * multi-argument constructors} quote illegal characters as * required by the components in which they appear. The percent character * ('%') is always quoted by these constructors. Any other * characters are preserved.

    • diff --git a/jdk/src/share/classes/java/nio/X-Buffer.java.template b/jdk/src/share/classes/java/nio/X-Buffer.java.template index 03a7255c16a..60f0733c9ab 100644 --- a/jdk/src/share/classes/java/nio/X-Buffer.java.template +++ b/jdk/src/share/classes/java/nio/X-Buffer.java.template @@ -1495,7 +1495,7 @@ public abstract class $Type$Buffer #end[char] public $Streamtype$Stream $type$s() { return StreamSupport.$streamtype$Stream(() -> new $Type$BufferSpliterator(this), - Buffer.SPLITERATOR_CHARACTERISTICS); + Buffer.SPLITERATOR_CHARACTERISTICS, false); } #end[streamableType] diff --git a/jdk/src/share/classes/java/nio/file/Files.java b/jdk/src/share/classes/java/nio/file/Files.java index ca0263d0660..586859f17dc 100644 --- a/jdk/src/share/classes/java/nio/file/Files.java +++ b/jdk/src/share/classes/java/nio/file/Files.java @@ -3269,9 +3269,10 @@ public final class Files { } }; - return new DelegatingCloseableStream<>(ds, - StreamSupport.stream(Spliterators.spliteratorUnknownSize(it, - Spliterator.DISTINCT))); + Stream s = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(it, Spliterator.DISTINCT), + false); + return new DelegatingCloseableStream<>(ds, s); } /** @@ -3358,9 +3359,12 @@ public final class Files { throws IOException { FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options); - return new DelegatingCloseableStream<>(iterator, - StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT)) - .map(entry -> entry.file())); + + Stream s = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT), + false). + map(entry -> entry.file()); + return new DelegatingCloseableStream<>(iterator, s); } /** @@ -3455,10 +3459,13 @@ public final class Files { throws IOException { FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options); - return new DelegatingCloseableStream<>(iterator, - StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT)) - .filter(entry -> matcher.test(entry.file(), entry.attributes())) - .map(entry -> entry.file())); + + Stream s = StreamSupport.stream( + Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT), + false). + filter(entry -> matcher.test(entry.file(), entry.attributes())). + map(entry -> entry.file()); + return new DelegatingCloseableStream<>(iterator, s); } /** diff --git a/jdk/src/share/classes/java/security/AuthProvider.java b/jdk/src/share/classes/java/security/AuthProvider.java index a5310aa9f42..571a1fe085f 100644 --- a/jdk/src/share/classes/java/security/AuthProvider.java +++ b/jdk/src/share/classes/java/security/AuthProvider.java @@ -41,6 +41,8 @@ import javax.security.auth.callback.CallbackHandler; */ public abstract class AuthProvider extends Provider { + private static final long serialVersionUID = 4197859053084546461L; + /** * Constructs a provider with the specified name, version number, * and information. diff --git a/jdk/src/share/classes/java/util/AbstractMap.java b/jdk/src/share/classes/java/util/AbstractMap.java index fdca2aa7993..7c5153fc3bb 100644 --- a/jdk/src/share/classes/java/util/AbstractMap.java +++ b/jdk/src/share/classes/java/util/AbstractMap.java @@ -543,6 +543,8 @@ public abstract class AbstractMap implements Map { /** * Utility method for SimpleEntry and SimpleImmutableEntry. * Test for equality, checking for nulls. + * + * NB: Do not replace with Object.equals until JDK-8015417 is resolved. */ private static boolean eq(Object o1, Object o2) { return o1 == null ? o2 == null : o1.equals(o2); diff --git a/jdk/src/share/classes/java/util/ArrayList.java b/jdk/src/share/classes/java/util/ArrayList.java index 2211cc8f10d..b7d5349cc00 100644 --- a/jdk/src/share/classes/java/util/ArrayList.java +++ b/jdk/src/share/classes/java/util/ArrayList.java @@ -70,9 +70,9 @@ import java.util.function.UnaryOperator; * unsynchronized access to the list:
        *   List list = Collections.synchronizedList(new ArrayList(...));
      * - *

      + *

      * The iterators returned by this class's {@link #iterator() iterator} and - * {@link #listIterator(int) listIterator} methods are fail-fast: + * {@link #listIterator(int) listIterator} methods are fail-fast: * if the list is structurally modified at any time after the iterator is * created, in any way except through the iterator's own * {@link ListIterator#remove() remove} or diff --git a/jdk/src/share/classes/java/util/Arrays.java b/jdk/src/share/classes/java/util/Arrays.java index 196a31e5767..47c99ef7f82 100644 --- a/jdk/src/share/classes/java/util/Arrays.java +++ b/jdk/src/share/classes/java/util/Arrays.java @@ -984,6 +984,7 @@ public class Arrays { * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to * execute any parallel tasks. * + * @param the class of the objects to be sorted * @param a the array to be sorted * * @throws ClassCastException if the array contains elements that are not @@ -1035,6 +1036,7 @@ public class Arrays { * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is * used to execute any parallel tasks. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted @@ -1087,6 +1089,7 @@ public class Arrays { * {@link ForkJoinPool#commonPool() ForkJoin common pool} is used to * execute any parallel tasks. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param cmp the comparator to determine the order of the array. A * {@code null} value indicates that the elements' @@ -1138,6 +1141,7 @@ public class Arrays { * array. The {@link ForkJoinPool#commonPool() ForkJoin common pool} is * used to execute any parallel tasks. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted @@ -1412,6 +1416,7 @@ public class Arrays { * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param c the comparator to determine the order of the array. A * {@code null} value indicates that the elements' @@ -1475,6 +1480,7 @@ public class Arrays { * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. * + * @param the class of the objects to be sorted * @param a the array to be sorted * @param fromIndex the index of the first element (inclusive) to be * sorted @@ -1569,6 +1575,7 @@ public class Arrays { * Parallel prefix computation is usually more efficient than * sequential loops for large arrays. * + * @param the class of the objects in the array * @param array the array, which is modified in-place by this method * @param op a side-effect-free, associative function to perform the * cumulation @@ -1585,6 +1592,7 @@ public class Arrays { * Performs {@link #parallelPrefix(Object[], BinaryOperator)} * for the given subrange of the array. * + * @param the class of the objects in the array * @param array the array * @param fromIndex the index of the first element, inclusive * @param toIndex the index of the last element, exclusive @@ -2437,6 +2445,7 @@ public class Arrays { * elements equal to the specified object, there is no guarantee which one * will be found. * + * @param the class of the objects in the array * @param a the array to be searched * @param key the value to be searched for * @param c the comparator by which the array is ordered. A @@ -2472,6 +2481,7 @@ public class Arrays { * If the range contains multiple elements equal to the specified object, * there is no guarantee which one will be found. * + * @param the class of the objects in the array * @param a the array to be searched * @param fromIndex the index of the first element (inclusive) to be * searched @@ -3143,6 +3153,7 @@ public class Arrays { * is greater than that of the original array. * The resulting array is of exactly the same class as the original array. * + * @param the class of the objects in the array * @param original the array to be copied * @param newLength the length of the copy to be returned * @return a copy of the original array, truncated or padded with nulls @@ -3166,6 +3177,8 @@ public class Arrays { * is greater than that of the original array. * The resulting array is of the class newType. * + * @param the class of the objects in the original array + * @param the class of the objects in the returned array * @param original the array to be copied * @param newLength the length of the copy to be returned * @param newType the class of the copy to be returned @@ -3396,6 +3409,7 @@ public class Arrays { *

      * The resulting array is of exactly the same class as the original array. * + * @param the class of the objects in the array * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. @@ -3428,6 +3442,8 @@ public class Arrays { * of the returned array will be to - from. * The resulting array is of the class newType. * + * @param the class of the objects in the original array + * @param the class of the objects in the returned array * @param original the array from which a range is to be copied * @param from the initial index of the range to be copied, inclusive * @param to the final index of the range to be copied, exclusive. @@ -3760,6 +3776,7 @@ public class Arrays { * List<String> stooges = Arrays.asList("Larry", "Moe", "Curly"); * * + * @param the class of the objects in the array * @param a the array by which the list will be backed * @return a list view of the specified array */ @@ -4966,7 +4983,7 @@ public class Arrays { * @since 1.8 */ public static Stream stream(T[] array, int startInclusive, int endExclusive) { - return StreamSupport.stream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.stream(spliterator(array, startInclusive, endExclusive), false); } /** @@ -4996,7 +5013,7 @@ public class Arrays { * @since 1.8 */ public static IntStream stream(int[] array, int startInclusive, int endExclusive) { - return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.intStream(spliterator(array, startInclusive, endExclusive), false); } /** @@ -5026,7 +5043,7 @@ public class Arrays { * @since 1.8 */ public static LongStream stream(long[] array, int startInclusive, int endExclusive) { - return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.longStream(spliterator(array, startInclusive, endExclusive), false); } /** @@ -5056,6 +5073,6 @@ public class Arrays { * @since 1.8 */ public static DoubleStream stream(double[] array, int startInclusive, int endExclusive) { - return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive)); + return StreamSupport.doubleStream(spliterator(array, startInclusive, endExclusive), false); } } diff --git a/jdk/src/share/classes/java/util/Base64.java b/jdk/src/share/classes/java/util/Base64.java index 2dbaf921a52..39da03b7e3c 100644 --- a/jdk/src/share/classes/java/util/Base64.java +++ b/jdk/src/share/classes/java/util/Base64.java @@ -42,24 +42,21 @@ import java.nio.charset.StandardCharsets; * *

      *

        - * - *
      • Basic + *
      • Basic *

        Uses "The Base64 Alphabet" as specified in Table 1 of * RFC 4648 and RFC 2045 for encoding and decoding operation. * The encoder does not add any line feed (line separator) * character. The decoder rejects data that contains characters * outside the base64 alphabet.

      • * - * - *
      • URL and Filename safe + *
      • URL and Filename safe *

        Uses the "URL and Filename safe Base64 Alphabet" as specified * in Table 2 of RFC 4648 for encoding and decoding. The * encoder does not add any line feed (line separator) character. * The decoder rejects data that contains characters outside the * base64 alphabet.

      • * - * - *
      • MIME + *
      • MIME *

        Uses the "The Base64 Alphabet" as specified in Table 1 of * RFC 2045 for encoding and decoding operation. The encoded output * must be represented in lines of no more than 76 characters each diff --git a/jdk/src/share/classes/java/util/BitSet.java b/jdk/src/share/classes/java/util/BitSet.java index 56faccc66fb..c7c3143221f 100644 --- a/jdk/src/share/classes/java/util/BitSet.java +++ b/jdk/src/share/classes/java/util/BitSet.java @@ -189,6 +189,7 @@ public class BitSet implements Cloneable, java.io.Serializable { * @param longs a long array containing a little-endian representation * of a sequence of bits to be used as the initial bits of the * new bit set + * @return a {@code BitSet} containing all the bits in the long array * @since 1.7 */ public static BitSet valueOf(long[] longs) { @@ -212,6 +213,8 @@ public class BitSet implements Cloneable, java.io.Serializable { * @param lb a long buffer containing a little-endian representation * of a sequence of bits between its position and limit, to be * used as the initial bits of the new bit set + * @return a {@code BitSet} containing all the bits in the buffer in the + * specified range * @since 1.7 */ public static BitSet valueOf(LongBuffer lb) { @@ -237,6 +240,7 @@ public class BitSet implements Cloneable, java.io.Serializable { * @param bytes a byte array containing a little-endian * representation of a sequence of bits to be used as the * initial bits of the new bit set + * @return a {@code BitSet} containing all the bits in the byte array * @since 1.7 */ public static BitSet valueOf(byte[] bytes) { @@ -257,6 +261,8 @@ public class BitSet implements Cloneable, java.io.Serializable { * @param bb a byte buffer containing a little-endian representation * of a sequence of bits between its position and limit, to be * used as the initial bits of the new bit set + * @return a {@code BitSet} containing all the bits in the buffer in the + * specified range * @since 1.7 */ public static BitSet valueOf(ByteBuffer bb) { @@ -1231,6 +1237,7 @@ public class BitSet implements Cloneable, java.io.Serializable { new BitSetIterator(), cardinality(), Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED), Spliterator.SIZED | Spliterator.SUBSIZED | - Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED); + Spliterator.ORDERED | Spliterator.DISTINCT | Spliterator.SORTED, + false); } } diff --git a/jdk/src/share/classes/java/util/Calendar.java b/jdk/src/share/classes/java/util/Calendar.java index 566b8b090be..076b59db52c 100644 --- a/jdk/src/share/classes/java/util/Calendar.java +++ b/jdk/src/share/classes/java/util/Calendar.java @@ -96,7 +96,7 @@ import sun.util.spi.CalendarProvider; * concrete subclass, such as ERA. See individual field * documentation and subclass documentation for details. * - *

        Getting and Setting Calendar Field Values

        + *

        Getting and Setting Calendar Field Values

        * *

        The calendar field values can be set by calling the set * methods. Any field values set in a Calendar will not be @@ -207,7 +207,7 @@ import sun.util.spi.CalendarProvider; *

        Field Manipulation

        * * The calendar fields can be changed using three methods: - * set(), add(), and roll().

        + * set(), add(), and roll(). * *

        set(f, value) changes calendar field * f to value. In addition, it sets an @@ -2024,6 +2024,7 @@ public abstract class Calendar implements Serializable, Cloneable, Comparableget method call. * + * @param field the calendar field to test * @return true if the given calendar field has a value set; * false otherwise. */ diff --git a/jdk/src/share/classes/java/util/Collection.java b/jdk/src/share/classes/java/util/Collection.java index 249be10f0ea..7fe7a75bc44 100644 --- a/jdk/src/share/classes/java/util/Collection.java +++ b/jdk/src/share/classes/java/util/Collection.java @@ -64,9 +64,9 @@ import java.util.stream.StreamSupport; * but is not required to, throw the exception if the collection to be added * is empty. * - *

        + *

        * Some collection implementations have restrictions on the elements that - * they may contain. For example, some implementations prohibit null elements, + * they may contain. For example, some implementations prohibit null elements, * and some have restrictions on the types of their elements. Attempting to * add an ineligible element throws an unchecked exception, typically * NullPointerException or ClassCastException. Attempting @@ -232,6 +232,7 @@ public interface Collection extends Iterable { * Note that toArray(new Object[0]) is identical in function to * toArray(). * + * @param the runtime type of the array to contain the collection * @param a the array into which the elements of this collection are to be * stored, if it is big enough; otherwise, a new array of the same * runtime type is allocated for this purpose. @@ -557,7 +558,7 @@ public interface Collection extends Iterable { * @since 1.8 */ default Stream stream() { - return StreamSupport.stream(spliterator()); + return StreamSupport.stream(spliterator(), false); } /** @@ -578,6 +579,6 @@ public interface Collection extends Iterable { * @since 1.8 */ default Stream parallelStream() { - return StreamSupport.parallelStream(spliterator()); + return StreamSupport.stream(spliterator(), true); } } diff --git a/jdk/src/share/classes/java/util/Collections.java b/jdk/src/share/classes/java/util/Collections.java index ad4540db14a..43ce42eeea6 100644 --- a/jdk/src/share/classes/java/util/Collections.java +++ b/jdk/src/share/classes/java/util/Collections.java @@ -27,6 +27,7 @@ package java.util; import java.io.Serializable; import java.io.ObjectOutputStream; import java.io.IOException; +import java.io.InvalidObjectException; import java.lang.reflect.Array; import java.util.function.BiConsumer; import java.util.function.BiFunction; @@ -34,6 +35,8 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; +import java.util.stream.Stream; +import java.util.stream.StreamSupport; /** * This class consists exclusively of static methods that operate on or return @@ -136,7 +139,7 @@ public class Collections { * *

        The implementation was adapted from Tim Peters's list sort for Python * ( - * TimSort). It uses techiques from Peter McIlroy's "Optimistic + * TimSort). It uses techniques from Peter McIlroy's "Optimistic * Sorting and Information Theoretic Complexity", in Proceedings of the * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. @@ -147,6 +150,7 @@ public class Collections { * n2 log(n) performance that would result from attempting * to sort a linked list in place. * + * @param the class of the objects in the list * @param list the list to be sorted. * @throws ClassCastException if the list contains elements that are not * mutually comparable (for example, strings and integers). @@ -197,7 +201,7 @@ public class Collections { * *

        The implementation was adapted from Tim Peters's list sort for Python * ( - * TimSort). It uses techiques from Peter McIlroy's "Optimistic + * TimSort). It uses techniques from Peter McIlroy's "Optimistic * Sorting and Information Theoretic Complexity", in Proceedings of the * Fourth Annual ACM-SIAM Symposium on Discrete Algorithms, pp 467-474, * January 1993. @@ -208,6 +212,7 @@ public class Collections { * n2 log(n) performance that would result from attempting * to sort a linked list in place. * + * @param the class of the objects in the list * @param list the list to be sorted. * @param c the comparator to determine the order of the list. A * {@code null} value indicates that the elements' natural @@ -246,6 +251,7 @@ public class Collections { * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * + * @param the class of the objects in the list * @param list the list to be searched. * @param key the key to be searched for. * @return the index of the search key, if it is contained in the list; @@ -346,6 +352,7 @@ public class Collections { * this method will do an iterator-based binary search that performs * O(n) link traversals and O(log n) element comparisons. * + * @param the class of the objects in the list * @param list the list to be searched. * @param key the key to be searched for. * @param c the comparator by which the list is ordered. @@ -565,6 +572,7 @@ public class Collections { * * This method runs in linear time. * + * @param the class of the objects in the list * @param list the list to be filled with the specified element. * @param obj The element with which to fill the specified list. * @throws UnsupportedOperationException if the specified list or its @@ -594,6 +602,7 @@ public class Collections { * * This method runs in linear time. * + * @param the class of the objects in the lists * @param dest The destination list. * @param src The source list. * @throws IndexOutOfBoundsException if the destination list is too small @@ -632,6 +641,7 @@ public class Collections { * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * + * @param the class of the objects in the collection * @param coll the collection whose minimum element is to be determined. * @return the minimum element of the given collection, according * to the natural ordering of its elements. @@ -664,6 +674,7 @@ public class Collections { * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * + * @param the class of the objects in the collection * @param coll the collection whose minimum element is to be determined. * @param comp the comparator with which to determine the minimum element. * A null value indicates that the elements' natural @@ -703,6 +714,7 @@ public class Collections { * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * + * @param the class of the objects in the collection * @param coll the collection whose maximum element is to be determined. * @return the maximum element of the given collection, according * to the natural ordering of its elements. @@ -735,6 +747,7 @@ public class Collections { * This method iterates over the entire collection, hence it requires * time proportional to the size of the collection. * + * @param the class of the objects in the collection * @param coll the collection whose maximum element is to be determined. * @param comp the comparator with which to determine the maximum element. * A null value indicates that the elements' natural @@ -869,6 +882,7 @@ public class Collections { * (oldVal==null ? e==null : oldVal.equals(e)). * (This method has no effect on the size of the list.) * + * @param the class of the objects in the list * @param list the list in which replacement is to occur. * @param oldVal the old value to be replaced. * @param newVal the new value with which oldVal is to be @@ -1050,6 +1064,7 @@ public class Collections { * The returned collection will be serializable if the specified collection * is serializable. * + * @param the class of the objects in the collection * @param c the collection for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified collection. @@ -1145,6 +1160,7 @@ public class Collections { * The returned set will be serializable if the specified set * is serializable. * + * @param the class of the objects in the set * @param s the set for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified set. */ @@ -1176,6 +1192,7 @@ public class Collections { * The returned sorted set will be serializable if the specified sorted set * is serializable. * + * @param the class of the objects in the set * @param s the sorted set for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted set. @@ -1211,6 +1228,95 @@ public class Collections { public E last() {return ss.last();} } + /** + * Returns an unmodifiable view of the specified navigable set. This method + * allows modules to provide users with "read-only" access to internal + * navigable sets. Query operations on the returned navigable set "read + * through" to the specified navigable set. Attempts to modify the returned + * navigable set, whether direct, via its iterator, or via its + * {@code subSet}, {@code headSet}, or {@code tailSet} views, result in + * an {@code UnsupportedOperationException}.

        + * + * The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + * @param the class of the objects in the set + * @param s the navigable set for which an unmodifiable view is to be + * returned + * @return an unmodifiable view of the specified navigable set + * @since 1.8 + */ + public static NavigableSet unmodifiableNavigableSet(NavigableSet s) { + return new UnmodifiableNavigableSet<>(s); + } + + /** + * Wraps a navigable set and disables all of the mutative operations. + * + * @param type of elements + * @serial include + */ + static class UnmodifiableNavigableSet + extends UnmodifiableSortedSet + implements NavigableSet, Serializable { + + private static final long serialVersionUID = -6027448201786391929L; + + /** + * A singleton empty unmodifiable navigable set used for + * {@link #emptyNavigableSet()}. + * + * @param type of elements, if there were any, and bounds + */ + private static class EmptyNavigableSet extends UnmodifiableNavigableSet + implements Serializable { + private static final long serialVersionUID = -6291252904449939134L; + + public EmptyNavigableSet() { + super(new TreeSet()); + } + + private Object readResolve() { return EMPTY_NAVIGABLE_SET; } + } + + @SuppressWarnings("rawtypes") + private static final NavigableSet EMPTY_NAVIGABLE_SET = + new EmptyNavigableSet<>(); + + /** + * The instance we are protecting. + */ + private final NavigableSet ns; + + UnmodifiableNavigableSet(NavigableSet s) {super(s); ns = s;} + + public E lower(E e) { return ns.lower(e); } + public E floor(E e) { return ns.floor(e); } + public E ceiling(E e) { return ns.ceiling(e); } + public E higher(E e) { return ns.higher(e); } + public E pollFirst() { throw new UnsupportedOperationException(); } + public E pollLast() { throw new UnsupportedOperationException(); } + public NavigableSet descendingSet() + { return new UnmodifiableNavigableSet<>(ns.descendingSet()); } + public Iterator descendingIterator() + { return descendingSet().iterator(); } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return new UnmodifiableNavigableSet<>( + ns.subSet(fromElement, fromInclusive, toElement, toInclusive)); + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + return new UnmodifiableNavigableSet<>( + ns.headSet(toElement, inclusive)); + } + + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return new UnmodifiableNavigableSet<>( + ns.tailSet(fromElement, inclusive)); + } + } + /** * Returns an unmodifiable view of the specified list. This method allows * modules to provide users with "read-only" access to internal @@ -1223,6 +1329,7 @@ public class Collections { * is serializable. Similarly, the returned list will implement * {@link RandomAccess} if the specified list does. * + * @param the class of the objects in the list * @param list the list for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified list. */ @@ -1238,6 +1345,7 @@ public class Collections { static class UnmodifiableList extends UnmodifiableCollection implements List { private static final long serialVersionUID = -283967356065247728L; + final List list; UnmodifiableList(List list) { @@ -1366,6 +1474,8 @@ public class Collections { * The returned map will be serializable if the specified map * is serializable. * + * @param the class of the map keys + * @param the class of the map values * @param m the map for which an unmodifiable view is to be returned. * @return an unmodifiable view of the specified map. */ @@ -1510,6 +1620,86 @@ public class Collections { // Need to cast to raw in order to work around a limitation in the type system super((Set)s); } + + static Consumer> entryConsumer(Consumer> action) { + return e -> action.accept(new UnmodifiableEntry<>(e)); + } + + public void forEach(Consumer> action) { + Objects.requireNonNull(action); + c.forEach(entryConsumer(action)); + } + + static final class UnmodifiableEntrySetSpliterator + implements Spliterator> { + final Spliterator> s; + + UnmodifiableEntrySetSpliterator(Spliterator> s) { + this.s = s; + } + + @Override + public boolean tryAdvance(Consumer> action) { + Objects.requireNonNull(action); + return s.tryAdvance(entryConsumer(action)); + } + + @Override + public void forEachRemaining(Consumer> action) { + Objects.requireNonNull(action); + s.forEachRemaining(entryConsumer(action)); + } + + @Override + public Spliterator> trySplit() { + Spliterator> split = s.trySplit(); + return split == null + ? null + : new UnmodifiableEntrySetSpliterator<>(split); + } + + @Override + public long estimateSize() { + return s.estimateSize(); + } + + @Override + public long getExactSizeIfKnown() { + return s.getExactSizeIfKnown(); + } + + @Override + public int characteristics() { + return s.characteristics(); + } + + @Override + public boolean hasCharacteristics(int characteristics) { + return s.hasCharacteristics(characteristics); + } + + @Override + public Comparator> getComparator() { + return s.getComparator(); + } + } + + @SuppressWarnings("unchecked") + public Spliterator> spliterator() { + return new UnmodifiableEntrySetSpliterator<>( + (Spliterator>) c.spliterator()); + } + + @Override + public Stream> stream() { + return StreamSupport.stream(spliterator(), false); + } + + @Override + public Stream> parallelStream() { + return StreamSupport.stream(spliterator(), true); + } + public Iterator> iterator() { return new Iterator>() { private final Iterator> i = c.iterator(); @@ -1600,7 +1790,8 @@ public class Collections { private static class UnmodifiableEntry implements Map.Entry { private Map.Entry e; - UnmodifiableEntry(Map.Entry e) {this.e = e;} + UnmodifiableEntry(Map.Entry e) + {this.e = Objects.requireNonNull(e);} public K getKey() {return e.getKey();} public V getValue() {return e.getValue();} @@ -1634,6 +1825,8 @@ public class Collections { * The returned sorted map will be serializable if the specified sorted map * is serializable. * + * @param the class of the map keys + * @param the class of the map values * @param m the sorted map for which an unmodifiable view is to be * returned. * @return an unmodifiable view of the specified sorted map. @@ -1652,24 +1845,153 @@ public class Collections { private final SortedMap sm; - UnmodifiableSortedMap(SortedMap m) {super(m); sm = m;} - - public Comparator comparator() {return sm.comparator();} - - public SortedMap subMap(K fromKey, K toKey) { - return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); - } - public SortedMap headMap(K toKey) { - return new UnmodifiableSortedMap<>(sm.headMap(toKey)); - } - public SortedMap tailMap(K fromKey) { - return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); - } - - public K firstKey() {return sm.firstKey();} - public K lastKey() {return sm.lastKey();} + UnmodifiableSortedMap(SortedMap m) {super(m); sm = m; } + public Comparator comparator() { return sm.comparator(); } + public SortedMap subMap(K fromKey, K toKey) + { return new UnmodifiableSortedMap<>(sm.subMap(fromKey, toKey)); } + public SortedMap headMap(K toKey) + { return new UnmodifiableSortedMap<>(sm.headMap(toKey)); } + public SortedMap tailMap(K fromKey) + { return new UnmodifiableSortedMap<>(sm.tailMap(fromKey)); } + public K firstKey() { return sm.firstKey(); } + public K lastKey() { return sm.lastKey(); } } + /** + * Returns an unmodifiable view of the specified navigable map. This method + * allows modules to provide users with "read-only" access to internal + * navigable maps. Query operations on the returned navigable map "read + * through" to the specified navigable map. Attempts to modify the returned + * navigable map, whether direct, via its collection views, or via its + * {@code subMap}, {@code headMap}, or {@code tailMap} views, result in + * an {@code UnsupportedOperationException}.

        + * + * The returned navigable map will be serializable if the specified + * navigable map is serializable. + * + * @param the class of the map keys + * @param the class of the map values + * @param m the navigable map for which an unmodifiable view is to be + * returned + * @return an unmodifiable view of the specified navigable map + * @since 1.8 + */ + public static NavigableMap unmodifiableNavigableMap(NavigableMap m) { + return new UnmodifiableNavigableMap<>(m); + } + + /** + * @serial include + */ + static class UnmodifiableNavigableMap + extends UnmodifiableSortedMap + implements NavigableMap, Serializable { + private static final long serialVersionUID = -4858195264774772197L; + + /** + * A class for the {@link EMPTY_NAVIGABLE_MAP} which needs readResolve + * to preserve singleton property. + * + * @param type of keys, if there were any, and of bounds + * @param type of values, if there were any + */ + private static class EmptyNavigableMap extends UnmodifiableNavigableMap + implements Serializable { + + private static final long serialVersionUID = -2239321462712562324L; + + EmptyNavigableMap() { super(new TreeMap()); } + + @Override + public NavigableSet navigableKeySet() + { return emptyNavigableSet(); } + + private Object readResolve() { return EMPTY_NAVIGABLE_MAP; } + } + + /** + * Singleton for {@link emptyNavigableMap()} which is also immutable. + */ + private static final EmptyNavigableMap EMPTY_NAVIGABLE_MAP = + new EmptyNavigableMap<>(); + + /** + * The instance we wrap and protect. + */ + private final NavigableMap nm; + + UnmodifiableNavigableMap(NavigableMap m) + {super(m); nm = m;} + + public K lowerKey(K key) { return nm.lowerKey(key); } + public K floorKey(K key) { return nm.floorKey(key); } + public K ceilingKey(K key) { return nm.ceilingKey(key); } + public K higherKey(K key) { return nm.higherKey(key); } + + public Entry lowerEntry(K key) { + Entry lower = (Entry) nm.lowerEntry(key); + return (null != lower) + ? new UnmodifiableEntrySet.UnmodifiableEntry(lower) + : null; + } + + public Entry floorEntry(K key) { + Entry floor = (Entry) nm.floorEntry(key); + return (null != floor) + ? new UnmodifiableEntrySet.UnmodifiableEntry(floor) + : null; + } + + public Entry ceilingEntry(K key) { + Entry ceiling = (Entry) nm.ceilingEntry(key); + return (null != ceiling) + ? new UnmodifiableEntrySet.UnmodifiableEntry(ceiling) + : null; + } + + + public Entry higherEntry(K key) { + Entry higher = (Entry) nm.higherEntry(key); + return (null != higher) + ? new UnmodifiableEntrySet.UnmodifiableEntry(higher) + : null; + } + + public Entry firstEntry() { + Entry first = (Entry) nm.firstEntry(); + return (null != first) + ? new UnmodifiableEntrySet.UnmodifiableEntry(first) + : null; + } + + public Entry lastEntry() { + Entry last = (Entry) nm.lastEntry(); + return (null != last) + ? new UnmodifiableEntrySet.UnmodifiableEntry(last) + : null; + } + + public Entry pollFirstEntry() + { throw new UnsupportedOperationException(); } + public Entry pollLastEntry() + { throw new UnsupportedOperationException(); } + public NavigableMap descendingMap() + { return unmodifiableNavigableMap(nm.descendingMap()); } + public NavigableSet navigableKeySet() + { return unmodifiableNavigableSet(nm.navigableKeySet()); } + public NavigableSet descendingKeySet() + { return unmodifiableNavigableSet(nm.descendingKeySet()); } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return unmodifiableNavigableMap( + nm.subMap(fromKey, fromInclusive, toKey, toInclusive)); + } + + public NavigableMap headMap(K toKey, boolean inclusive) + { return unmodifiableNavigableMap(nm.headMap(toKey, inclusive)); } + public NavigableMap tailMap(K fromKey, boolean inclusive) + { return unmodifiableNavigableMap(nm.tailMap(fromKey, inclusive)); } + } // Synch Wrappers @@ -1702,6 +2024,7 @@ public class Collections { * The returned collection will be serializable if the specified collection * is serializable. * + * @param the class of the objects in the collection * @param c the collection to be "wrapped" in a synchronized collection. * @return a synchronized view of the specified collection. */ @@ -1723,14 +2046,13 @@ public class Collections { final Object mutex; // Object on which to synchronize SynchronizedCollection(Collection c) { - if (c==null) - throw new NullPointerException(); - this.c = c; + this.c = Objects.requireNonNull(c); mutex = this; } + SynchronizedCollection(Collection c, Object mutex) { - this.c = c; - this.mutex = mutex; + this.c = Objects.requireNonNull(c); + this.mutex = Objects.requireNonNull(mutex); } public int size() { @@ -1818,6 +2140,7 @@ public class Collections { *

        The returned set will be serializable if the specified set is * serializable. * + * @param the class of the objects in the set * @param s the set to be "wrapped" in a synchronized set. * @return a synchronized view of the specified set. */ @@ -1888,6 +2211,7 @@ public class Collections { *

        The returned sorted set will be serializable if the specified * sorted set is serializable. * + * @param the class of the objects in the set * @param s the sorted set to be "wrapped" in a synchronized sorted set. * @return a synchronized view of the specified sorted set. */ @@ -1944,6 +2268,121 @@ public class Collections { } } + /** + * Returns a synchronized (thread-safe) navigable set backed by the + * specified navigable set. In order to guarantee serial access, it is + * critical that all access to the backing navigable set is + * accomplished through the returned navigable set (or its views).

        + * + * It is imperative that the user manually synchronize on the returned + * navigable set when iterating over it or any of its {@code subSet}, + * {@code headSet}, or {@code tailSet} views. + *

        +     *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
        +     *      ...
        +     *  synchronized (s) {
        +     *      Iterator i = s.iterator(); // Must be in the synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * or: + *
        +     *  NavigableSet s = Collections.synchronizedNavigableSet(new TreeSet());
        +     *  NavigableSet s2 = s.headSet(foo, true);
        +     *      ...
        +     *  synchronized (s) {  // Note: s, not s2!!!
        +     *      Iterator i = s2.iterator(); // Must be in the synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * Failure to follow this advice may result in non-deterministic behavior. + * + *

        The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + * @param the class of the objects in the set + * @param s the navigable set to be "wrapped" in a synchronized navigable + * set + * @return a synchronized view of the specified navigable set + * @since 1.8 + */ + public static NavigableSet synchronizedNavigableSet(NavigableSet s) { + return new SynchronizedNavigableSet<>(s); + } + + /** + * @serial include + */ + static class SynchronizedNavigableSet + extends SynchronizedSortedSet + implements NavigableSet + { + private static final long serialVersionUID = -5505529816273629798L; + + private final NavigableSet ns; + + SynchronizedNavigableSet(NavigableSet s) { + super(s); + ns = s; + } + + SynchronizedNavigableSet(NavigableSet s, Object mutex) { + super(s, mutex); + ns = s; + } + public E lower(E e) { synchronized (mutex) {return ns.lower(e);} } + public E floor(E e) { synchronized (mutex) {return ns.floor(e);} } + public E ceiling(E e) { synchronized (mutex) {return ns.ceiling(e);} } + public E higher(E e) { synchronized (mutex) {return ns.higher(e);} } + public E pollFirst() { synchronized (mutex) {return ns.pollFirst();} } + public E pollLast() { synchronized (mutex) {return ns.pollLast();} } + + public NavigableSet descendingSet() { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.descendingSet(), mutex); + } + } + + public Iterator descendingIterator() + { synchronized (mutex) { return descendingSet().iterator(); } } + + public NavigableSet subSet(E fromElement, E toElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.subSet(fromElement, true, toElement, false), mutex); + } + } + public NavigableSet headSet(E toElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.headSet(toElement, false), mutex); + } + } + public NavigableSet tailSet(E fromElement) { + synchronized (mutex) { + return new SynchronizedNavigableSet(ns.tailSet(fromElement, true), mutex); + } + } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); + } + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.headSet(toElement, inclusive), mutex); + } + } + + public NavigableSet tailSet(E fromElement, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableSet<>(ns.tailSet(fromElement, inclusive)); + } + } + } + /** * Returns a synchronized (thread-safe) list backed by the specified * list. In order to guarantee serial access, it is critical that @@ -1966,6 +2405,7 @@ public class Collections { *

        The returned list will be serializable if the specified list is * serializable. * + * @param the class of the objects in the list * @param list the list to be "wrapped" in a synchronized list. * @return a synchronized view of the specified list. */ @@ -2135,6 +2575,8 @@ public class Collections { *

        The returned map will be serializable if the specified map is * serializable. * + * @param the class of the map keys + * @param the class of the map values * @param m the map to be "wrapped" in a synchronized map. * @return a synchronized view of the specified map. */ @@ -2153,9 +2595,7 @@ public class Collections { final Object mutex; // Object on which to synchronize SynchronizedMap(Map m) { - if (m==null) - throw new NullPointerException(); - this.m = m; + this.m = Objects.requireNonNull(m); mutex = this; } @@ -2327,6 +2767,8 @@ public class Collections { *

        The returned sorted map will be serializable if the specified * sorted map is serializable. * + * @param the class of the map keys + * @param the class of the map values * @param m the sorted map to be "wrapped" in a synchronized sorted map. * @return a synchronized view of the specified sorted map. */ @@ -2334,7 +2776,6 @@ public class Collections { return new SynchronizedSortedMap<>(m); } - /** * @serial include */ @@ -2384,6 +2825,166 @@ public class Collections { } } + /** + * Returns a synchronized (thread-safe) navigable map backed by the + * specified navigable map. In order to guarantee serial access, it is + * critical that all access to the backing navigable map is + * accomplished through the returned navigable map (or its views).

        + * + * It is imperative that the user manually synchronize on the returned + * navigable map when iterating over any of its collection views, or the + * collections views of any of its {@code subMap}, {@code headMap} or + * {@code tailMap} views. + *

        +     *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
        +     *      ...
        +     *  Set s = m.keySet();  // Needn't be in synchronized block
        +     *      ...
        +     *  synchronized (m) {  // Synchronizing on m, not s!
        +     *      Iterator i = s.iterator(); // Must be in synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * or: + *
        +     *  NavigableMap m = Collections.synchronizedNavigableMap(new TreeMap());
        +     *  NavigableMap m2 = m.subMap(foo, true, bar, false);
        +     *      ...
        +     *  Set s2 = m2.keySet();  // Needn't be in synchronized block
        +     *      ...
        +     *  synchronized (m) {  // Synchronizing on m, not m2 or s2!
        +     *      Iterator i = s.iterator(); // Must be in synchronized block
        +     *      while (i.hasNext())
        +     *          foo(i.next());
        +     *  }
        +     * 
        + * Failure to follow this advice may result in non-deterministic behavior. + * + *

        The returned navigable map will be serializable if the specified + * navigable map is serializable. + * + * @param the class of the map keys + * @param the class of the map values + * @param m the navigable map to be "wrapped" in a synchronized navigable + * map + * @return a synchronized view of the specified navigable map. + * @since 1.8 + */ + public static NavigableMap synchronizedNavigableMap(NavigableMap m) { + return new SynchronizedNavigableMap<>(m); + } + + /** + * A synchronized NavigableMap. + * + * @serial include + */ + static class SynchronizedNavigableMap + extends SynchronizedSortedMap + implements NavigableMap + { + private static final long serialVersionUID = 699392247599746807L; + + private final NavigableMap nm; + + SynchronizedNavigableMap(NavigableMap m) { + super(m); + nm = m; + } + SynchronizedNavigableMap(NavigableMap m, Object mutex) { + super(m, mutex); + nm = m; + } + + public Entry lowerEntry(K key) + { synchronized (mutex) { return nm.lowerEntry(key); } } + public K lowerKey(K key) + { synchronized (mutex) { return nm.lowerKey(key); } } + public Entry floorEntry(K key) + { synchronized (mutex) { return nm.floorEntry(key); } } + public K floorKey(K key) + { synchronized (mutex) { return nm.floorKey(key); } } + public Entry ceilingEntry(K key) + { synchronized (mutex) { return nm.ceilingEntry(key); } } + public K ceilingKey(K key) + { synchronized (mutex) { return nm.ceilingKey(key); } } + public Entry higherEntry(K key) + { synchronized (mutex) { return nm.higherEntry(key); } } + public K higherKey(K key) + { synchronized (mutex) { return nm.higherKey(key); } } + public Entry firstEntry() + { synchronized (mutex) { return nm.firstEntry(); } } + public Entry lastEntry() + { synchronized (mutex) { return nm.lastEntry(); } } + public Entry pollFirstEntry() + { synchronized (mutex) { return nm.pollFirstEntry(); } } + public Entry pollLastEntry() + { synchronized (mutex) { return nm.pollLastEntry(); } } + + public NavigableMap descendingMap() { + synchronized (mutex) { + return + new SynchronizedNavigableMap(nm.descendingMap(), mutex); + } + } + + public NavigableSet keySet() { + return navigableKeySet(); + } + + public NavigableSet navigableKeySet() { + synchronized (mutex) { + return new SynchronizedNavigableSet(nm.navigableKeySet(), mutex); + } + } + + public NavigableSet descendingKeySet() { + synchronized (mutex) { + return new SynchronizedNavigableSet(nm.descendingKeySet(), mutex); + } + } + + + public SortedMap subMap(K fromKey, K toKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>( + nm.subMap(fromKey, true, toKey, false), mutex); + } + } + public SortedMap headMap(K toKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>(nm.headMap(toKey, false), mutex); + } + } + public SortedMap tailMap(K fromKey) { + synchronized (mutex) { + return new SynchronizedNavigableMap<>(nm.tailMap(fromKey, true),mutex); + } + } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); + } + } + + public NavigableMap headMap(K toKey, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.headMap(toKey, inclusive), mutex); + } + } + + public NavigableMap tailMap(K fromKey, boolean inclusive) { + synchronized (mutex) { + return new SynchronizedNavigableMap( + nm.tailMap(fromKey, inclusive), mutex); + } + } + } + // Dynamically typesafe collection wrappers /** @@ -2415,12 +3016,12 @@ public class Collections { * program to wrap the collection with a dynamically typesafe view. * For example, this declaration: *

         {@code
        -     *     Collection c = new HashSet();
        +     *     Collection c = new HashSet<>();
              * }
        * may be replaced temporarily by this one: *
         {@code
              *     Collection c = Collections.checkedCollection(
        -     *         new HashSet(), String.class);
        +     *         new HashSet<>(), String.class);
              * }
        * Running the program again will cause it to fail at the point where * an incorrectly typed element is inserted into the collection, clearly @@ -2440,6 +3041,7 @@ public class Collections { * type, the returned collection permits insertion of null elements * whenever the backing collection does. * + * @param the class of the objects in the collection * @param c the collection for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code c} is permitted to hold @@ -2585,6 +3187,7 @@ public class Collections { * type, the returned queue permits insertion of {@code null} elements * whenever the backing queue does. * + * @param the class of the objects in the queue * @param queue the queue for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code queue} is permitted to hold @@ -2643,6 +3246,7 @@ public class Collections { * type, the returned set permits insertion of null elements whenever * the backing set does. * + * @param the class of the objects in the set * @param s the set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold @@ -2688,6 +3292,7 @@ public class Collections { * type, the returned sorted set permits insertion of null elements * whenever the backing sorted set does. * + * @param the class of the objects in the set * @param s the sorted set for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code s} is permitted to hold @@ -2706,6 +3311,7 @@ public class Collections { implements SortedSet, Serializable { private static final long serialVersionUID = 1599911165492914959L; + private final SortedSet ss; CheckedSortedSet(SortedSet s, Class type) { @@ -2728,6 +3334,88 @@ public class Collections { } } +/** + * Returns a dynamically typesafe view of the specified navigable set. + * Any attempt to insert an element of the wrong type will result in an + * immediate {@link ClassCastException}. Assuming a navigable set + * contains no incorrectly typed elements prior to the time a + * dynamically typesafe view is generated, and that all subsequent + * access to the navigable set takes place through the view, it is + * guaranteed that the navigable set cannot contain an incorrectly + * typed element. + * + *

        A discussion of the use of dynamically typesafe views may be + * found in the documentation for the {@link #checkedCollection + * checkedCollection} method. + * + *

        The returned navigable set will be serializable if the specified + * navigable set is serializable. + * + *

        Since {@code null} is considered to be a value of any reference + * type, the returned navigable set permits insertion of null elements + * whenever the backing sorted set does. + * + * @param the class of the objects in the set + * @param s the navigable set for which a dynamically typesafe view is to be + * returned + * @param type the type of element that {@code s} is permitted to hold + * @return a dynamically typesafe view of the specified navigable set + * @since 1.8 + */ + public static NavigableSet checkedNavigableSet(NavigableSet s, + Class type) { + return new CheckedNavigableSet<>(s, type); + } + + /** + * @serial include + */ + static class CheckedNavigableSet extends CheckedSortedSet + implements NavigableSet, Serializable + { + private static final long serialVersionUID = -5429120189805438922L; + + private final NavigableSet ns; + + CheckedNavigableSet(NavigableSet s, Class type) { + super(s, type); + ns = s; + } + + public E lower(E e) { return ns.lower(e); } + public E floor(E e) { return ns.floor(e); } + public E ceiling(E e) { return ns.ceiling(e); } + public E higher(E e) { return ns.higher(e); } + public E pollFirst() { return ns.pollFirst(); } + public E pollLast() {return ns.pollLast(); } + public NavigableSet descendingSet() + { return checkedNavigableSet(ns.descendingSet(), type); } + public Iterator descendingIterator() + {return checkedNavigableSet(ns.descendingSet(), type).iterator(); } + + public NavigableSet subSet(E fromElement, E toElement) { + return checkedNavigableSet(ns.subSet(fromElement, true, toElement, false), type); + } + public NavigableSet headSet(E toElement) { + return checkedNavigableSet(ns.headSet(toElement, false), type); + } + public NavigableSet tailSet(E fromElement) { + return checkedNavigableSet(ns.tailSet(fromElement, true), type); + } + + public NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { + return checkedNavigableSet(ns.subSet(fromElement, fromInclusive, toElement, toInclusive), type); + } + + public NavigableSet headSet(E toElement, boolean inclusive) { + return checkedNavigableSet(ns.headSet(toElement, inclusive), type); + } + + public NavigableSet tailSet(E fromElement, boolean inclusive) { + return checkedNavigableSet(ns.tailSet(fromElement, inclusive), type); + } + } + /** * Returns a dynamically typesafe view of the specified list. * Any attempt to insert an element of the wrong type will result in @@ -2748,6 +3436,7 @@ public class Collections { * type, the returned list permits insertion of null elements whenever * the backing list does. * + * @param the class of the objects in the list * @param list the list for which a dynamically typesafe view is to be * returned * @param type the type of element that {@code list} is permitted to hold @@ -2885,6 +3574,8 @@ public class Collections { * type, the returned map permits insertion of null keys or values * whenever the backing map does. * + * @param the class of the map keys + * @param the class of the map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold @@ -2940,11 +3631,9 @@ public class Collections { } CheckedMap(Map m, Class keyType, Class valueType) { - if (m == null || keyType == null || valueType == null) - throw new NullPointerException(); - this.m = m; - this.keyType = keyType; - this.valueType = valueType; + this.m = Objects.requireNonNull(m); + this.keyType = Objects.requireNonNull(keyType); + this.valueType = Objects.requireNonNull(valueType); } public int size() { return m.size(); } @@ -3221,8 +3910,8 @@ public class Collections { private final Class valueType; CheckedEntry(Map.Entry e, Class valueType) { - this.e = e; - this.valueType = valueType; + this.e = Objects.requireNonNull(e); + this.valueType = Objects.requireNonNull(valueType); } public K getKey() { return e.getKey(); } @@ -3280,6 +3969,8 @@ public class Collections { * type, the returned map permits insertion of null keys or values * whenever the backing map does. * + * @param the class of the map keys + * @param the class of the map values * @param m the map for which a dynamically typesafe view is to be * returned * @param keyType the type of key that {@code m} is permitted to hold @@ -3325,27 +4016,195 @@ public class Collections { } } + /** + * Returns a dynamically typesafe view of the specified navigable map. + * Any attempt to insert a mapping whose key or value have the wrong + * type will result in an immediate {@link ClassCastException}. + * Similarly, any attempt to modify the value currently associated with + * a key will result in an immediate {@link ClassCastException}, + * whether the modification is attempted directly through the map + * itself, or through a {@link Map.Entry} instance obtained from the + * map's {@link Map#entrySet() entry set} view. + * + *

        Assuming a map contains no incorrectly typed keys or values + * prior to the time a dynamically typesafe view is generated, and + * that all subsequent access to the map takes place through the view + * (or one of its collection views), it is guaranteed that the + * map cannot contain an incorrectly typed key or value. + * + *

        A discussion of the use of dynamically typesafe views may be + * found in the documentation for the {@link #checkedCollection + * checkedCollection} method. + * + *

        The returned map will be serializable if the specified map is + * serializable. + * + *

        Since {@code null} is considered to be a value of any reference + * type, the returned map permits insertion of null keys or values + * whenever the backing map does. + * + * @param type of map keys + * @param type of map values + * @param m the map for which a dynamically typesafe view is to be + * returned + * @param keyType the type of key that {@code m} is permitted to hold + * @param valueType the type of value that {@code m} is permitted to hold + * @return a dynamically typesafe view of the specified map + * @since 1.8 + */ + public static NavigableMap checkedNavigableMap(NavigableMap m, + Class keyType, + Class valueType) { + return new CheckedNavigableMap<>(m, keyType, valueType); + } + + /** + * @serial include + */ + static class CheckedNavigableMap extends CheckedSortedMap + implements NavigableMap, Serializable + { + private static final long serialVersionUID = -4852462692372534096L; + + private final NavigableMap nm; + + CheckedNavigableMap(NavigableMap m, + Class keyType, Class valueType) { + super(m, keyType, valueType); + nm = m; + } + + public Comparator comparator() { return nm.comparator(); } + public K firstKey() { return nm.firstKey(); } + public K lastKey() { return nm.lastKey(); } + + public Entry lowerEntry(K key) { + Entry lower = nm.lowerEntry(key); + return (null != lower) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(lower, valueType) + : null; + } + + public K lowerKey(K key) { return nm.lowerKey(key); } + + public Entry floorEntry(K key) { + Entry floor = nm.floorEntry(key); + return (null != floor) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(floor, valueType) + : null; + } + + public K floorKey(K key) { return nm.floorKey(key); } + + public Entry ceilingEntry(K key) { + Entry ceiling = nm.ceilingEntry(key); + return (null != ceiling) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(ceiling, valueType) + : null; + } + + public K ceilingKey(K key) { return nm.ceilingKey(key); } + + public Entry higherEntry(K key) { + Entry higher = nm.higherEntry(key); + return (null != higher) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(higher, valueType) + : null; + } + + public K higherKey(K key) { return nm.higherKey(key); } + + public Entry firstEntry() { + Entry first = nm.firstEntry(); + return (null != first) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(first, valueType) + : null; + } + + public Entry lastEntry() { + Entry last = nm.lastEntry(); + return (null != last) + ? new CheckedMap.CheckedEntrySet.CheckedEntry(last, valueType) + : null; + } + + public Entry pollFirstEntry() { + Entry entry = nm.pollFirstEntry(); + return (null == entry) + ? null + : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType); + } + + public Entry pollLastEntry() { + Entry entry = nm.pollLastEntry(); + return (null == entry) + ? null + : new CheckedMap.CheckedEntrySet.CheckedEntry(entry, valueType); + } + + public NavigableMap descendingMap() { + return checkedNavigableMap(nm.descendingMap(), keyType, valueType); + } + + public NavigableSet keySet() { + return navigableKeySet(); + } + + public NavigableSet navigableKeySet() { + return checkedNavigableSet(nm.navigableKeySet(), keyType); + } + + public NavigableSet descendingKeySet() { + return checkedNavigableSet(nm.descendingKeySet(), keyType); + } + + @Override + public NavigableMap subMap(K fromKey, K toKey) { + return checkedNavigableMap(nm.subMap(fromKey, true, toKey, false), + keyType, valueType); + } + + @Override + public NavigableMap headMap(K toKey) { + return checkedNavigableMap(nm.headMap(toKey, false), keyType, valueType); + } + + @Override + public NavigableMap tailMap(K fromKey) { + return checkedNavigableMap(nm.tailMap(fromKey, true), keyType, valueType); + } + + public NavigableMap subMap(K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { + return checkedNavigableMap(nm.subMap(fromKey, fromInclusive, toKey, toInclusive), keyType, valueType); + } + + public NavigableMap headMap(K toKey, boolean inclusive) { + return checkedNavigableMap(nm.headMap(toKey, inclusive), keyType, valueType); + } + + public NavigableMap tailMap(K fromKey, boolean inclusive) { + return checkedNavigableMap(nm.tailMap(fromKey, inclusive), keyType, valueType); + } + } + // Empty collections /** * Returns an iterator that has no elements. More precisely, * - *

          - * + *
            *
          • {@link Iterator#hasNext hasNext} always returns {@code - * false}. - * + * false}.
          • *
          • {@link Iterator#next next} always throws {@link - * NoSuchElementException}. - * + * NoSuchElementException}.
          • *
          • {@link Iterator#remove remove} always throws {@link - * IllegalStateException}. - * + * IllegalStateException}.
          • *
          * *

          Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * + * @param type of elements, if there were any, in the iterator * @return an empty iterator * @since 1.7 */ @@ -3370,32 +4229,26 @@ public class Collections { /** * Returns a list iterator that has no elements. More precisely, * - *

            - * + *
              *
            • {@link Iterator#hasNext hasNext} and {@link * ListIterator#hasPrevious hasPrevious} always return {@code - * false}. - * + * false}.
            • *
            • {@link Iterator#next next} and {@link ListIterator#previous - * previous} always throw {@link NoSuchElementException}. - * + * previous} always throw {@link NoSuchElementException}.
            • *
            • {@link Iterator#remove remove} and {@link ListIterator#set - * set} always throw {@link IllegalStateException}. - * + * set} always throw {@link IllegalStateException}.
            • *
            • {@link ListIterator#add add} always throws {@link - * UnsupportedOperationException}. - * + * UnsupportedOperationException}.
            • *
            • {@link ListIterator#nextIndex nextIndex} always returns - * {@code 0} . - * + * {@code 0}.
            • *
            • {@link ListIterator#previousIndex previousIndex} always - * returns {@code -1}. - * + * returns {@code -1}.
            • *
            * *

            Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * + * @param type of elements, if there were any, in the iterator * @return an empty list iterator * @since 1.7 */ @@ -3422,19 +4275,17 @@ public class Collections { /** * Returns an enumeration that has no elements. More precisely, * - *

              - * + *
                *
              • {@link Enumeration#hasMoreElements hasMoreElements} always - * returns {@code false}. - * + * returns {@code false}.
              • *
              • {@link Enumeration#nextElement nextElement} always throws - * {@link NoSuchElementException}. - * + * {@link NoSuchElementException}.
              • *
              * *

              Implementations of this method are permitted, but not * required, to return the same object from multiple invocations. * + * @param the class of the objects in the enumeration * @return an empty enumeration * @since 1.7 */ @@ -3460,17 +4311,20 @@ public class Collections { public static final Set EMPTY_SET = new EmptySet<>(); /** - * Returns the empty set (immutable). This set is serializable. + * Returns an empty set (immutable). This set is serializable. * Unlike the like-named field, this method is parameterized. * *

              This example illustrates the type-safe way to obtain an empty set: *

                    *     Set<String> s = Collections.emptySet();
                    * 
              - * Implementation note: Implementations of this method need not - * create a separate Set object for each call. Using this - * method is likely to have comparable cost to using the like-named - * field. (Unlike this method, the field does not provide type safety.) + * @implNote Implementations of this method need not create a separate + * {@code Set} object for each call. Using this method is likely to have + * comparable cost to using the like-named field. (Unlike this method, the + * field does not provide type safety.) + * + * @param the class of the objects in the set + * @return the empty set * * @see #EMPTY_SET * @since 1.5 @@ -3525,121 +4379,45 @@ public class Collections { } /** - * Returns the empty sorted set (immutable). This set is serializable. + * Returns an empty sorted set (immutable). This set is serializable. * - *

              This example illustrates the type-safe way to obtain an empty sorted - * set: - *

              -     *     SortedSet<String> s = Collections.emptySortedSet();
              -     * 
              - * Implementation note: Implementations of this method need not - * create a separate SortedSet object for each call. + *

              This example illustrates the type-safe way to obtain an empty + * sorted set: + *

               {@code
              +     *     SortedSet s = Collections.emptySortedSet();
              +     * }
              * + * @implNote Implementations of this method need not create a separate + * {@code SortedSet} object for each call. + * + * @param type of elements, if there were any, in the set + * @return the empty sorted set * @since 1.8 */ @SuppressWarnings("unchecked") - public static final SortedSet emptySortedSet() { - return (SortedSet) new EmptySortedSet<>(); + public static SortedSet emptySortedSet() { + return (SortedSet) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** - * @serial include + * Returns an empty navigable set (immutable). This set is serializable. + * + *

              This example illustrates the type-safe way to obtain an empty + * navigable set: + *

               {@code
              +     *     NavigableSet s = Collections.emptyNavigableSet();
              +     * }
              + * + * @implNote Implementations of this method need not + * create a separate {@code NavigableSet} object for each call. + * + * @param type of elements, if there were any, in the set + * @return the empty navigable set + * @since 1.8 */ - private static class EmptySortedSet - extends AbstractSet - implements SortedSet, Serializable - { - private static final long serialVersionUID = 6316515401502265487L; - public Iterator iterator() { return emptyIterator(); } - public int size() {return 0;} - public boolean isEmpty() {return true;} - public boolean contains(Object obj) {return false;} - public boolean containsAll(Collection c) { return c.isEmpty(); } - public Object[] toArray() { return new Object[0]; } - - public E[] toArray(E[] a) { - if (a.length > 0) - a[0] = null; - return a; - } - - // Preserves singleton property - private Object readResolve() { - return new EmptySortedSet<>(); - } - - @Override - public Comparator comparator() { - return null; - } - - @Override - @SuppressWarnings("unchecked") - public SortedSet subSet(Object fromElement, Object toElement) { - Objects.requireNonNull(fromElement); - Objects.requireNonNull(toElement); - - if (!(fromElement instanceof Comparable) || - !(toElement instanceof Comparable)) - { - throw new ClassCastException(); - } - - if ((((Comparable)fromElement).compareTo(toElement) >= 0) || - (((Comparable)toElement).compareTo(fromElement) < 0)) - { - throw new IllegalArgumentException(); - } - - return emptySortedSet(); - } - - @Override - public SortedSet headSet(Object toElement) { - Objects.requireNonNull(toElement); - - if (!(toElement instanceof Comparable)) { - throw new ClassCastException(); - } - - return emptySortedSet(); - } - - @Override - public SortedSet tailSet(Object fromElement) { - Objects.requireNonNull(fromElement); - - if (!(fromElement instanceof Comparable)) { - throw new ClassCastException(); - } - - return emptySortedSet(); - } - - @Override - public E first() { - throw new NoSuchElementException(); - } - - @Override - public E last() { - throw new NoSuchElementException(); - } - - // Override default methods in Collection - @Override - public void forEach(Consumer action) { - Objects.requireNonNull(action); - } - - @Override - public boolean removeIf(Predicate filter) { - Objects.requireNonNull(filter); - return false; - } - - @Override - public Spliterator spliterator() { return Spliterators.emptySpliterator(); } + @SuppressWarnings("unchecked") + public static NavigableSet emptyNavigableSet() { + return (NavigableSet) UnmodifiableNavigableSet.EMPTY_NAVIGABLE_SET; } /** @@ -3651,7 +4429,7 @@ public class Collections { public static final List EMPTY_LIST = new EmptyList<>(); /** - * Returns the empty list (immutable). This list is serializable. + * Returns an empty list (immutable). This list is serializable. * *

              This example illustrates the type-safe way to obtain an empty list: *

              @@ -3662,6 +4440,9 @@ public class Collections {
                    * method is likely to have comparable cost to using the like-named
                    * field.  (Unlike this method, the field does not provide type safety.)
                    *
              +     * @param  type of elements, if there were any, in the list
              +     * @return an empty immutable list
              +     *
                    * @see #EMPTY_LIST
                    * @since 1.5
                    */
              @@ -3748,17 +4529,20 @@ public class Collections {
                   public static final Map EMPTY_MAP = new EmptyMap<>();
               
                   /**
              -     * Returns the empty map (immutable).  This map is serializable.
              +     * Returns an empty map (immutable).  This map is serializable.
                    *
              -     * 

              This example illustrates the type-safe way to obtain an empty set: + *

              This example illustrates the type-safe way to obtain an empty map: *

                    *     Map<String, Date> s = Collections.emptyMap();
                    * 
              - * Implementation note: Implementations of this method need not - * create a separate Map object for each call. Using this - * method is likely to have comparable cost to using the like-named - * field. (Unlike this method, the field does not provide type safety.) + * @implNote Implementations of this method need not create a separate + * {@code Map} object for each call. Using this method is likely to have + * comparable cost to using the like-named field. (Unlike this method, the + * field does not provide type safety.) * + * @param the class of the map keys + * @param the class of the map values + * @return an empty map * @see #EMPTY_MAP * @since 1.5 */ @@ -3767,6 +4551,48 @@ public class Collections { return (Map) EMPTY_MAP; } + /** + * Returns an empty sorted map (immutable). This map is serializable. + * + *

              This example illustrates the type-safe way to obtain an empty map: + *

               {@code
              +     *     SortedMap s = Collections.emptySortedMap();
              +     * }
              + * + * @implNote Implementations of this method need not create a separate + * {@code SortedMap} object for each call. + * + * @param the class of the map keys + * @param the class of the map values + * @return an empty sorted map + * @since 1.8 + */ + @SuppressWarnings("unchecked") + public static final SortedMap emptySortedMap() { + return (SortedMap) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; + } + + /** + * Returns an empty navigable map (immutable). This map is serializable. + * + *

              This example illustrates the type-safe way to obtain an empty map: + *

               {@code
              +     *     NavigableMap s = Collections.emptyNavigableMap();
              +     * }
              + * + * @implNote Implementations of this method need not create a separate + * {@code NavigableMap} object for each call. + * + * @param the class of the map keys + * @param the class of the map values + * @return an empty navigable map + * @since 1.8 + */ + @SuppressWarnings("unchecked") + public static final NavigableMap emptyNavigableMap() { + return (NavigableMap) UnmodifiableNavigableMap.EMPTY_NAVIGABLE_MAP; + } + /** * @serial include */ @@ -3864,6 +4690,7 @@ public class Collections { * Returns an immutable set containing only the specified object. * The returned set is serializable. * + * @param the class of the objects in the set * @param o the sole object to be stored in the returned set. * @return an immutable set containing only the specified object. */ @@ -3984,6 +4811,7 @@ public class Collections { * Returns an immutable list containing only the specified object. * The returned list is serializable. * + * @param the class of the objects in the list * @param o the sole object to be stored in the returned list. * @return an immutable list containing only the specified object. * @since 1.3 @@ -4045,6 +4873,8 @@ public class Collections { * Returns an immutable map, mapping only the specified key to the * specified value. The returned map is serializable. * + * @param the class of the map keys + * @param the class of the map values * @param key the sole key to be stored in the returned map. * @param value the value to which the returned map maps key. * @return an immutable map containing only the specified key-value @@ -4071,15 +4901,11 @@ public class Collections { v = value; } - public int size() {return 1;} - - public boolean isEmpty() {return false;} - - public boolean containsKey(Object key) {return eq(key, k);} - - public boolean containsValue(Object value) {return eq(value, v);} - - public V get(Object key) {return (eq(key, k) ? v : null);} + public int size() {return 1;} + public boolean isEmpty() {return false;} + public boolean containsKey(Object key) {return eq(key, k);} + public boolean containsValue(Object value) {return eq(value, v);} + public V get(Object key) {return (eq(key, k) ? v : null);} private transient Set keySet = null; private transient Set> entrySet = null; @@ -4174,6 +5000,8 @@ public class Collections { * combination with the List.addAll method to grow lists. * The returned list is serializable. * + * @param the class of the object to copy and of the objects + * in the returned list. * @param n the number of elements in the returned list. * @param o the element to appear repeatedly in the returned list. * @return an immutable list consisting of n copies of the @@ -4278,6 +5106,7 @@ public class Collections { * * The returned comparator is serializable. * + * @param the class of the objects compared by the comparator * @return A comparator that imposes the reverse of the natural * ordering on a collection of objects that implement * the Comparable interface. @@ -4321,6 +5150,7 @@ public class Collections { *

              The returned comparator is serializable (assuming the specified * comparator is also serializable or {@code null}). * + * @param the class of the objects compared by the comparator * @param cmp a comparator who's ordering is to be reversed by the returned * comparator or {@code null} * @return A comparator that imposes the reverse ordering of the @@ -4384,6 +5214,7 @@ public class Collections { * interoperability with legacy APIs that require an enumeration * as input. * + * @param the class of the objects in the collection * @param c the collection for which an enumeration is to be returned. * @return an enumeration over the specified collection. * @see Enumeration @@ -4409,6 +5240,7 @@ public class Collections { * legacy APIs that return enumerations and new APIs that require * collections. * + * @param the class of the objects returned by the enumeration * @param e enumeration providing elements for the returned * array list * @return an array list containing the elements returned @@ -4426,6 +5258,8 @@ public class Collections { /** * Returns true if the specified arguments are equal, or both null. + * + * NB: Do not replace with Object.equals until JDK-8015417 is resolved. */ static boolean eq(Object o1, Object o2) { return o1==null ? o2==null : o1.equals(o2); @@ -4440,6 +5274,7 @@ public class Collections { * @param c the collection in which to determine the frequency * of o * @param o the object whose frequency is to be determined + * @return the number of elements in {@code c} equal to {@code o} * @throws NullPointerException if c is null * @since 1.5 */ @@ -4560,6 +5395,7 @@ public class Collections { * Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon"); *

              * + * @param the class of the elements to add and of the collection * @param c the collection into which elements are to be inserted * @param elements the elements to insert into c * @return true if the collection changed as a result of the call @@ -4605,6 +5441,8 @@ public class Collections { * new WeakHashMap<Object, Boolean>()); * * + * @param the class of the map keys and of the objects in the + * returned set * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if map is not empty @@ -4683,6 +5521,7 @@ public class Collections { * implemented as a sequence of {@link Deque#addFirst addFirst} * invocations on the backing deque. * + * @param the class of the objects in the deque * @param deque the deque * @return the queue * @since 1.6 diff --git a/jdk/src/share/classes/java/util/ConcurrentModificationException.java b/jdk/src/share/classes/java/util/ConcurrentModificationException.java index 3683fb399cf..d5256538f04 100644 --- a/jdk/src/share/classes/java/util/ConcurrentModificationException.java +++ b/jdk/src/share/classes/java/util/ConcurrentModificationException.java @@ -57,6 +57,7 @@ package java.util; * @author Josh Bloch * @see Collection * @see Iterator + * @see Spliterator * @see ListIterator * @see Vector * @see LinkedList diff --git a/jdk/src/share/classes/java/util/EnumSet.java b/jdk/src/share/classes/java/util/EnumSet.java index 039d772094e..6aff2994ebe 100644 --- a/jdk/src/share/classes/java/util/EnumSet.java +++ b/jdk/src/share/classes/java/util/EnumSet.java @@ -100,8 +100,10 @@ public abstract class EnumSet> extends AbstractSet /** * Creates an empty enum set with the specified element type. * + * @param The class of the elements in the set * @param elementType the class object of the element type for this enum * set + * @return An empty enum set of the specified type. * @throws NullPointerException if elementType is null */ public static > EnumSet noneOf(Class elementType) { @@ -119,8 +121,10 @@ public abstract class EnumSet> extends AbstractSet * Creates an enum set containing all of the elements in the specified * element type. * + * @param The class of the elements in the set * @param elementType the class object of the element type for this enum * set + * @return An enum set containing all the elements in the specified type. * @throws NullPointerException if elementType is null */ public static > EnumSet allOf(Class elementType) { @@ -139,7 +143,9 @@ public abstract class EnumSet> extends AbstractSet * Creates an enum set with the same element type as the specified enum * set, initially containing the same elements (if any). * + * @param The class of the elements in the set * @param s the enum set from which to initialize this enum set + * @return A copy of the specified enum set. * @throws NullPointerException if s is null */ public static > EnumSet copyOf(EnumSet s) { @@ -153,7 +159,9 @@ public abstract class EnumSet> extends AbstractSet * Otherwise, the specified collection must contain at least one element * (in order to determine the new enum set's element type). * + * @param The class of the elements in the collection * @param c the collection from which to initialize this enum set + * @return An enum set initialized from the given collection. * @throws IllegalArgumentException if c is not an * EnumSet instance and contains no elements * @throws NullPointerException if c is null @@ -178,7 +186,9 @@ public abstract class EnumSet> extends AbstractSet * set, initially containing all the elements of this type that are * not contained in the specified set. * + * @param The class of the elements in the enum set * @param s the enum set from whose complement to initialize this enum set + * @return The complement of the specified set in this set * @throws NullPointerException if s is null */ public static > EnumSet complementOf(EnumSet s) { @@ -196,6 +206,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the specified element and of the set * @param e the element that this set is to contain initially * @throws NullPointerException if e is null * @return an enum set initially containing the specified element @@ -215,6 +226,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @throws NullPointerException if any parameters are null @@ -236,6 +248,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially @@ -259,6 +272,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially @@ -284,6 +298,7 @@ public abstract class EnumSet> extends AbstractSet * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * + * @param The class of the parameter elements and of the set * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially @@ -311,6 +326,7 @@ public abstract class EnumSet> extends AbstractSet * number of elements, but it is likely to run slower than the overloadings * that do not use varargs. * + * @param The class of the parameter elements and of the set * @param first an element that the set is to contain initially * @param rest the remaining elements the set is to contain initially * @throws NullPointerException if any of the specified elements are null, @@ -332,6 +348,7 @@ public abstract class EnumSet> extends AbstractSet * contain the endpoints themselves, which may be identical but must not * be out of order. * + * @param The class of the parameter elements and of the set * @param from the first element in the range * @param to the last element in the range * @throws NullPointerException if {@code from} or {@code to} are null diff --git a/jdk/src/share/classes/java/util/Formattable.java b/jdk/src/share/classes/java/util/Formattable.java index 28b788c340a..6f3fd1ab080 100644 --- a/jdk/src/share/classes/java/util/Formattable.java +++ b/jdk/src/share/classes/java/util/Formattable.java @@ -36,7 +36,7 @@ import java.io.IOException; * For example, the following class prints out different representations of a * stock's name depending on the flags and length constraints: * - *
              + * {@code
                *   import java.nio.CharBuffer;
                *   import java.util.Formatter;
                *   import java.util.Formattable;
              @@ -89,12 +89,12 @@ import java.io.IOException;
                *           return String.format("%s - %s", symbol, companyName);
                *       }
                *   }
              - * 
              + * } * *

              When used in conjunction with the {@link java.util.Formatter}, the above * class produces the following output for various format strings. * - *

              + * {@code
                *   Formatter fmt = new Formatter();
                *   StockName sn = new StockName("HUGE", "Huge Fruit, Inc.",
                *                                "Fruit Titanesque, Inc.");
              @@ -104,7 +104,7 @@ import java.io.IOException;
                *   fmt.format("%-10.8s", sn);              //   -> "HUGE      "
                *   fmt.format("%.12s", sn);                //   -> "Huge Fruit,*"
                *   fmt.format(Locale.FRANCE, "%25s", sn);  //   -> "   Fruit Titanesque, Inc."
              - * 
              + * } * *

              Formattables are not necessarily safe for multithreaded access. Thread * safety is optional and may be enforced by classes that extend and implement diff --git a/jdk/src/share/classes/java/util/Formatter.java b/jdk/src/share/classes/java/util/Formatter.java index 7906c763fe2..5c096c63acf 100644 --- a/jdk/src/share/classes/java/util/Formatter.java +++ b/jdk/src/share/classes/java/util/Formatter.java @@ -190,7 +190,7 @@ import sun.misc.FormattedFloatingDecimal; *

              The optional flags is a set of characters that modify the output * format. The set of valid flags depends on the conversion. * - *

              The optional width is a non-negative decimal integer indicating + *

              The optional width is a positive decimal integer indicating * the minimum number of characters to be written to the output. * *

              The optional precision is a non-negative decimal integer usually @@ -841,7 +841,7 @@ import sun.misc.FormattedFloatingDecimal; * *

              Numeric types will be formatted according to the following algorithm: * - *

              Number Localization Algorithm + *

              Number Localization Algorithm * *

              After digits are obtained for the integer part, fractional part, and * exponent (as appropriate for the data type), the following transformation @@ -860,7 +860,7 @@ import sun.misc.FormattedFloatingDecimal; * substituted. * *

            • If the {@code ','} ('\u002c') - * flag is given, then the locale-specific {@linkplain + * flag is given, then the locale-specific {@linkplain * java.text.DecimalFormatSymbols#getGroupingSeparator grouping separator} is * inserted by scanning the integer part of the string from least significant * to most significant digits and inserting a separator at intervals defined by @@ -902,7 +902,7 @@ import sun.misc.FormattedFloatingDecimal; *
    unicast
    {@code 'd'} * '\u0054' * Formats the argument as a decimal integer. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    If the {@code '0'} flag is given and the value is negative, then * the zero padding will occur after the sign. @@ -1011,7 +1011,7 @@ import sun.misc.FormattedFloatingDecimal; *

    '\u002c' * Requires the output to include the locale-specific {@linkplain * java.text.DecimalFormatSymbols#getGroupingSeparator group separators} as - * described in the "group" section of the + * described in the "group" section of the * localization algorithm. * *
    {@code '('} @@ -1060,7 +1060,7 @@ import sun.misc.FormattedFloatingDecimal; *
    {@code 'd'} * '\u0054' * Requires the output to be formatted as a decimal integer. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    If the {@code '#'} flag is given {@link * FormatFlagsConversionMismatchException} will be thrown. @@ -1155,7 +1155,7 @@ import sun.misc.FormattedFloatingDecimal; *

    '\u0065' * Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    The formatting of the magnitude m depends upon its value. * @@ -1168,7 +1168,7 @@ import sun.misc.FormattedFloatingDecimal; * *

    Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. The formatting of the sign - * is described in the localization + * is described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1207,7 +1207,7 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code 'g'} * '\u0067' * Requires the output to be formatted in general scientific notation - * as described below. The localization + * as described below. The localization * algorithm is applied. * *

    After rounding for the precision, the formatting of the resulting @@ -1236,12 +1236,12 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code 'f'} * '\u0066' * Requires the output to be formatted using decimal - * format. The localization algorithm is + * format. The localization algorithm is * applied. * *

    The result is a string that represents the sign and magnitude * (absolute value) of the argument. The formatting of the sign is - * described in the localization + * described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1382,7 +1382,7 @@ import sun.misc.FormattedFloatingDecimal; *

    '\u0065' * Requires the output to be formatted using computerized scientific notation. The localization algorithm is applied. + * href="#L10nAlgorithm">localization algorithm is applied. * *

    The formatting of the magnitude m depends upon its value. * @@ -1391,7 +1391,7 @@ import sun.misc.FormattedFloatingDecimal; * *

    Otherwise, the result is a string that represents the sign and * magnitude (absolute value) of the argument. The formatting of the sign - * is described in the localization + * is described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1428,7 +1428,7 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code 'g'} * '\u0067' * Requires the output to be formatted in general scientific notation - * as described below. The localization + * as described below. The localization * algorithm is applied. * *

    After rounding for the precision, the formatting of the resulting @@ -1457,12 +1457,12 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code 'f'} * '\u0066' * Requires the output to be formatted using decimal - * format. The localization algorithm is + * format. The localization algorithm is * applied. * *

    The result is a string that represents the sign and magnitude * (absolute value) of the argument. The formatting of the sign is - * described in the localization + * described in the localization * algorithm. The formatting of the magnitude m depends upon its * value. * @@ -1721,7 +1721,7 @@ import sun.misc.FormattedFloatingDecimal; * conversions applies. If the {@code '#'} flag is given, then a {@link * FormatFlagsConversionMismatchException} will be thrown. * - *

    The width is the minimum number of characters to + *

    The width is the minimum number of characters to * be written to the output. If the length of the converted value is less than * the {@code width} then the output will be padded by spaces * ('\u0020') until the total number of characters equals width. @@ -1741,7 +1741,7 @@ import sun.misc.FormattedFloatingDecimal; *

    {@code '%'} * The result is a literal {@code '%'} ('\u0025') * - *

    The width is the minimum number of characters to + *

    The width is the minimum number of characters to * be written to the output including the {@code '%'}. If the length of the * converted value is less than the {@code width} then the output will be * padded by spaces ('\u0020') until the total number of @@ -2590,7 +2590,20 @@ public final class Formatter implements Closeable, Flushable { public String toString() { return s; } } - public enum BigDecimalLayoutForm { SCIENTIFIC, DECIMAL_FLOAT }; + /** + * Enum for {@code BigDecimal} formatting. + */ + public enum BigDecimalLayoutForm { + /** + * Format the {@code BigDecimal} in computerized scientific notation. + */ + SCIENTIFIC, + + /** + * Format the {@code BigDecimal} as a decimal number. + */ + DECIMAL_FLOAT + }; private class FormatSpecifier implements FormatString { private int index = -1; diff --git a/jdk/src/share/classes/java/util/GregorianCalendar.java b/jdk/src/share/classes/java/util/GregorianCalendar.java index 1f818ed6f64..8381a4fab4b 100644 --- a/jdk/src/share/classes/java/util/GregorianCalendar.java +++ b/jdk/src/share/classes/java/util/GregorianCalendar.java @@ -94,7 +94,7 @@ import sun.util.calendar.ZoneInfo; * adjustment may be made if desired for dates that are prior to the Gregorian * changeover and which fall between January 1 and March 24. * - *

    Week Of Year and Week Year

    + *

    Week Of Year and Week Year

    * *

    Values calculated for the {@link Calendar#WEEK_OF_YEAR * WEEK_OF_YEAR} field range from 1 to 53. The first week of a diff --git a/jdk/src/share/classes/java/util/HashMap.java b/jdk/src/share/classes/java/util/HashMap.java index eab47e3776d..c2aace9db8f 100644 --- a/jdk/src/share/classes/java/util/HashMap.java +++ b/jdk/src/share/classes/java/util/HashMap.java @@ -1013,7 +1013,7 @@ public class HashMap */ @SuppressWarnings("unchecked") final Entry getEntry(Object key) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1468,7 +1468,7 @@ public class HashMap @Override public boolean remove(Object key, Object value) { - if (isEmpty()) { + if (size == 0) { return false; } if (key == null) { @@ -1531,7 +1531,7 @@ public class HashMap @Override public boolean replace(K key, V oldValue, V newValue) { - if (isEmpty()) { + if (size == 0) { return false; } if (key == null) { @@ -1574,7 +1574,7 @@ public class HashMap @Override public V replace(K key, V value) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1694,7 +1694,7 @@ public class HashMap @Override public V computeIfPresent(K key, BiFunction remappingFunction) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -1980,7 +1980,7 @@ public class HashMap * TreeNode in a TreeBin. */ final Entry removeEntryForKey(Object key) { - if (isEmpty()) { + if (size == 0) { return null; } if (key == null) { @@ -2040,7 +2040,7 @@ public class HashMap * for matching. */ final Entry removeMapping(Object o) { - if (isEmpty() || !(o instanceof Map.Entry)) + if (size == 0 || !(o instanceof Map.Entry)) return null; Map.Entry entry = (Map.Entry) o; diff --git a/jdk/src/share/classes/java/util/LinkedList.java b/jdk/src/share/classes/java/util/LinkedList.java index 54297d96232..4d0f6dbca92 100644 --- a/jdk/src/share/classes/java/util/LinkedList.java +++ b/jdk/src/share/classes/java/util/LinkedList.java @@ -1195,12 +1195,7 @@ public class LinkedList n = s; if (n > MAX_BATCH) n = MAX_BATCH; - Object[] a; - try { - a = new Object[n]; - } catch (OutOfMemoryError oome) { - return null; - } + Object[] a = new Object[n]; int j = 0; do { a[j++] = p.item; } while ((p = p.next) != null && j < n); current = p; diff --git a/jdk/src/share/classes/java/util/Locale.java b/jdk/src/share/classes/java/util/Locale.java index 69f277659ab..6ecd39393fd 100644 --- a/jdk/src/share/classes/java/util/Locale.java +++ b/jdk/src/share/classes/java/util/Locale.java @@ -84,7 +84,7 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * described below. * *

    - *
    language
    + *
    language
    * *
    ISO 639 alpha-2 or alpha-3 language code, or registered * language subtags up to 8 alpha letters (for future enhancements). @@ -92,51 +92,51 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * alpha-2 code must be used. You can find a full list of valid * language codes in the IANA Language Subtag Registry (search for * "Type: language"). The language field is case insensitive, but - * Locale always canonicalizes to lower case.

    + * Locale always canonicalizes to lower case. * *
    Well-formed language values have the form * [a-zA-Z]{2,8}. Note that this is not the the full * BCP47 language production, since it excludes extlang. They are * not needed since modern three-letter language codes replace - * them.

    + * them. * - *
    Example: "en" (English), "ja" (Japanese), "kok" (Konkani)

    + *
    Example: "en" (English), "ja" (Japanese), "kok" (Konkani)
    * - *
    script
    + *
    script
    * *
    ISO 15924 alpha-4 script code. You can find a full list of * valid script codes in the IANA Language Subtag Registry (search * for "Type: script"). The script field is case insensitive, but * Locale always canonicalizes to title case (the first * letter is upper case and the rest of the letters are lower - * case).

    + * case). * *
    Well-formed script values have the form - * [a-zA-Z]{4}

    + * [a-zA-Z]{4} * - *
    Example: "Latn" (Latin), "Cyrl" (Cyrillic)

    + *
    Example: "Latn" (Latin), "Cyrl" (Cyrillic)
    * - *
    country (region)
    + *
    country (region)
    * *
    ISO 3166 alpha-2 country code or UN M.49 numeric-3 area code. * You can find a full list of valid country and region codes in the * IANA Language Subtag Registry (search for "Type: region"). The * country (region) field is case insensitive, but - * Locale always canonicalizes to upper case.

    + * Locale always canonicalizes to upper case. * *
    Well-formed country/region values have - * the form [a-zA-Z]{2} | [0-9]{3}

    + * the form [a-zA-Z]{2} | [0-9]{3} * *
    Example: "US" (United States), "FR" (France), "029" - * (Caribbean)

    + * (Caribbean) * - *
    variant
    + *
    variant
    * *
    Any arbitrary value used to indicate a variation of a * Locale. Where there are two or more variant values * each indicating its own semantics, these values should be ordered * by importance, with most important first, separated by - * underscore('_'). The variant field is case sensitive.

    + * underscore('_'). The variant field is case sensitive. * *
    Note: IETF BCP 47 places syntactic restrictions on variant * subtags. Also BCP 47 subtags are strictly used to indicate @@ -152,16 +152,16 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * cultural behaviors such as calendar type or number script. In * BCP 47 this kind of information, which does not identify the * language, is supported by extension subtags or private use - * subtags.

    + * subtags. * *
    Well-formed variant values have the form SUBTAG * (('_'|'-') SUBTAG)* where SUBTAG = * [0-9][0-9a-zA-Z]{3} | [0-9a-zA-Z]{5,8}. (Note: BCP 47 only - * uses hyphen ('-') as a delimiter, this is more lenient).

    + * uses hyphen ('-') as a delimiter, this is more lenient). * - *
    Example: "polyton" (Polytonic Greek), "POSIX"

    + *
    Example: "polyton" (Polytonic Greek), "POSIX"
    * - *
    extensions
    + *
    extensions
    * *
    A map from single character keys to string values, indicating * extensions apart from language identification. The extensions in @@ -169,14 +169,14 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * extension subtags and private use subtags. The extensions are * case insensitive, but Locale canonicalizes all * extension keys and values to lower case. Note that extensions - * cannot have empty values.

    + * cannot have empty values. * *
    Well-formed keys are single characters from the set * [0-9a-zA-Z]. Well-formed values have the form * SUBTAG ('-' SUBTAG)* where for the key 'x' * SUBTAG = [0-9a-zA-Z]{1,8} and for other keys * SUBTAG = [0-9a-zA-Z]{2,8} (that is, 'x' allows - * single-character subtags).

    + * single-character subtags). * *
    Example: key="u"/value="ca-japanese" (Japanese Calendar), * key="x"/value="java-1-7"
    @@ -189,7 +189,7 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * requirement (is well-formed), but does not validate the value * itself. See {@link Builder} for details. * - *

    Unicode locale/language extension

    + *

    Unicode locale/language extension

    * *

    UTS#35, "Unicode Locale Data Markup Language" defines optional * attributes and keywords to override or refine the default behavior @@ -409,7 +409,7 @@ import sun.util.locale.provider.ResourceBundleBasedAdapter; * Clients desiring a string representation of the complete locale can * then always rely on toLanguageTag for this purpose. * - *

    Special cases
    + *
    Special cases
    * *

    For compatibility reasons, two * non-conforming locales are treated as special cases. These are @@ -1007,6 +1007,8 @@ public final class Locale implements Cloneable, Serializable { * country (region), such as 3-letter numeric UN M.49 area codes. * Therefore, the list returned by this method does not contain ALL valid * codes that can be used to create Locales. + * + * @return An array of ISO 3166 two-letter country codes. */ public static String[] getISOCountries() { if (isoCountries == null) { @@ -1030,6 +1032,8 @@ public final class Locale implements Cloneable, Serializable { * 8 characters in length. Therefore, the list returned by this method does * not contain ALL valid codes that can be used to create Locales. * + * + * @return Am array of ISO 639 two-letter language codes. */ public static String[] getISOLanguages() { if (isoLanguages == null) { @@ -1268,15 +1272,15 @@ public final class Locale implements Cloneable, Serializable { * fields only. To represent a Locale as a String for interchange purposes, use * {@link #toLanguageTag}. * - *

    Examples:

      - *
    • en - *
    • de_DE - *
    • _GB - *
    • en_US_WIN - *
    • de__POSIX - *
    • zh_CN_#Hans - *
    • zh_TW_#Hant-x-java - *
    • th_TH_TH_#u-nu-thai
    + *

    Examples:

      + *
    • en
    • + *
    • de_DE
    • + *
    • _GB
    • + *
    • en_US_WIN
    • + *
    • de__POSIX
    • + *
    • zh_CN_#Hans
    • + *
    • zh_TW_#Hant-x-java
    • + *
    • th_TH_TH_#u-nu-thai
    * * @return A string representation of the Locale, for debugging. * @see #getDisplayName @@ -1506,7 +1510,7 @@ public final class Locale implements Cloneable, Serializable { * *

    Grandfathered tags with canonical replacements are as follows: * - * + *
    * * * @@ -1535,7 +1539,7 @@ public final class Locale implements Cloneable, Serializable { *

    Grandfathered tags with no modern replacement will be * converted as follows: * - *

    grandfathered tag modern replacement
    art-lojban jbo
    + *
    * * * @@ -1659,6 +1663,8 @@ public final class Locale implements Cloneable, Serializable { * (say, we don't have a Japanese name for Croatian), * this function falls back on the English name, and uses the ISO code as a last-resort * value. If the locale doesn't specify a language, this function returns the empty string. + * + * @return The name of the display language. */ public final String getDisplayLanguage() { return getDisplayLanguage(getDefault(Category.DISPLAY)); @@ -1677,6 +1683,8 @@ public final class Locale implements Cloneable, Serializable { * on the ISO code as a last-resort value. If the locale doesn't specify a language, * this function returns the empty string. * + * @param inLocale The locale for which to retrieve the display language. + * @return The name of the display language appropriate to the given locale. * @exception NullPointerException if inLocale is null */ public String getDisplayLanguage(Locale inLocale) { @@ -1703,6 +1711,7 @@ public final class Locale implements Cloneable, Serializable { * localized for the given locale. Returns the empty string if * this locale doesn't specify a script code. * + * @param inLocale The locale for which to retrieve the display script. * @return the display name of the script code for the current default * {@link Locale.Category#DISPLAY DISPLAY} locale * @throws NullPointerException if inLocale is null @@ -1727,6 +1736,8 @@ public final class Locale implements Cloneable, Serializable { * (say, we don't have a Japanese name for Croatia), * this function falls back on the English name, and uses the ISO code as a last-resort * value. If the locale doesn't specify a country, this function returns the empty string. + * + * @return The name of the country appropriate to the locale. */ public final String getDisplayCountry() { return getDisplayCountry(getDefault(Category.DISPLAY)); @@ -1745,6 +1756,8 @@ public final class Locale implements Cloneable, Serializable { * on the ISO code as a last-resort value. If the locale doesn't specify a country, * this function returns the empty string. * + * @param inLocale The locale for which to retrieve the display country. + * @return The name of the country appropriate to the given locale. * @exception NullPointerException if inLocale is null */ public String getDisplayCountry(Locale inLocale) { @@ -1778,6 +1791,8 @@ public final class Locale implements Cloneable, Serializable { * user. If possible, the name will be localized for the default * {@link Locale.Category#DISPLAY DISPLAY} locale. If the locale * doesn't specify a variant code, this function returns the empty string. + * + * @return The name of the display variant code appropriate to the locale. */ public final String getDisplayVariant() { return getDisplayVariant(getDefault(Category.DISPLAY)); @@ -1788,6 +1803,8 @@ public final class Locale implements Cloneable, Serializable { * user. If possible, the name will be localized for inLocale. If the locale * doesn't specify a variant code, this function returns the empty string. * + * @param inLocale The locale for which to retrieve the display variant code. + * @return The name of the display variant code appropriate to the given locale. * @exception NullPointerException if inLocale is null */ public String getDisplayVariant(Locale inLocale) { @@ -1821,6 +1838,8 @@ public final class Locale implements Cloneable, Serializable { * depending on which fields are specified in the locale. If the * language, sacript, country, and variant fields are all empty, * this function returns the empty string. + * + * @return The name of the locale appropriate to display. */ public final String getDisplayName() { return getDisplayName(getDefault(Category.DISPLAY)); @@ -1844,6 +1863,8 @@ public final class Locale implements Cloneable, Serializable { * language, script, country, and variant fields are all empty, * this function returns the empty string. * + * @param inLocale The locale for which to retrieve the display name. + * @return The name of the locale appropriate to display. * @throws NullPointerException if inLocale is null */ public String getDisplayName(Locale inLocale) { @@ -2672,7 +2693,7 @@ public final class Locale implements Cloneable, Serializable { * * The filtering method will behave as follows: * - *
    grandfathered tag converts to
    cel-gaulish xtg-x-cel-gaulish
    + *
    * * * diff --git a/jdk/src/share/classes/java/util/NavigableSet.java b/jdk/src/share/classes/java/util/NavigableSet.java index 26fcd3a7c35..4dbb1c1cc45 100644 --- a/jdk/src/share/classes/java/util/NavigableSet.java +++ b/jdk/src/share/classes/java/util/NavigableSet.java @@ -303,7 +303,7 @@ public interface NavigableSet extends SortedSet { * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} -na */ + */ SortedSet headSet(E toElement); /** diff --git a/jdk/src/share/classes/java/util/Optional.java b/jdk/src/share/classes/java/util/Optional.java index b51a4d26122..4e95e18684b 100644 --- a/jdk/src/share/classes/java/util/Optional.java +++ b/jdk/src/share/classes/java/util/Optional.java @@ -25,6 +25,8 @@ package java.util; import java.util.function.Consumer; +import java.util.function.Function; +import java.util.function.Predicate; import java.util.function.Supplier; /** @@ -52,7 +54,7 @@ public final class Optional { private final T value; /** - * Construct an empty instance. + * Constructs an empty instance. * * @implNote Generally only one empty instance, {@link Optional#EMPTY}, * should exist per VM. @@ -80,7 +82,7 @@ public final class Optional { } /** - * Construct an instance with the value present. + * Constructs an instance with the value present. * * @param value the non-null value to be present */ @@ -89,7 +91,7 @@ public final class Optional { } /** - * Return an {@code Optional} with the specified present value. + * Returns an {@code Optional} with the specified present non-null value. * * @param value the value to be present, which must be non-null * @return an {@code Optional} with the value present @@ -98,6 +100,18 @@ public final class Optional { return new Optional<>(value); } + /** + * Returns an {@code Optional} describing the specified value, if non-null, + * otherwise returns an empty {@code Optional}. + * + * @param value the possibly-null value to describe + * @return an {@code Optional} with a present value if the specified value + * is non-null, otherwise an empty {@code Optional} + */ + public static Optional ofNullable(T value) { + return value == null ? empty() : of(value); + } + /** * If a value is present in this {@code Optional}, returns the value, * otherwise throws {@code NoSuchElementException}. @@ -124,7 +138,7 @@ public final class Optional { } /** - * Have the specified consumer accept the value if a value is present, + * If a value is present, invoke the specified consumer with the value, * otherwise do nothing. * * @param consumer block to be executed if a value is present @@ -136,6 +150,89 @@ public final class Optional { consumer.accept(value); } + /** + * If a value is present, and the value matches the given predicate, + * return an {@code Optional} describing the value, otherwise return an + * empty {@code Optional}. + * + * @param predicate a predicate to apply to the value, if present + * @return an {@code Optional} describing the value of this {@code Optional} + * if a value is present and the value matches the given predicate, + * otherwise an empty {@code Optional} + * @throws NullPointerException if the predicate is null + */ + public Optional filter(Predicate predicate) { + Objects.requireNonNull(predicate); + if (!isPresent()) + return this; + else + return predicate.test(value) ? this : empty(); + } + + /** + * If a value is present, apply the provided mapping function to it, + * and if the result is non-null, return an {@code Optional} describing the + * result. Otherwise return an empty {@code Optional}. + * + * @apiNote This method supports post-processing on optional values, without + * the need to explicitly check for a return status. For example, the + * following code traverses a stream of file names, selects one that has + * not yet been processed, and then opens that file, returning an + * {@code Optional}: + * + *
    {@code
    +     *     Optional fis =
    +     *         names.stream().filter(name -> !isProcessedYet(name))
    +     *                       .findFirst()
    +     *                       .map(name -> new FileInputStream(name));
    +     * }
    + * + * Here, {@code findFirst} returns an {@code Optional}, and then + * {@code map} returns an {@code Optional} for the desired + * file if one exists. + * + * @param The type of the result of the mapping function + * @param mapper a mapping function to apply to the value, if present + * @return an {@code Optional} describing the result of applying a mapping + * function to the value of this {@code Optional}, if a value is present, + * otherwise an empty {@code Optional} + * @throws NullPointerException if the mapping function is null + */ + public Optional map(Function mapper) { + Objects.requireNonNull(mapper); + if (!isPresent()) + return empty(); + else { + return Optional.ofNullable(mapper.apply(value)); + } + } + + /** + * If a value is present, apply the provided {@code Optional}-bearing + * mapping function to it, return that result, otherwise return an empty + * {@code Optional}. This method is similar to {@link #map(Function)}, + * but the provided mapper is one whose result is already an {@code Optional}, + * and if invoked, {@code flatMap} does not wrap it with an additional + * {@code Optional}. + * + * @param The type parameter to the {@code Optional} returned by + * @param mapper a mapping function to apply to the value, if present + * the mapping function + * @return the result of applying an {@code Optional}-bearing mapping + * function to the value of this {@code Optional}, if a value is present, + * otherwise an empty {@code Optional} + * @throws NullPointerException if the mapping function is null or returns + * a null result + */ + public Optional flatMap(Function> mapper) { + Objects.requireNonNull(mapper); + if (!isPresent()) + return empty(); + else { + return Objects.requireNonNull(mapper.apply(value)); + } + } + /** * Return the value if present, otherwise return {@code other}. * diff --git a/jdk/src/share/classes/java/util/OptionalDouble.java b/jdk/src/share/classes/java/util/OptionalDouble.java index 118a4b8d017..eda306cf7d4 100644 --- a/jdk/src/share/classes/java/util/OptionalDouble.java +++ b/jdk/src/share/classes/java/util/OptionalDouble.java @@ -186,10 +186,10 @@ public final class OptionalDouble { } /** - * Indicates whether some other object is "equal to" this Optional. The + * Indicates whether some other object is "equal to" this OptionalDouble. The * other object is considered equal if: *
      - *
    • it is also an {@code OptionalInt} and; + *
    • it is also an {@code OptionalDouble} and; *
    • both instances have no value present or; *
    • the present values are "equal to" each other via {@code Double.compare() == 0}. *
    @@ -226,12 +226,14 @@ public final class OptionalDouble { } /** - * Returns a non-empty string representation of this OptionalDouble suitable for + * {@inheritDoc} + * + * Returns a non-empty string representation of this object suitable for * debugging. The exact presentation format is unspecified and may vary * between implementations and versions. * * @implSpec If a value is present the result must include its string - * representation in the result. Empty and present OptionalDoubless must be + * representation in the result. Empty and present instances must be * unambiguously differentiable. * * @return the string representation of this instance diff --git a/jdk/src/share/classes/java/util/OptionalInt.java b/jdk/src/share/classes/java/util/OptionalInt.java index 755c2870b73..66478ce4713 100644 --- a/jdk/src/share/classes/java/util/OptionalInt.java +++ b/jdk/src/share/classes/java/util/OptionalInt.java @@ -186,7 +186,7 @@ public final class OptionalInt { } /** - * Indicates whether some other object is "equal to" this Optional. The + * Indicates whether some other object is "equal to" this OptionalInt. The * other object is considered equal if: *
      *
    • it is also an {@code OptionalInt} and; @@ -226,12 +226,14 @@ public final class OptionalInt { } /** - * Returns a non-empty string representation of this OptionalInt suitable for + * {@inheritDoc} + * + * Returns a non-empty string representation of this object suitable for * debugging. The exact presentation format is unspecified and may vary * between implementations and versions. * * @implSpec If a value is present the result must include its string - * representation in the result. Empty and present OptionalInts must be + * representation in the result. Empty and present instances must be * unambiguously differentiable. * * @return the string representation of this instance diff --git a/jdk/src/share/classes/java/util/OptionalLong.java b/jdk/src/share/classes/java/util/OptionalLong.java index fbb1661cc25..f07cc0d3d3a 100644 --- a/jdk/src/share/classes/java/util/OptionalLong.java +++ b/jdk/src/share/classes/java/util/OptionalLong.java @@ -186,10 +186,10 @@ public final class OptionalLong { } /** - * Indicates whether some other object is "equal to" this Optional. The + * Indicates whether some other object is "equal to" this OptionalLong. The * other object is considered equal if: *
        - *
      • it is also an {@code OptionalInt} and; + *
      • it is also an {@code OptionalLong} and; *
      • both instances have no value present or; *
      • the present values are "equal to" each other via {@code ==}. *
      @@ -226,12 +226,14 @@ public final class OptionalLong { } /** - * Returns a non-empty string representation of this OptionalLong suitable for + * {@inheritDoc} + * + * Returns a non-empty string representation of this object suitable for * debugging. The exact presentation format is unspecified and may vary * between implementations and versions. * * @implSpec If a value is present the result must include its string - * representation in the result. Empty and present OptionalLongs must be + * representation in the result. Empty and present instances must be * unambiguously differentiable. * * @return the string representation of this instance diff --git a/jdk/src/share/classes/java/util/ResourceBundle.java b/jdk/src/share/classes/java/util/ResourceBundle.java index 1d9d80b90a4..b16174d30b7 100644 --- a/jdk/src/share/classes/java/util/ResourceBundle.java +++ b/jdk/src/share/classes/java/util/ResourceBundle.java @@ -74,7 +74,7 @@ import sun.util.locale.LocaleObjectCache; * *

      * This allows you to write programs that can: - *

        + *
          *
        • be easily localized, or translated, into different languages *
        • handle multiple locales at once *
        • be easily modified later to support even more locales @@ -184,7 +184,7 @@ import sun.util.locale.LocaleObjectCache; * subclass. Your subclasses must override two methods: handleGetObject * and getKeys(). * - *

          ResourceBundle.Control

          + *

          ResourceBundle.Control

          * * The {@link ResourceBundle.Control} class provides information necessary * to perform the bundle loading process by the getBundle @@ -195,7 +195,7 @@ import sun.util.locale.LocaleObjectCache; * {@link #getBundle(String, Locale, ClassLoader, Control) getBundle} * factory method for details. * - *

          For the {@code getBundle} factory + *

          For the {@code getBundle} factory * methods that take no {@link Control} instance, their default behavior of resource bundle loading * can be modified with installed {@link @@ -206,7 +206,7 @@ import sun.util.locale.LocaleObjectCache; * more than one service provider installed for supporting the same base name, * the first one returned from {@link ServiceLoader} will be used. * - *

          Cache Management

          + *

          Cache Management

          * * Resource bundle instances created by the getBundle factory * methods are cached by default, and the factory methods return the same @@ -222,7 +222,7 @@ import sun.util.locale.LocaleObjectCache; * Control#needsReload(String, Locale, String, ClassLoader, ResourceBundle, * long) ResourceBundle.Control.needsReload} for details. * - *

          Example

          + *

          Example

          * * The following is a very simple example of a ResourceBundle * subclass, MyResources, that manages two resources (for a larger number of @@ -878,8 +878,8 @@ public abstract class ResourceBundle { * description of modifying the default * behavior. * - *

          The following describes the default - * behavior. + *

          The following describes the default + * behavior. * *

          getBundle uses the base name, the specified locale, and * the default locale (obtained from {@link java.util.Locale#getDefault() @@ -974,8 +974,8 @@ public abstract class ResourceBundle { *

          If still no result bundle is found, the base name alone is looked up. If * this still fails, a MissingResourceException is thrown. * - *

          Once a result resource bundle has been found, - * its parent chain is instantiated. If the result bundle already + *

          Once a result resource bundle has been found, + * its parent chain is instantiated. If the result bundle already * has a parent (perhaps because it was returned from a cache) the chain is * complete. * @@ -1004,8 +1004,8 @@ public abstract class ResourceBundle { * path name (using "/") instead of a fully qualified class name (using * "."). * - *

          - * Example: + *

          + * Example: *

          * The following class and property files are provided: *

          @@ -1026,7 +1026,7 @@ public abstract class ResourceBundle {
                * 

          Calling getBundle with the locale arguments below will * instantiate resource bundles as follows: * - *

    Filtering ModeLanguage Priority List: {@code "de-DE"}
    + *
    * * * @@ -1106,45 +1106,45 @@ public abstract class ResourceBundle { * control.newBundle. * *
    Locale("fr", "CH")MyResources_fr_CH.class, parent MyResources_fr.properties, parent MyResources.class
    Locale("fr", "FR")MyResources_fr.properties, parent MyResources.class
    Locale("de", "DE")MyResources_en.properties, parent MyResources.class
    - * + * border="0" cellpadding="2" cellspacing="2" summary="locale-format combinations for newBundle"> + * * * * * * - * - * * * - * - * + * * * - * - * + * + * * * - * - * + * + * * * - * - * + * * * - * - * + * + * * - * + * *
    Locale
    + * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;">Locale
    *
    format
    + * style="vertical-align: top; text-align: left; font-weight: bold; width: 50%;">format
    *
    Locale("de", "DE")
    + *
    Locale("de", "DE")
    *
    java.class
    + *
    java.class
    *
    Locale("de", "DE")java.properties
    + *
    Locale("de", "DE")java.properties
    *
    Locale("de")java.classLocale("de")java.class
    Locale("de")java.propertiesLocale("de")java.properties
    Locale("")
    + *
    Locale("")
    *
    java.classjava.class
    Locale("")java.propertiesLocale("")java.properties
    * * @@ -2199,11 +2199,11 @@ public abstract class ResourceBundle { * one by one as below: * *

      - *
    • [L, C, V] - *
    • [L, C] - *
    • [L] - *
    • Locale.ROOT - *
    + *
  • [L, C, V]
  • + *
  • [L, C]
  • + *
  • [L]
  • + *
  • Locale.ROOT
  • + * * *
  • For an input Locale with a non-empty script value, * append candidate Locales by omitting the final component @@ -2211,14 +2211,14 @@ public abstract class ResourceBundle { * Locale with country and variant restored: * *
      - *
    • [L, S, C, V] - *
    • [L, S, C] - *
    • [L, S] - *
    • [L, C, V] - *
    • [L, C] - *
    • [L] - *
    • Locale.ROOT - *
    + *
  • [L, S, C, V]
  • + *
  • [L, S, C]
  • + *
  • [L, S]
  • + *
  • [L, C, V]
  • + *
  • [L, C]
  • + *
  • [L]
  • + *
  • Locale.ROOT
  • + * * *
  • For an input Locale with a variant value consisting * of multiple subtags separated by underscore, generate candidate @@ -2228,16 +2228,16 @@ public abstract class ResourceBundle { * the variant consists of two subtags V1 and V2: * *
      - *
    • [L, S, C, V1, V2] - *
    • [L, S, C, V1] - *
    • [L, S, C] - *
    • [L, S] - *
    • [L, C, V1, V2] - *
    • [L, C, V1] - *
    • [L, C] - *
    • [L] - *
    • Locale.ROOT - *
    + *
  • [L, S, C, V1, V2]
  • + *
  • [L, S, C, V1]
  • + *
  • [L, S, C]
  • + *
  • [L, S]
  • + *
  • [L, C, V1, V2]
  • + *
  • [L, C, V1]
  • + *
  • [L, C]
  • + *
  • [L]
  • + *
  • Locale.ROOT
  • + * * *
  • Special cases for Chinese. When an input Locale has the * language "zh" (Chinese) and an empty script value, either "Hans" (Simplified) or @@ -2248,21 +2248,21 @@ public abstract class ResourceBundle { * is empty, no script is supplied. For example, for Locale("zh", "CN") * , the candidate list will be: *
      - *
    • [L("zh"), S("Hans"), C("CN")] - *
    • [L("zh"), S("Hans")] - *
    • [L("zh"), C("CN")] - *
    • [L("zh")] - *
    • Locale.ROOT + *
    • [L("zh"), S("Hans"), C("CN")]
    • + *
    • [L("zh"), S("Hans")]
    • + *
    • [L("zh"), C("CN")]
    • + *
    • [L("zh")]
    • + *
    • Locale.ROOT
    • *
    * * For Locale("zh", "TW"), the candidate list will be: *
      - *
    • [L("zh"), S("Hant"), C("TW")] - *
    • [L("zh"), S("Hant")] - *
    • [L("zh"), C("TW")] - *
    • [L("zh")] - *
    • Locale.ROOT - *
    + *
  • [L("zh"), S("Hant"), C("TW")]
  • + *
  • [L("zh"), S("Hant")]
  • + *
  • [L("zh"), C("TW")]
  • + *
  • [L("zh")]
  • + *
  • Locale.ROOT
  • + * * *
  • Special cases for Norwegian. Both Locale("no", "NO", * "NY") and Locale("nn", "NO") represent Norwegian @@ -2270,10 +2270,10 @@ public abstract class ResourceBundle { * list is generated up to [L("nn")], and then the following * candidates are added: * - *