- Building JDK 8 requires use of a version
- of JDK 7 that is at Update 7 or newer. JDK 8
- developers should not use JDK 8 as the boot
- JDK, to ensure that JDK 8 dependencies are
+ Building JDK 9 requires JDK 8. JDK 9
+ developers should not use JDK 9 as the boot
+ JDK, to ensure that JDK 9 dependencies are
not introduced into the parts of the system
- that are built with JDK 7.
+ that are built with JDK 8.
- The JDK 7 binaries can be downloaded from Oracle's
+ The JDK 8 binaries can be downloaded from Oracle's
JDK 7 download site.
- For build performance reasons
+ target="_blank">JDK 8 download site.
+ For build performance reasons it
is very important that this bootstrap JDK be made available
on the local disk of the machine doing the build.
You should add its bin directory
@@ -1454,9 +1453,7 @@
One of the top goals of the new build system is to improve the
build performance and decrease the time needed to build. This will
soon also apply to the java compilation when the Smart Javac wrapper
- is making its way into jdk8. It can be tried in the build-infra
- repository already. You are likely to find that the new build system
- is faster than the old one even without this feature.
+ is fully supported.
At the end of a successful execution of configure,
you will get a performance summary,
diff --git a/common/autoconf/boot-jdk.m4 b/common/autoconf/boot-jdk.m4
index edd6cec4ffb..ae679a9d469 100644
--- a/common/autoconf/boot-jdk.m4
+++ b/common/autoconf/boot-jdk.m4
@@ -82,10 +82,10 @@ AC_DEFUN([BOOTJDK_DO_CHECK],
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- [FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`]
+ [FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`]
if test "x$FOUND_CORRECT_VERSION" = x; then
AC_MSG_NOTICE([Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring])
- AC_MSG_NOTICE([(Your Boot JDK must be version 7, 8 or 9)])
+ AC_MSG_NOTICE([(Your Boot JDK must be version 8 or 9)])
BOOT_JDK_FOUND=no
else
# We're done! :-)
diff --git a/common/autoconf/build-performance.m4 b/common/autoconf/build-performance.m4
index 22a62748a13..7d4b8abb8da 100644
--- a/common/autoconf/build-performance.m4
+++ b/common/autoconf/build-performance.m4
@@ -89,7 +89,7 @@ AC_DEFUN([BPERF_CHECK_MEMORY_SIZE],
if test "x$FOUND_MEM" = xyes; then
AC_MSG_RESULT([$MEMORY_SIZE MB])
else
- AC_MSG_RESULT([could not detect memory size, defaulting to 1024 MB])
+ AC_MSG_RESULT([could not detect memory size, defaulting to $MEMORY_SIZE MB])
AC_MSG_WARN([This might seriously impact build performance!])
fi
])
diff --git a/common/autoconf/flags.m4 b/common/autoconf/flags.m4
index a3f0803b0fe..fc13f71b8aa 100644
--- a/common/autoconf/flags.m4
+++ b/common/autoconf/flags.m4
@@ -473,7 +473,8 @@ AC_DEFUN_ONCE([FLAGS_SETUP_COMPILER_FLAGS_FOR_JDK],
CFLAGS_JDK="${CFLAGS_JDK} -fno-strict-aliasing"
;;
ppc )
- # on ppc we don't prevent gcc to omit frame pointer nor strict-aliasing
+ # on ppc we don't prevent gcc to omit frame pointer but do prevent strict aliasing
+ CFLAGS_JDK="${CFLAGS_JDK} -fno-strict-aliasing"
;;
* )
CCXXFLAGS_JDK="$CCXXFLAGS_JDK -fno-omit-frame-pointer"
diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh
index fdf1c6dc829..b06c7d249cb 100644
--- a/common/autoconf/generated-configure.sh
+++ b/common/autoconf/generated-configure.sh
@@ -4243,7 +4243,7 @@ TOOLCHAIN_DESCRIPTION_xlc="IBM XL C/C++"
#CUSTOM_AUTOCONF_INCLUDE
# Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1396624161
+DATE_WHEN_GENERATED=1398196583
###############################################################################
#
@@ -19896,12 +19896,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -20228,12 +20228,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -20422,12 +20422,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -20609,12 +20609,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -20795,12 +20795,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -20981,12 +20981,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -21158,12 +21158,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -21476,12 +21476,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -21804,12 +21804,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -22019,12 +22019,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -22199,12 +22199,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -22407,12 +22407,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -22587,12 +22587,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -22795,12 +22795,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -22975,12 +22975,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -23183,12 +23183,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -23363,12 +23363,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -23558,12 +23558,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -23736,12 +23736,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -23932,12 +23932,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -24110,12 +24110,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -24305,12 +24305,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -24483,12 +24483,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -24679,12 +24679,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -24857,12 +24857,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -25034,12 +25034,12 @@ $as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK did not contain an rt.ja
BOOT_JDK_VERSION=`"$BOOT_JDK/bin/java" -version 2>&1 | head -n 1`
# Extra M4 quote needed to protect [] in grep expression.
- FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[789]\.'`
+ FOUND_CORRECT_VERSION=`echo $BOOT_JDK_VERSION | grep '\"1\.[89]\.'`
if test "x$FOUND_CORRECT_VERSION" = x; then
{ $as_echo "$as_me:${as_lineno-$LINENO}: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&5
$as_echo "$as_me: Potential Boot JDK found at $BOOT_JDK is incorrect JDK version ($BOOT_JDK_VERSION); ignoring" >&6;}
- { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 7, 8 or 9)" >&5
-$as_echo "$as_me: (Your Boot JDK must be version 7, 8 or 9)" >&6;}
+ { $as_echo "$as_me:${as_lineno-$LINENO}: (Your Boot JDK must be version 8 or 9)" >&5
+$as_echo "$as_me: (Your Boot JDK must be version 8 or 9)" >&6;}
BOOT_JDK_FOUND=no
else
# We're done! :-)
@@ -41662,7 +41662,8 @@ fi
CFLAGS_JDK="${CFLAGS_JDK} -fno-strict-aliasing"
;;
ppc )
- # on ppc we don't prevent gcc to omit frame pointer nor strict-aliasing
+ # on ppc we don't prevent gcc to omit frame pointer but do prevent strict aliasing
+ CFLAGS_JDK="${CFLAGS_JDK} -fno-strict-aliasing"
;;
* )
CCXXFLAGS_JDK="$CCXXFLAGS_JDK -fno-omit-frame-pointer"
@@ -48566,8 +48567,8 @@ $as_echo_n "checking for memory size... " >&6; }
{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $MEMORY_SIZE MB" >&5
$as_echo "$MEMORY_SIZE MB" >&6; }
else
- { $as_echo "$as_me:${as_lineno-$LINENO}: result: could not detect memory size, defaulting to 1024 MB" >&5
-$as_echo "could not detect memory size, defaulting to 1024 MB" >&6; }
+ { $as_echo "$as_me:${as_lineno-$LINENO}: result: could not detect memory size, defaulting to $MEMORY_SIZE MB" >&5
+$as_echo "could not detect memory size, defaulting to $MEMORY_SIZE MB" >&6; }
{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: This might seriously impact build performance!" >&5
$as_echo "$as_me: WARNING: This might seriously impact build performance!" >&2;}
fi
diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in
index c793d0e5c63..47861fcf2b8 100644
--- a/common/autoconf/spec.gmk.in
+++ b/common/autoconf/spec.gmk.in
@@ -261,6 +261,7 @@ BOOT_JDK_SOURCETARGET:=@BOOT_JDK_SOURCETARGET@
# Information about the build system
NUM_CORES:=@NUM_CORES@
+MEMORY_SIZE:=@MEMORY_SIZE@
# Enable sjavac support = use a javac server,
# multi core javac compilation and dependency tracking.
ENABLE_SJAVAC:=@ENABLE_SJAVAC@
diff --git a/common/bin/hgforest.sh b/common/bin/hgforest.sh
index 3ada41ee0cd..13f44425585 100644
--- a/common/bin/hgforest.sh
+++ b/common/bin/hgforest.sh
@@ -72,12 +72,21 @@ usage() {
exit 1
}
-
if [ "x" = "x$command" ] ; then
echo "ERROR: No command to hg supplied!"
usage
fi
+# Check if we can use fifos for monitoring sub-process completion.
+on_windows=`uname -s | egrep -ic -e 'cygwin|msys'`
+if [ ${on_windows} = "1" ]; then
+ # cygwin has (2014-04-18) broken (single writer only) FIFOs
+ # msys has (2014-04-18) no FIFOs.
+ have_fifos="false"
+else
+ have_fifos="true"
+fi
+
# Clean out the temporary directory that stores the pid files.
tmp=/tmp/forest.$$
rm -f -r ${tmp}
@@ -210,7 +219,19 @@ if [ "${command}" = "serve" ] ; then
) &
else
# Run the supplied command on all repos in parallel.
+
+ # n is the number of subprocess started or which might still be running.
n=0
+ if [ $have_fifos = "true" ]; then
+ # if we have fifos use them to detect command completion.
+ mkfifo ${tmp}/fifo
+ exec 3<>${tmp}/fifo
+ if [ "${sflag}" = "true" ] ; then
+ # force sequential
+ at_a_time=1
+ fi
+ fi
+
for i in ${repos} ${repos_extra} ; do
n=`expr ${n} '+' 1`
repopidfile=`echo ${i} | sed -e 's@./@@' -e 's@/@_@g'`
@@ -221,10 +242,11 @@ else
pull_base="${pull_extra}"
fi
done
+ pull_base="`echo ${pull_base} | sed -e 's@[/]*$@@'`"
(
(
if [ "${command}" = "clone" -o "${command}" = "fclone" -o "${command}" = "tclone" ] ; then
- pull_newrepo="`echo ${pull_base}/${i} | sed -e 's@\([^:]/\)//*@\1@g'`"
+ pull_newrepo="${pull_base}/${i}"
path="`dirname ${i}`"
if [ "${path}" != "." ] ; then
times=0
@@ -237,7 +259,7 @@ else
sleep 5
done
fi
- echo "hg clone ${pull_newrepo} ${i}" > ${status_output}
+ echo "hg${global_opts} clone ${pull_newrepo} ${i}" > ${status_output}
(PYTHONUNBUFFERED=true hg${global_opts} clone ${pull_newrepo} ${i}; echo "$?" > ${tmp}/${repopidfile}.pid.rc ) 2>&1 &
else
echo "cd ${i} && hg${global_opts} ${command} ${command_args}" > ${status_output}
@@ -246,21 +268,41 @@ else
echo $! > ${tmp}/${repopidfile}.pid
) 2>&1 | sed -e "s@^@${reponame}: @" > ${status_output}
+ if [ $have_fifos = "true" ]; then
+ echo "${reponame}" >&3
+ fi
) &
- if [ `expr ${n} '%' ${at_a_time}` -eq 0 -a "${sflag}" = "false" ] ; then
- sleep 2
- echo "Waiting 5 secs before spawning next background command." > ${status_output}
- sleep 3
- fi
-
- if [ "${sflag}" = "true" ] ; then
+ if [ $have_fifos = "true" ]; then
+ # check on count of running subprocesses and possibly wait for completion
+ if [ ${at_a_time} -lt ${n} ] ; then
+ # read will block until there are completed subprocesses
+ while read repo_done; do
+ n=`expr ${n} '-' 1`
+ if [ ${n} -lt ${at_a_time} ] ; then
+ # we should start more subprocesses
+ break;
+ fi
+ done <&3
+ fi
+ else
+ if [ "${sflag}" = "false" ] ; then
+ # Compare completions to starts
+ completed="`(ls -1 ${tmp}/*.pid.rc 2> /dev/null | wc -l) || echo 0`"
+ while [ ${at_a_time} -lt `expr ${n} '-' ${completed}` ] ; do
+ # sleep a short time to give time for something to complete
+ sleep 1
+ completed="`(ls -1 ${tmp}/*.pid.rc 2> /dev/null | wc -l) || echo 0`"
+ done
+ else
+ # complete this task before starting another.
wait
+ fi
fi
done
fi
-# Wait for all hg commands to complete
+# Wait for all subprocesses to complete
wait
# Terminate with exit 0 only if all subprocesses were successful
@@ -270,7 +312,7 @@ if [ -d ${tmp} ]; then
exit_code=`cat ${rc} | tr -d ' \n\r'`
if [ "${exit_code}" != "0" ] ; then
repo="`echo ${rc} | sed -e s@^${tmp}@@ -e 's@/*\([^/]*\)\.pid\.rc$@\1@' -e 's@_@/@g'`"
- echo "WARNING: ${repo} exited abnormally." > ${status_output}
+ echo "WARNING: ${repo} exited abnormally ($exit_code)" > ${status_output}
ec=1
fi
done
diff --git a/common/src/fixpath.c b/common/src/fixpath.c
index b30f58d6b51..9e8d352121a 100644
--- a/common/src/fixpath.c
+++ b/common/src/fixpath.c
@@ -109,7 +109,7 @@ char *replace_cygdrive_cygwin(char const *in)
void append(char **b, size_t *bl, size_t *u, char *add, size_t addlen)
{
- while ( (addlen+*u+1) > *bl) {
+ while ((addlen+*u+1) > *bl) {
*bl *= 2;
*b = (char*) realloc(*b, *bl);
}
@@ -118,7 +118,7 @@ void append(char **b, size_t *bl, size_t *u, char *add, size_t addlen)
}
/*
- * Creates a new string from in where the first occurance of sub is
+ * Creates a new string from in where the first occurrence of sub is
* replaced by rep.
*/
char *replace_substring(char *in, char *sub, char *rep)
@@ -246,7 +246,7 @@ char *fix_at_file(char const *in)
}
buffer = (char*) malloc(buflen);
- while((blocklen = fread(block,1,sizeof(block),atin)) > 0) {
+ while ((blocklen = fread(block, 1, sizeof(block), atin)) > 0) {
append(&buffer, &buflen, &used, block, blocklen);
}
buffer[used] = 0;
@@ -280,16 +280,21 @@ char * quote_arg(char const * in_arg) {
char *current = quoted;
int pass;
- if(strpbrk(in_arg, " \t\n\v\r\\\"") == NULL) {
+ if (strlen(in_arg) == 0) {
+ // empty string? explicitly quote it.
+ return _strdup("\"\"");
+ }
+
+ if (strpbrk(in_arg, " \t\n\v\r\\\"") == NULL) {
return _strdup(in_arg);
}
// process the arg twice. Once to calculate the size and then to copy it.
- for(pass=1; pass<=2; pass++) {
+ for (pass=1; pass<=2; pass++) {
char const *arg = in_arg;
// initial "
- if(pass == 2) {
+ if (pass == 2) {
*current = '\"';
}
current++;
@@ -328,7 +333,7 @@ char * quote_arg(char const * in_arg) {
*current = *arg;
}
current++;
- } while( *arg++ != '\0');
+ } while (*arg++ != '\0');
// allocate the buffer
if (pass == 1) {
@@ -362,7 +367,7 @@ int main(int argc, char const ** argv)
if (getenv("DEBUG_FIXPATH") != NULL) {
char const * cmdline = GetCommandLine();
- fprintf(stderr, "fixpath input line >%s<\n", strstr( cmdline , argv[1]));
+ fprintf(stderr, "fixpath input line >%s<\n", strstr(cmdline, argv[1]));
}
if (argv[1][1] == 'c' && argv[1][2] == '\0') {
@@ -399,7 +404,7 @@ int main(int argc, char const ** argv)
}
rc = SetEnvironmentVariable(var, val);
- if(!rc) {
+ if (!rc) {
// Could not set var for some reason. Try to report why.
const int msg_len = 80 + var_len + strlen(val);
char * msg = (char *) alloca(msg_len);
@@ -422,7 +427,7 @@ int main(int argc, char const ** argv)
// handle command and it's args.
while (i < argc) {
char const *replaced = replace_cygdrive(argv[i]);
- if(replaced[0] == '@') {
+ if (replaced[0] == '@') {
// Found at-file! Fix it!
replaced = fix_at_file(replaced);
}
@@ -433,7 +438,7 @@ int main(int argc, char const ** argv)
// determine the length of the line
line = NULL;
// args
- for(i = cmd; i < argc; i++) {
+ for (i = cmd; i < argc; i++) {
line += (ptrdiff_t) strlen(argv[i]);
}
// spaces and null
@@ -443,7 +448,7 @@ int main(int argc, char const ** argv)
// copy in args.
current = line;
- for(i = cmd; i < argc; i++) {
+ for (i = cmd; i < argc; i++) {
ptrdiff_t len = strlen(argv[i]);
if (i != cmd) {
*current++ = ' ';
@@ -457,16 +462,16 @@ int main(int argc, char const ** argv)
fprintf(stderr, "fixpath converted line >%s<\n", line);
}
- if(cmd == argc) {
+ if (cmd == argc) {
if (getenv("DEBUG_FIXPATH") != NULL) {
fprintf(stderr, "fixpath no command provided!\n");
}
exit(0);
}
- ZeroMemory(&si,sizeof(si));
+ ZeroMemory(&si, sizeof(si));
si.cb=sizeof(si);
- ZeroMemory(&pi,sizeof(pi));
+ ZeroMemory(&pi, sizeof(pi));
fflush(stderr);
fflush(stdout);
@@ -481,14 +486,14 @@ int main(int argc, char const ** argv)
NULL,
&si,
&pi);
- if(!rc) {
+ if (!rc) {
// Could not start process for some reason. Try to report why:
report_error("Could not start process!");
exit(126);
}
- WaitForSingleObject(pi.hProcess,INFINITE);
- GetExitCodeProcess(pi.hProcess,&exitCode);
+ WaitForSingleObject(pi.hProcess, INFINITE);
+ GetExitCodeProcess(pi.hProcess, &exitCode);
if (getenv("DEBUG_FIXPATH") != NULL) {
for (i=0; i noTypesList[] = {};
/** true if represents enum type */
private boolean isEnum;
private static final Bridge bridge =
- (Bridge)AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
+ AccessController.doPrivileged(
+ new PrivilegedAction() {
+ public Bridge run() {
return Bridge.get() ;
}
}
@@ -98,7 +99,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* is returned if the specified class does not implement
* java.io.Serializable or java.io.Externalizable.
*/
- static final ObjectStreamClass lookup(Class cl)
+ static final ObjectStreamClass lookup(Class> cl)
{
ObjectStreamClass desc = lookupInternal(cl);
if (desc.isSerializable() || desc.isExternalizable())
@@ -110,7 +111,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* Find the class descriptor for the specified class.
* Package access only so it can be called from ObjectIn/OutStream.
*/
- static ObjectStreamClass lookupInternal(Class cl)
+ static ObjectStreamClass lookupInternal(Class> cl)
{
/* Synchronize on the hashtable so no two threads will do
* this at the same time.
@@ -121,14 +122,14 @@ public class ObjectStreamClass implements java.io.Serializable {
desc = findDescriptorFor(cl);
if (desc == null) {
/* Check if it's serializable */
- boolean serializable = classSerializable.isAssignableFrom(cl);
+ boolean serializable = Serializable.class.isAssignableFrom(cl);
/* If the class is only Serializable,
* lookup the descriptor for the superclass.
*/
ObjectStreamClass superdesc = null;
if (serializable) {
- Class superclass = cl.getSuperclass();
+ Class> superclass = cl.getSuperclass();
if (superclass != null)
superdesc = lookup(superclass);
}
@@ -141,7 +142,7 @@ public class ObjectStreamClass implements java.io.Serializable {
if (serializable) {
externalizable =
((superdesc != null) && superdesc.isExternalizable()) ||
- classExternalizable.isAssignableFrom(cl);
+ Externalizable.class.isAssignableFrom(cl);
if (externalizable) {
serializable = false;
}
@@ -185,7 +186,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* that have evolved from a common root class and agree to be serialized
* and deserialized using a common format.
*/
- public static final long getSerialVersionUID( java.lang.Class clazz) {
+ public static final long getSerialVersionUID( java.lang.Class> clazz) {
ObjectStreamClass theosc = ObjectStreamClass.lookup( clazz );
if( theosc != null )
{
@@ -219,7 +220,7 @@ public class ObjectStreamClass implements java.io.Serializable {
/**
* Return the actual (computed) serialVersionUID for this class.
*/
- public static final long getActualSerialVersionUID( java.lang.Class clazz )
+ public static final long getActualSerialVersionUID( java.lang.Class> clazz )
{
ObjectStreamClass theosc = ObjectStreamClass.lookup( clazz );
if( theosc != null )
@@ -249,7 +250,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* Return the class in the local VM that this version is mapped to.
* Null is returned if there is no corresponding local class.
*/
- public final Class forClass() {
+ public final Class> forClass() {
return ofClass;
}
@@ -349,7 +350,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* Create a new ObjectStreamClass from a loaded class.
* Don't call this directly, call lookup instead.
*/
- private ObjectStreamClass(java.lang.Class cl, ObjectStreamClass superdesc,
+ private ObjectStreamClass(java.lang.Class> cl, ObjectStreamClass superdesc,
boolean serial, boolean extern)
{
ofClass = cl; /* created from this class */
@@ -433,7 +434,7 @@ public class ObjectStreamClass implements java.io.Serializable {
if (initialized)
return;
- final Class cl = ofClass;
+ final Class> cl = ofClass;
if (!serializable ||
externalizable ||
@@ -561,9 +562,9 @@ public class ObjectStreamClass implements java.io.Serializable {
* will call it as necessary.
*/
writeObjectMethod = getPrivateMethod( cl, "writeObject",
- new Class[] { java.io.ObjectOutputStream.class }, Void.TYPE ) ;
+ new Class>[] { java.io.ObjectOutputStream.class }, Void.TYPE ) ;
readObjectMethod = getPrivateMethod( cl, "readObject",
- new Class[] { java.io.ObjectInputStream.class }, Void.TYPE ) ;
+ new Class>[] { java.io.ObjectInputStream.class }, Void.TYPE ) ;
}
return null;
}
@@ -589,9 +590,9 @@ public class ObjectStreamClass implements java.io.Serializable {
* class, or null if none found. Access checks are disabled on the
* returned method (if any).
*/
- private static Method getPrivateMethod(Class cl, String name,
- Class[] argTypes,
- Class returnType)
+ private static Method getPrivateMethod(Class> cl, String name,
+ Class>[] argTypes,
+ Class> returnType)
{
try {
Method meth = cl.getDeclaredMethod(name, argTypes);
@@ -653,7 +654,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* Fill in the reflected Fields that will be used
* for reading.
*/
- final void setClass(Class cl) throws InvalidClassException {
+ final void setClass(Class> cl) throws InvalidClassException {
if (cl == null) {
localClassDesc = null;
@@ -920,9 +921,9 @@ public class ObjectStreamClass implements java.io.Serializable {
* Access checks are disabled on the returned constructor (if any), since
* the defining class may still be non-public.
*/
- private static Constructor getExternalizableConstructor(Class cl) {
+ private static Constructor getExternalizableConstructor(Class> cl) {
try {
- Constructor cons = cl.getDeclaredConstructor(new Class[0]);
+ Constructor cons = cl.getDeclaredConstructor(new Class>[0]);
cons.setAccessible(true);
return ((cons.getModifiers() & Modifier.PUBLIC) != 0) ?
cons : null;
@@ -936,15 +937,15 @@ public class ObjectStreamClass implements java.io.Serializable {
* superclass, or null if none found. Access checks are disabled on the
* returned constructor (if any).
*/
- private static Constructor getSerializableConstructor(Class cl) {
- Class initCl = cl;
+ private static Constructor getSerializableConstructor(Class> cl) {
+ Class> initCl = cl;
while (Serializable.class.isAssignableFrom(initCl)) {
if ((initCl = initCl.getSuperclass()) == null) {
return null;
}
}
try {
- Constructor cons = initCl.getDeclaredConstructor(new Class[0]);
+ Constructor cons = initCl.getDeclaredConstructor(new Class>[0]);
int mods = cons.getModifiers();
if ((mods & Modifier.PRIVATE) != 0 ||
((mods & (Modifier.PUBLIC | Modifier.PROTECTED)) == 0 &&
@@ -1049,7 +1050,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* items to the hash accumulating in the digest stream.
* Fold the hash into a long. Use the SHA secure hash function.
*/
- private static long _computeSerialVersionUID(Class cl) {
+ private static long _computeSerialVersionUID(Class> cl) {
if (DEBUG_SVUID)
msg( "Computing SerialVersionUID for " + cl ) ;
ByteArrayOutputStream devnull = new ByteArrayOutputStream(512);
@@ -1103,7 +1104,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* them from its computation.
*/
- Class interfaces[] = cl.getInterfaces();
+ Class> interfaces[] = cl.getInterfaces();
Arrays.sort(interfaces, compareClassByName);
for (int i = 0; i < interfaces.length; i++) {
@@ -1233,7 +1234,7 @@ public class ObjectStreamClass implements java.io.Serializable {
return h;
}
- private static long computeStructuralUID(com.sun.corba.se.impl.io.ObjectStreamClass osc, Class cl) {
+ private static long computeStructuralUID(com.sun.corba.se.impl.io.ObjectStreamClass osc, Class> cl) {
ByteArrayOutputStream devnull = new ByteArrayOutputStream(512);
long h = 0;
@@ -1253,7 +1254,7 @@ public class ObjectStreamClass implements java.io.Serializable {
DataOutputStream data = new DataOutputStream(mdo);
// Get SUID of parent
- Class parent = cl.getSuperclass();
+ Class> parent = cl.getSuperclass();
if ((parent != null))
// SerialBug 1; acc. to spec the one for
// java.lang.object
@@ -1309,10 +1310,10 @@ public class ObjectStreamClass implements java.io.Serializable {
/**
* Compute the JVM signature for the class.
*/
- static String getSignature(Class clazz) {
+ static String getSignature(Class> clazz) {
String type = null;
if (clazz.isArray()) {
- Class cl = clazz;
+ Class> cl = clazz;
int dimensions = 0;
while (cl.isArray()) {
dimensions++;
@@ -1358,7 +1359,7 @@ public class ObjectStreamClass implements java.io.Serializable {
sb.append("(");
- Class[] params = meth.getParameterTypes(); // avoid clone
+ Class>[] params = meth.getParameterTypes(); // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(getSignature(params[j]));
}
@@ -1375,7 +1376,7 @@ public class ObjectStreamClass implements java.io.Serializable {
sb.append("(");
- Class[] params = cons.getParameterTypes(); // avoid clone
+ Class>[] params = cons.getParameterTypes(); // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(getSignature(params[j]));
}
@@ -1395,7 +1396,7 @@ public class ObjectStreamClass implements java.io.Serializable {
* The entries are extended from java.lang.ref.SoftReference so the
* gc will be able to free them if needed.
*/
- private static ObjectStreamClass findDescriptorFor(Class cl) {
+ private static ObjectStreamClass findDescriptorFor(Class> cl) {
int hash = cl.hashCode();
int index = (hash & 0x7FFFFFFF) % descriptorFor.length;
@@ -1442,7 +1443,7 @@ public class ObjectStreamClass implements java.io.Serializable {
descriptorFor[index] = e;
}
- private static Field[] getDeclaredFields(final Class clz) {
+ private static Field[] getDeclaredFields(final Class> clz) {
return (Field[]) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
return clz.getDeclaredFields();
@@ -1476,7 +1477,7 @@ public class ObjectStreamClass implements java.io.Serializable {
/*
* Class that is a descriptor for in this virtual machine.
*/
- private Class ofClass;
+ private Class> ofClass;
/*
* True if descriptor for a proxy class.
@@ -1548,30 +1549,17 @@ public class ObjectStreamClass implements java.io.Serializable {
* Returns true if the given class defines a static initializer method,
* false otherwise.
*/
- private static boolean hasStaticInitializer(Class cl) {
+ private static boolean hasStaticInitializer(Class> cl) {
if (hasStaticInitializerMethod == null) {
- Class classWithThisMethod = null;
+ Class> classWithThisMethod = null;
try {
- try {
- // When using rip-int with Merlin or when this is a Merlin
- // workspace, the method we want is in sun.misc.ClassReflector
- // and absent from java.io.ObjectStreamClass.
- //
- // When compiling rip-int with JDK 1.3.x, we have to get it
- // from java.io.ObjectStreamClass.
- classWithThisMethod = Class.forName("sun.misc.ClassReflector");
- } catch (ClassNotFoundException cnfe) {
- // Do nothing. This is either not a Merlin workspace,
- // or rip-int is being compiled with something other than
- // Merlin, probably JDK 1.3. Fall back on java.io.ObjectStreaClass.
- }
if (classWithThisMethod == null)
classWithThisMethod = java.io.ObjectStreamClass.class;
hasStaticInitializerMethod =
classWithThisMethod.getDeclaredMethod("hasStaticInitializer",
- new Class[] { Class.class });
+ new Class>[] { Class.class });
} catch (NoSuchMethodException ex) {
}
@@ -1596,22 +1584,6 @@ public class ObjectStreamClass implements java.io.Serializable {
}
- /* The Class Object for java.io.Serializable */
- private static Class classSerializable = null;
- private static Class classExternalizable = null;
-
- /*
- * Resolve java.io.Serializable at load time.
- */
- static {
- try {
- classSerializable = Class.forName("java.io.Serializable");
- classExternalizable = Class.forName("java.io.Externalizable");
- } catch (Throwable e) {
- System.err.println("Could not load java.io.Serializable or java.io.Externalizable.");
- }
- }
-
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = -6120832682080437368L;
@@ -1649,8 +1621,8 @@ public class ObjectStreamClass implements java.io.Serializable {
private static class CompareClassByName implements Comparator {
public int compare(Object o1, Object o2) {
- Class c1 = (Class)o1;
- Class c2 = (Class)o2;
+ Class> c1 = (Class)o1;
+ Class> c2 = (Class)o2;
return (c1.getName()).compareTo(c2.getName());
}
}
@@ -1764,12 +1736,12 @@ public class ObjectStreamClass implements java.io.Serializable {
*
* Copied from the Merlin java.io.ObjectStreamClass.
*/
- private static Method getInheritableMethod(Class cl, String name,
- Class[] argTypes,
- Class returnType)
+ private static Method getInheritableMethod(Class> cl, String name,
+ Class>[] argTypes,
+ Class> returnType)
{
Method meth = null;
- Class defCl = cl;
+ Class> defCl = cl;
while (defCl != null) {
try {
meth = defCl.getDeclaredMethod(name, argTypes);
@@ -1801,7 +1773,7 @@ public class ObjectStreamClass implements java.io.Serializable {
*
* Copied from the Merlin java.io.ObjectStreamClass.
*/
- private static boolean packageEquals(Class cl1, Class cl2) {
+ private static boolean packageEquals(Class> cl1, Class> cl2) {
Package pkg1 = cl1.getPackage(), pkg2 = cl2.getPackage();
return ((pkg1 == pkg2) || ((pkg1 != null) && (pkg1.equals(pkg2))));
}
diff --git a/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClassUtil_1_3.java b/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClassUtil_1_3.java
index 6fb95dbccad..8a4fdc0ee34 100644
--- a/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClassUtil_1_3.java
+++ b/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClassUtil_1_3.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2000, 2002, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,7 +94,7 @@ public final class ObjectStreamClassUtil_1_3 {
});
}
- public static long computeStructuralUID(boolean hasWriteObject, Class cl) {
+ public static long computeStructuralUID(boolean hasWriteObject, Class> cl) {
ByteArrayOutputStream devnull = new ByteArrayOutputStream(512);
long h = 0;
@@ -119,7 +119,7 @@ public final class ObjectStreamClassUtil_1_3 {
// Object method in there
// Get SUID of parent
- Class parent = cl.getSuperclass();
+ Class> parent = cl.getSuperclass();
if ((parent != null) && (parent != java.lang.Object.class)) {
boolean hasWriteObjectFlag = false;
Class [] args = {java.io.ObjectOutputStream.class};
@@ -503,19 +503,6 @@ public final class ObjectStreamClassUtil_1_3 {
Class classWithThisMethod = null;
try {
- try {
- // When using rip-int with Merlin or when this is a Merlin
- // workspace, the method we want is in sun.misc.ClassReflector
- // and absent from java.io.ObjectStreamClass.
- //
- // When compiling rip-int with JDK 1.3.x, we have to get it
- // from java.io.ObjectStreamClass.
- classWithThisMethod = Class.forName("sun.misc.ClassReflector");
- } catch (ClassNotFoundException cnfe) {
- // Do nothing. This is either not a Merlin workspace,
- // or rip-int is being compiled with something other than
- // Merlin, probably JDK 1.3. Fall back on java.io.ObjectStreaClass.
- }
if (classWithThisMethod == null)
classWithThisMethod = java.io.ObjectStreamClass.class;
diff --git a/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClass_1_3_1.java b/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClass_1_3_1.java
index 891a4887123..3e06edc2550 100644
--- a/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClass_1_3_1.java
+++ b/corba/src/share/classes/com/sun/corba/se/impl/orbutil/ObjectStreamClass_1_3_1.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -53,6 +53,7 @@ import java.io.DataOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.InvalidClassException;
import java.io.Serializable;
+import java.io.Externalizable;
import java.util.Arrays;
import java.util.Comparator;
@@ -88,7 +89,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
public static final long kDefaultUID = -1;
private static Object noArgsList[] = {};
- private static Class noTypesList[] = {};
+ private static Class> noTypesList[] = {};
private static Hashtable translatedFields;
@@ -96,7 +97,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
* is returned if the specified class does not implement
* java.io.Serializable or java.io.Externalizable.
*/
- static final ObjectStreamClass_1_3_1 lookup(Class cl)
+ static final ObjectStreamClass_1_3_1 lookup(Class> cl)
{
ObjectStreamClass_1_3_1 desc = lookupInternal(cl);
if (desc.isSerializable() || desc.isExternalizable())
@@ -108,7 +109,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
* Find the class descriptor for the specified class.
* Package access only so it can be called from ObjectIn/OutStream.
*/
- static ObjectStreamClass_1_3_1 lookupInternal(Class cl)
+ static ObjectStreamClass_1_3_1 lookupInternal(Class> cl)
{
/* Synchronize on the hashtable so no two threads will do
* this at the same time.
@@ -122,13 +123,13 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
}
/* Check if it's serializable */
- boolean serializable = classSerializable.isAssignableFrom(cl);
+ boolean serializable = Serializable.class.isAssignableFrom(cl);
/* If the class is only Serializable,
* lookup the descriptor for the superclass.
*/
ObjectStreamClass_1_3_1 superdesc = null;
if (serializable) {
- Class superclass = cl.getSuperclass();
+ Class> superclass = cl.getSuperclass();
if (superclass != null)
superdesc = lookup(superclass);
}
@@ -141,7 +142,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
if (serializable) {
externalizable =
((superdesc != null) && superdesc.isExternalizable()) ||
- classExternalizable.isAssignableFrom(cl);
+ Externalizable.class.isAssignableFrom(cl);
if (externalizable) {
serializable = false;
}
@@ -170,7 +171,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
* that have evolved from a common root class and agree to be serialized
* and deserialized using a common format.
*/
- public static final long getSerialVersionUID( java.lang.Class clazz) {
+ public static final long getSerialVersionUID( java.lang.Class> clazz) {
ObjectStreamClass_1_3_1 theosc = ObjectStreamClass_1_3_1.lookup( clazz );
if( theosc != null )
{
@@ -204,7 +205,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
/**
* Return the actual (computed) serialVersionUID for this class.
*/
- public static final long getActualSerialVersionUID( java.lang.Class clazz )
+ public static final long getActualSerialVersionUID( java.lang.Class> clazz )
{
ObjectStreamClass_1_3_1 theosc = ObjectStreamClass_1_3_1.lookup( clazz );
if( theosc != null )
@@ -234,7 +235,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
* Return the class in the local VM that this version is mapped to.
* Null is returned if there is no corresponding local class.
*/
- public final Class forClass() {
+ public final Class> forClass() {
return ofClass;
}
@@ -333,7 +334,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
* Create a new ObjectStreamClass_1_3_1 from a loaded class.
* Don't call this directly, call lookup instead.
*/
- private ObjectStreamClass_1_3_1(java.lang.Class cl, ObjectStreamClass_1_3_1 superdesc,
+ private ObjectStreamClass_1_3_1(java.lang.Class> cl, ObjectStreamClass_1_3_1 superdesc,
boolean serial, boolean extern)
{
ofClass = cl; /* created from this class */
@@ -376,7 +377,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
private void init() {
synchronized (lock) {
- final Class cl = ofClass;
+ final Class> cl = ofClass;
if (fields != null) // already initialized
return;
@@ -558,7 +559,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
* will call it as necessary.
*/
try {
- Class[] args = {java.io.ObjectOutputStream.class};
+ Class>[] args = {java.io.ObjectOutputStream.class};
writeObjectMethod = cl.getDeclaredMethod("writeObject", args);
hasWriteObjectMethod = true;
int mods = writeObjectMethod.getModifiers();
@@ -578,7 +579,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
* ObjectInputStream so it can all the method directly.
*/
try {
- Class[] args = {java.io.ObjectInputStream.class};
+ Class>[] args = {java.io.ObjectInputStream.class};
readObjectMethod = cl.getDeclaredMethod("readObject", args);
int mods = readObjectMethod.getModifiers();
@@ -629,11 +630,11 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
if (translation != null)
return translation;
else {
- Class osfClass = com.sun.corba.se.impl.orbutil.ObjectStreamField.class;
+ Class> osfClass = com.sun.corba.se.impl.orbutil.ObjectStreamField.class;
translation = (Object[])java.lang.reflect.Array.newInstance(osfClass, objs.length);
Object arg[] = new Object[2];
- Class types[] = {String.class, Class.class};
+ Class> types[] = {String.class, Class.class};
Constructor constructor = osfClass.getDeclaredConstructor(types);
for (int i = fields.length -1; i >= 0; i--){
arg[0] = fields[i].getName();
@@ -804,7 +805,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
}
}
- private static long computeStructuralUID(ObjectStreamClass_1_3_1 osc, Class cl) {
+ private static long computeStructuralUID(ObjectStreamClass_1_3_1 osc, Class> cl) {
ByteArrayOutputStream devnull = new ByteArrayOutputStream(512);
long h = 0;
@@ -824,7 +825,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
DataOutputStream data = new DataOutputStream(mdo);
// Get SUID of parent
- Class parent = cl.getSuperclass();
+ Class> parent = cl.getSuperclass();
if ((parent != null))
// SerialBug 1; acc. to spec the one for
// java.lang.object
@@ -910,10 +911,10 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
/**
* Compute the JVM signature for the class.
*/
- static String getSignature(Class clazz) {
+ static String getSignature(Class> clazz) {
String type = null;
if (clazz.isArray()) {
- Class cl = clazz;
+ Class> cl = clazz;
int dimensions = 0;
while (cl.isArray()) {
dimensions++;
@@ -959,7 +960,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
sb.append("(");
- Class[] params = meth.getParameterTypes(); // avoid clone
+ Class>[] params = meth.getParameterTypes(); // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(getSignature(params[j]));
}
@@ -976,7 +977,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
sb.append("(");
- Class[] params = cons.getParameterTypes(); // avoid clone
+ Class>[] params = cons.getParameterTypes(); // avoid clone
for (int j = 0; j < params.length; j++) {
sb.append(getSignature(params[j]));
}
@@ -996,7 +997,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
* The entries are extended from java.lang.ref.SoftReference so the
* gc will be able to free them if needed.
*/
- private static ObjectStreamClass_1_3_1 findDescriptorFor(Class cl) {
+ private static ObjectStreamClass_1_3_1 findDescriptorFor(Class> cl) {
int hash = cl.hashCode();
int index = (hash & 0x7FFFFFFF) % descriptorFor.length;
@@ -1077,7 +1078,7 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
/*
* Class that is a descriptor for in this virtual machine.
*/
- private Class ofClass;
+ private Class> ofClass;
/*
* True if descriptor for a proxy class.
@@ -1130,22 +1131,6 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
/* Get the private static final field for serial version UID */
// private static native long getSerialVersionUIDField(Class cl);
- /* The Class Object for java.io.Serializable */
- private static Class classSerializable = null;
- private static Class classExternalizable = null;
-
- /*
- * Resolve java.io.Serializable at load time.
- */
- static {
- try {
- classSerializable = Class.forName("java.io.Serializable");
- classExternalizable = Class.forName("java.io.Externalizable");
- } catch (Throwable e) {
- System.err.println("Could not load java.io.Serializable or java.io.Externalizable.");
- }
- }
-
/** use serialVersionUID from JDK 1.1. for interoperability */
private static final long serialVersionUID = -6120832682080437368L;
@@ -1183,8 +1168,8 @@ public class ObjectStreamClass_1_3_1 implements java.io.Serializable {
private static class CompareClassByName implements Comparator {
public int compare(Object o1, Object o2) {
- Class c1 = (Class)o1;
- Class c2 = (Class)o2;
+ Class> c1 = (Class)o1;
+ Class> c2 = (Class)o2;
return (c1.getName()).compareTo(c2.getName());
}
}
diff --git a/corba/src/share/classes/org/omg/CORBA/ORB.java b/corba/src/share/classes/org/omg/CORBA/ORB.java
index 58649f00630..2250ba066a2 100644
--- a/corba/src/share/classes/org/omg/CORBA/ORB.java
+++ b/corba/src/share/classes/org/omg/CORBA/ORB.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,6 +36,8 @@ import java.io.FileInputStream;
import java.security.AccessController;
import java.security.PrivilegedAction;
+import sun.reflect.misc.ReflectUtil;
+
/**
* A class providing APIs for the CORBA Object Request Broker
* features. The ORB class also provides
@@ -161,6 +163,20 @@ import java.security.PrivilegedAction;
*
* An application or applet can be initialized in one or more ORBs.
* ORB initialization is a bootstrap call into the CORBA world.
+ *
+ *
+ * @implNote
+ * As described above it is possible to specify, at runtime, an alternative ORBSingleton class and
+ * an alternative ORB implementation class, via the system properties {@code org.omg.CORBA.ORBSingletonClass}
+ * and {@code org.omg.CORBA.ORBClass} respectively.
+ * The class loading strategy is organized, such that, in the case of the ORBSingleton
+ * the system class loader is used to load the alternative singleton ORB.
+ * Thus, it is necessary that an application's CLASSPATH
+ * includes the classes for this alternative ORBSingleton, when specified.
+ *
+ * In the case of specifying an alternative ORB implementation class, the loading
+ * strategy will use the thread context class loader, as appropriate.
+ *
* @since JDK1.2
*/
abstract public class ORB {
@@ -289,20 +305,38 @@ abstract public class ORB {
(className.equals("com.sun.corba.se.impl.orb.ORBSingleton"))) {
singleton = new com.sun.corba.se.impl.orb.ORBSingleton();
} else {
- singleton = create_impl(className);
+ singleton = create_impl_with_systemclassloader(className);
}
}
return singleton;
}
- private static ORB create_impl(String className) {
+ private static ORB create_impl_with_systemclassloader(String className) {
+ try {
+ ReflectUtil.checkPackageAccess(className);
+ ClassLoader cl = ClassLoader.getSystemClassLoader();
+ Class orbBaseClass = org.omg.CORBA.ORB.class;
+ Class> singletonOrbClass = Class.forName(className, true, cl).asSubclass(orbBaseClass);
+ return (ORB)singletonOrbClass.newInstance();
+ } catch (Throwable ex) {
+ SystemException systemException = new INITIALIZE(
+ "can't instantiate default ORB implementation " + className);
+ systemException.initCause(ex);
+ throw systemException;
+ }
+ }
+
+ private static ORB create_impl(String className) {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null)
cl = ClassLoader.getSystemClassLoader();
try {
- return (ORB) Class.forName(className, true, cl).newInstance();
+ ReflectUtil.checkPackageAccess(className);
+ Class orbBaseClass = org.omg.CORBA.ORB.class;
+ Class> orbClass = Class.forName(className, true, cl).asSubclass(orbBaseClass);
+ return (ORB)orbClass.newInstance();
} catch (Throwable ex) {
SystemException systemException = new INITIALIZE(
"can't instantiate default ORB implementation " + className);
@@ -346,7 +380,6 @@ abstract public class ORB {
} else {
orb = create_impl(className);
}
-
orb.set_parameters(args, props);
return orb;
}
@@ -377,7 +410,6 @@ abstract public class ORB {
} else {
orb = create_impl(className);
}
-
orb.set_parameters(app, props);
return orb;
}
@@ -573,7 +605,7 @@ abstract public class ORB {
try {
// First try to load the OperationDef class
String opDefClassName = "org.omg.CORBA.OperationDef";
- Class opDefClass = null;
+ Class> opDefClass = null;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if ( cl == null )
@@ -583,7 +615,7 @@ abstract public class ORB {
// OK, we loaded OperationDef. Now try to get the
// create_operation_list(OperationDef oper) method.
- Class[] argc = { opDefClass };
+ Class>[] argc = { opDefClass };
java.lang.reflect.Method meth =
this.getClass().getMethod("create_operation_list", argc);
diff --git a/hotspot/.hgtags b/hotspot/.hgtags
index 856ce390fa1..8999d15f5a8 100644
--- a/hotspot/.hgtags
+++ b/hotspot/.hgtags
@@ -410,3 +410,6 @@ b2fee789d23f3cdabb3db4e51af43038e5692d3a jdk9-b03
bdc5311e1db7598589b77015119b821bf8c828bd jdk9-b05
52377a30a3f87b62d6135706997b8c7a47366e37 jdk9-b06
52f7edf2589d9f9d35db3008bc5377f279de9c18 jdk9-b07
+4dedef5e51ed3a36677a8ba82949fc517ad64162 jdk9-b08
+05e8f5242c26ba45d4fa947e4f4f54c058c9b522 jdk9-b09
+ebc44d040cd149d2120d69fe183a3dae7840f4b4 jdk9-b10
diff --git a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp
index 9d4d13bf663..c809d2b2694 100644
--- a/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/interp_masm_sparc.cpp
@@ -2003,7 +2003,7 @@ void InterpreterMacroAssembler::profile_arguments_type(Register callee, Register
}
} else {
assert(MethodData::profile_return(), "either profile call args or call ret");
- update_mdp_by_constant(in_bytes(ReturnTypeEntry::size()));
+ update_mdp_by_constant(in_bytes(TypeEntriesAtCall::return_only_size()));
}
// mdp points right after the end of the
diff --git a/hotspot/src/cpu/x86/vm/interp_masm_x86.cpp b/hotspot/src/cpu/x86/vm/interp_masm_x86.cpp
index 799be13037f..42a826d7710 100644
--- a/hotspot/src/cpu/x86/vm/interp_masm_x86.cpp
+++ b/hotspot/src/cpu/x86/vm/interp_masm_x86.cpp
@@ -137,7 +137,7 @@ void InterpreterMacroAssembler::profile_arguments_type(Register mdp, Register ca
movptr(Address(rbp, frame::interpreter_frame_mdx_offset * wordSize), mdp);
} else {
assert(MethodData::profile_return(), "either profile call args or call ret");
- update_mdp_by_constant(mdp, in_bytes(ReturnTypeEntry::size()));
+ update_mdp_by_constant(mdp, in_bytes(TypeEntriesAtCall::return_only_size()));
}
// mdp points right after the end of the
diff --git a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
index 6d7ed620be3..8a8b6ad6066 100644
--- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
+++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp
@@ -3188,8 +3188,8 @@ void LIRGenerator::profile_arguments(ProfileCall* x) {
#ifdef ASSERT
Bytecodes::Code code = x->method()->raw_code_at_bci(x->bci_of_invoke());
int n = x->nb_profiled_args();
- assert(MethodData::profile_parameters() && x->inlined() &&
- ((code == Bytecodes::_invokedynamic && n <= 1) || (code == Bytecodes::_invokehandle && n <= 2)),
+ assert(MethodData::profile_parameters() && (MethodData::profile_arguments_jsr292_only() ||
+ (x->inlined() && ((code == Bytecodes::_invokedynamic && n <= 1) || (code == Bytecodes::_invokehandle && n <= 2)))),
"only at JSR292 bytecodes");
#endif
}
diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp
index 00157d7eccd..aedeecc5db5 100644
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp
@@ -564,11 +564,11 @@ void CompactibleFreeListSpace::reportIndexedFreeListStatistics() const {
"--------------------------------\n");
size_t total_size = totalSizeInIndexedFreeLists();
size_t free_blocks = numFreeBlocksInIndexedFreeLists();
- gclog_or_tty->print("Total Free Space: %d\n", total_size);
- gclog_or_tty->print("Max Chunk Size: %d\n", maxChunkSizeInIndexedFreeLists());
- gclog_or_tty->print("Number of Blocks: %d\n", free_blocks);
+ gclog_or_tty->print("Total Free Space: " SIZE_FORMAT "\n", total_size);
+ gclog_or_tty->print("Max Chunk Size: " SIZE_FORMAT "\n", maxChunkSizeInIndexedFreeLists());
+ gclog_or_tty->print("Number of Blocks: " SIZE_FORMAT "\n", free_blocks);
if (free_blocks != 0) {
- gclog_or_tty->print("Av. Block Size: %d\n", total_size/free_blocks);
+ gclog_or_tty->print("Av. Block Size: " SIZE_FORMAT "\n", total_size/free_blocks);
}
}
@@ -2152,7 +2152,7 @@ void CompactibleFreeListSpace::beginSweepFLCensus(
for (i = IndexSetStart; i < IndexSetSize; i += IndexSetStride) {
AdaptiveFreeList* fl = &_indexedFreeList[i];
if (PrintFLSStatistics > 1) {
- gclog_or_tty->print("size[%d] : ", i);
+ gclog_or_tty->print("size[" SIZE_FORMAT "] : ", i);
}
fl->compute_desired(inter_sweep_current, inter_sweep_estimate, intra_sweep_estimate);
fl->set_coal_desired((ssize_t)((double)fl->desired() * CMSSmallCoalSurplusPercent));
@@ -2683,7 +2683,8 @@ void CFLS_LAB::compute_desired_plab_size() {
_global_num_workers[i] = 0;
_global_num_blocks[i] = 0;
if (PrintOldPLAB) {
- gclog_or_tty->print_cr("[%d]: %d", i, (size_t)_blocks_to_claim[i].average());
+ gclog_or_tty->print_cr("[" SIZE_FORMAT "]: " SIZE_FORMAT,
+ i, (size_t)_blocks_to_claim[i].average());
}
}
}
@@ -2722,7 +2723,7 @@ void CFLS_LAB::retire(int tid) {
}
}
if (PrintOldPLAB) {
- gclog_or_tty->print_cr("%d[%d]: %d/%d/%d",
+ gclog_or_tty->print_cr("%d[" SIZE_FORMAT "]: " SIZE_FORMAT "/" SIZE_FORMAT "/" SIZE_FORMAT,
tid, i, num_retire, _num_blocks[i], (size_t)_blocks_to_claim[i].average());
}
// Reset stats for next round
diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
index d71e82799d2..40ff7b30e40 100644
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp
@@ -1512,6 +1512,8 @@ bool CMSCollector::shouldConcurrentCollect() {
gclog_or_tty->print_cr("cms_allocation_rate=%g", stats().cms_allocation_rate());
gclog_or_tty->print_cr("occupancy=%3.7f", _cmsGen->occupancy());
gclog_or_tty->print_cr("initiatingOccupancy=%3.7f", _cmsGen->initiating_occupancy());
+ gclog_or_tty->print_cr("cms_time_since_begin=%3.7f", stats().cms_time_since_begin());
+ gclog_or_tty->print_cr("cms_time_since_end=%3.7f", stats().cms_time_since_end());
gclog_or_tty->print_cr("metadata initialized %d",
MetaspaceGC::should_concurrent_collect());
}
@@ -1574,6 +1576,28 @@ bool CMSCollector::shouldConcurrentCollect() {
return true;
}
+ // CMSTriggerInterval starts a CMS cycle if enough time has passed.
+ if (CMSTriggerInterval >= 0) {
+ if (CMSTriggerInterval == 0) {
+ // Trigger always
+ return true;
+ }
+
+ // Check the CMS time since begin (we do not check the stats validity
+ // as we want to be able to trigger the first CMS cycle as well)
+ if (stats().cms_time_since_begin() >= (CMSTriggerInterval / ((double) MILLIUNITS))) {
+ if (Verbose && PrintGCDetails) {
+ if (stats().valid()) {
+ gclog_or_tty->print_cr("CMSCollector: collect because of trigger interval (time since last begin %3.7f secs)",
+ stats().cms_time_since_begin());
+ } else {
+ gclog_or_tty->print_cr("CMSCollector: collect because of trigger interval (first collection)");
+ }
+ }
+ return true;
+ }
+ }
+
return false;
}
@@ -2894,13 +2918,13 @@ bool CMSCollector::is_cms_reachable(HeapWord* addr) {
// Clear the marking bit map array before starting, but, just
// for kicks, first report if the given address is already marked
- gclog_or_tty->print_cr("Start: Address 0x%x is%s marked", addr,
+ gclog_or_tty->print_cr("Start: Address " PTR_FORMAT " is%s marked", addr,
_markBitMap.isMarked(addr) ? "" : " not");
if (verify_after_remark()) {
MutexLockerEx x(verification_mark_bm()->lock(), Mutex::_no_safepoint_check_flag);
bool result = verification_mark_bm()->isMarked(addr);
- gclog_or_tty->print_cr("TransitiveMark: Address 0x%x %s marked", addr,
+ gclog_or_tty->print_cr("TransitiveMark: Address " PTR_FORMAT " %s marked", addr,
result ? "IS" : "is NOT");
return result;
} else {
@@ -4569,7 +4593,7 @@ void CMSCollector::abortable_preclean() {
}
}
if (PrintCMSStatistics > 0) {
- gclog_or_tty->print(" [%d iterations, %d waits, %d cards)] ",
+ gclog_or_tty->print(" [" SIZE_FORMAT " iterations, " SIZE_FORMAT " waits, " SIZE_FORMAT " cards)] ",
loops, waited, cumworkdone);
}
}
@@ -4721,7 +4745,7 @@ size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) {
numIter++, lastNumCards = curNumCards, cumNumCards += curNumCards) {
curNumCards = preclean_mod_union_table(_cmsGen, &smoac_cl);
if (Verbose && PrintGCDetails) {
- gclog_or_tty->print(" (modUnionTable: %d cards)", curNumCards);
+ gclog_or_tty->print(" (modUnionTable: " SIZE_FORMAT " cards)", curNumCards);
}
// Either there are very few dirty cards, so re-mark
// pause will be small anyway, or our pre-cleaning isn't
@@ -4743,7 +4767,7 @@ size_t CMSCollector::preclean_work(bool clean_refs, bool clean_survivor) {
curNumCards = preclean_card_table(_cmsGen, &smoac_cl);
cumNumCards += curNumCards;
if (PrintGCDetails && PrintCMSStatistics != 0) {
- gclog_or_tty->print_cr(" (cardTable: %d cards, re-scanned %d cards, %d iterations)",
+ gclog_or_tty->print_cr(" (cardTable: " SIZE_FORMAT " cards, re-scanned " SIZE_FORMAT " cards, " SIZE_FORMAT " iterations)",
curNumCards, cumNumCards, numIter);
}
return cumNumCards; // as a measure of useful work done
@@ -8205,7 +8229,7 @@ SweepClosure::~SweepClosure() {
void SweepClosure::initialize_free_range(HeapWord* freeFinger,
bool freeRangeInFreeLists) {
if (CMSTraceSweeper) {
- gclog_or_tty->print("---- Start free range at 0x%x with free block (%d)\n",
+ gclog_or_tty->print("---- Start free range at " PTR_FORMAT " with free block (%d)\n",
freeFinger, freeRangeInFreeLists);
}
assert(!inFreeRange(), "Trampling existing free range");
@@ -8275,10 +8299,10 @@ size_t SweepClosure::do_blk_careful(HeapWord* addr) {
pointer_delta(addr, freeFinger()));
if (CMSTraceSweeper) {
gclog_or_tty->print("Sweep: last chunk: ");
- gclog_or_tty->print("put_free_blk 0x%x ("SIZE_FORMAT") "
- "[coalesced:"SIZE_FORMAT"]\n",
+ gclog_or_tty->print("put_free_blk " PTR_FORMAT " ("SIZE_FORMAT") "
+ "[coalesced:%d]\n",
freeFinger(), pointer_delta(addr, freeFinger()),
- lastFreeRangeCoalesced());
+ lastFreeRangeCoalesced() ? 1 : 0);
}
}
@@ -8421,7 +8445,7 @@ void SweepClosure::do_already_free_chunk(FreeChunk* fc) {
// the midst of a free range, we are coalescing
print_free_block_coalesced(fc);
if (CMSTraceSweeper) {
- gclog_or_tty->print(" -- pick up free block 0x%x (%d)\n", fc, size);
+ gclog_or_tty->print(" -- pick up free block " PTR_FORMAT " (" SIZE_FORMAT ")\n", fc, size);
}
// remove it from the free lists
_sp->removeFreeChunkFromFreeLists(fc);
@@ -8483,7 +8507,7 @@ size_t SweepClosure::do_garbage_chunk(FreeChunk* fc) {
// this will be swept up when we hit the end of the
// free range
if (CMSTraceSweeper) {
- gclog_or_tty->print(" -- pick up garbage 0x%x (%d) \n", fc, size);
+ gclog_or_tty->print(" -- pick up garbage " PTR_FORMAT " (" SIZE_FORMAT ")\n", fc, size);
}
// If the chunk is being coalesced and the current free range is
// in the free lists, remove the current free range so that it
@@ -8576,7 +8600,7 @@ void SweepClosure::do_post_free_or_garbage_chunk(FreeChunk* fc,
}
if (CMSTraceSweeper) {
- gclog_or_tty->print_cr(" -- pick up another chunk at 0x%x (%d)", fc, chunkSize);
+ gclog_or_tty->print_cr(" -- pick up another chunk at " PTR_FORMAT " (" SIZE_FORMAT ")", fc, chunkSize);
}
HeapWord* const fc_addr = (HeapWord*) fc;
@@ -8705,7 +8729,7 @@ void SweepClosure::flush_cur_free_chunk(HeapWord* chunk, size_t size) {
"chunk should not be in free lists yet");
}
if (CMSTraceSweeper) {
- gclog_or_tty->print_cr(" -- add free block 0x%x (%d) to free lists",
+ gclog_or_tty->print_cr(" -- add free block " PTR_FORMAT " (" SIZE_FORMAT ") to free lists",
chunk, size);
}
// A new free range is going to be starting. The current
diff --git a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/promotionInfo.cpp b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/promotionInfo.cpp
index 40626ee2f66..cc870308548 100644
--- a/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/promotionInfo.cpp
+++ b/hotspot/src/share/vm/gc_implementation/concurrentMarkSweep/promotionInfo.cpp
@@ -265,7 +265,7 @@ void PromotionInfo::print_statistics(uint worker_id) const {
slots += _spoolHead->bufferSize - 1;
blocks++;
}
- gclog_or_tty->print_cr(" [worker %d] promo_blocks = %d, promo_slots = %d ",
+ gclog_or_tty->print_cr(" [worker %d] promo_blocks = " SIZE_FORMAT ", promo_slots = " SIZE_FORMAT,
worker_id, blocks, slots);
}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp
index 83847cd1bf5..90e0aedd084 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.cpp
@@ -29,7 +29,7 @@
#include "gc_implementation/g1/g1HotCardCache.hpp"
#include "runtime/java.hpp"
-ConcurrentG1Refine::ConcurrentG1Refine(G1CollectedHeap* g1h) :
+ConcurrentG1Refine::ConcurrentG1Refine(G1CollectedHeap* g1h, CardTableEntryClosure* refine_closure) :
_threads(NULL), _n_threads(0),
_hot_card_cache(g1h)
{
@@ -61,7 +61,7 @@ ConcurrentG1Refine::ConcurrentG1Refine(G1CollectedHeap* g1h) :
ConcurrentG1RefineThread *next = NULL;
for (uint i = _n_threads - 1; i != UINT_MAX; i--) {
- ConcurrentG1RefineThread* t = new ConcurrentG1RefineThread(this, next, worker_id_offset, i);
+ ConcurrentG1RefineThread* t = new ConcurrentG1RefineThread(this, next, refine_closure, worker_id_offset, i);
assert(t != NULL, "Conc refine should have been created");
if (t->osthread() == NULL) {
vm_shutdown_during_initialization("Could not create ConcurrentG1RefineThread");
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.hpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.hpp
index 1aea2345aea..f466e0de339 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1Refine.hpp
@@ -71,7 +71,7 @@ class ConcurrentG1Refine: public CHeapObj {
void reset_threshold_step();
public:
- ConcurrentG1Refine(G1CollectedHeap* g1h);
+ ConcurrentG1Refine(G1CollectedHeap* g1h, CardTableEntryClosure* refine_closure);
~ConcurrentG1Refine();
void init(); // Accomplish some initialization that has to wait.
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.cpp
index 4435d370519..886af56e576 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.cpp
@@ -33,8 +33,10 @@
ConcurrentG1RefineThread::
ConcurrentG1RefineThread(ConcurrentG1Refine* cg1r, ConcurrentG1RefineThread *next,
+ CardTableEntryClosure* refine_closure,
uint worker_id_offset, uint worker_id) :
ConcurrentGCThread(),
+ _refine_closure(refine_closure),
_worker_id_offset(worker_id_offset),
_worker_id(worker_id),
_active(false),
@@ -71,6 +73,7 @@ void ConcurrentG1RefineThread::initialize() {
}
void ConcurrentG1RefineThread::sample_young_list_rs_lengths() {
+ SuspendibleThreadSetJoiner sts;
G1CollectedHeap* g1h = G1CollectedHeap::heap();
G1CollectorPolicy* g1p = g1h->g1_policy();
if (g1p->adaptive_young_list_length()) {
@@ -82,8 +85,8 @@ void ConcurrentG1RefineThread::sample_young_list_rs_lengths() {
// we try to yield every time we visit 10 regions
if (regions_visited == 10) {
- if (_sts.should_yield()) {
- _sts.yield("G1 refine");
+ if (sts.should_yield()) {
+ sts.yield();
// we just abandon the iteration
break;
}
@@ -99,9 +102,7 @@ void ConcurrentG1RefineThread::run_young_rs_sampling() {
DirtyCardQueueSet& dcqs = JavaThread::dirty_card_queue_set();
_vtime_start = os::elapsedVTime();
while(!_should_terminate) {
- _sts.join();
sample_young_list_rs_lengths();
- _sts.leave();
if (os::supports_vtime()) {
_vtime_accum = (os::elapsedVTime() - _vtime_start);
@@ -182,37 +183,37 @@ void ConcurrentG1RefineThread::run() {
break;
}
- _sts.join();
+ {
+ SuspendibleThreadSetJoiner sts;
- do {
- int curr_buffer_num = (int)dcqs.completed_buffers_num();
- // If the number of the buffers falls down into the yellow zone,
- // that means that the transition period after the evacuation pause has ended.
- if (dcqs.completed_queue_padding() > 0 && curr_buffer_num <= cg1r()->yellow_zone()) {
- dcqs.set_completed_queue_padding(0);
- }
+ do {
+ int curr_buffer_num = (int)dcqs.completed_buffers_num();
+ // If the number of the buffers falls down into the yellow zone,
+ // that means that the transition period after the evacuation pause has ended.
+ if (dcqs.completed_queue_padding() > 0 && curr_buffer_num <= cg1r()->yellow_zone()) {
+ dcqs.set_completed_queue_padding(0);
+ }
- if (_worker_id > 0 && curr_buffer_num <= _deactivation_threshold) {
- // If the number of the buffer has fallen below our threshold
- // we should deactivate. The predecessor will reactivate this
- // thread should the number of the buffers cross the threshold again.
+ if (_worker_id > 0 && curr_buffer_num <= _deactivation_threshold) {
+ // If the number of the buffer has fallen below our threshold
+ // we should deactivate. The predecessor will reactivate this
+ // thread should the number of the buffers cross the threshold again.
+ deactivate();
+ break;
+ }
+
+ // Check if we need to activate the next thread.
+ if (_next != NULL && !_next->is_active() && curr_buffer_num > _next->_threshold) {
+ _next->activate();
+ }
+ } while (dcqs.apply_closure_to_completed_buffer(_refine_closure, _worker_id + _worker_id_offset, cg1r()->green_zone()));
+
+ // We can exit the loop above while being active if there was a yield request.
+ if (is_active()) {
deactivate();
- break;
}
-
- // Check if we need to activate the next thread.
- if (_next != NULL && !_next->is_active() && curr_buffer_num > _next->_threshold) {
- _next->activate();
- }
- } while (dcqs.apply_closure_to_completed_buffer(_worker_id + _worker_id_offset, cg1r()->green_zone()));
-
- // We can exit the loop above while being active if there was a yield request.
- if (is_active()) {
- deactivate();
}
- _sts.leave();
-
if (os::supports_vtime()) {
_vtime_accum = (os::elapsedVTime() - _vtime_start);
} else {
@@ -223,17 +224,6 @@ void ConcurrentG1RefineThread::run() {
terminate();
}
-
-void ConcurrentG1RefineThread::yield() {
- if (G1TraceConcRefinement) {
- gclog_or_tty->print_cr("G1-Refine-yield");
- }
- _sts.yield("G1 refine");
- if (G1TraceConcRefinement) {
- gclog_or_tty->print_cr("G1-Refine-yield-end");
- }
-}
-
void ConcurrentG1RefineThread::stop() {
// it is ok to take late safepoints here, if needed
{
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.hpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.hpp
index 6eb08642686..05a8dc44ec3 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentG1RefineThread.hpp
@@ -28,6 +28,7 @@
#include "gc_implementation/shared/concurrentGCThread.hpp"
// Forward Decl.
+class CardTableEntryClosure;
class ConcurrentG1Refine;
// The G1 Concurrent Refinement Thread (could be several in the future).
@@ -49,6 +50,9 @@ class ConcurrentG1RefineThread: public ConcurrentGCThread {
Monitor* _monitor;
ConcurrentG1Refine* _cg1r;
+ // The closure applied to completed log buffers.
+ CardTableEntryClosure* _refine_closure;
+
int _thread_threshold_step;
// This thread activation threshold
int _threshold;
@@ -64,13 +68,11 @@ class ConcurrentG1RefineThread: public ConcurrentGCThread {
void activate();
void deactivate();
- // For use by G1CollectedHeap, which is a friend.
- static SuspendibleThreadSet* sts() { return &_sts; }
-
public:
virtual void run();
// Constructor
ConcurrentG1RefineThread(ConcurrentG1Refine* cg1r, ConcurrentG1RefineThread* next,
+ CardTableEntryClosure* refine_closure,
uint worker_id_offset, uint worker_id);
void initialize();
@@ -84,8 +86,6 @@ public:
ConcurrentG1Refine* cg1r() { return _cg1r; }
- // Yield for GC
- void yield();
// shutdown
void stop();
};
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
index bf69f4db0e2..f7494e12fde 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.cpp
@@ -976,11 +976,11 @@ void ConcurrentMark::enter_first_sync_barrier(uint worker_id) {
}
if (concurrent()) {
- ConcurrentGCThread::stsLeave();
+ SuspendibleThreadSet::leave();
}
_first_overflow_barrier_sync.enter();
if (concurrent()) {
- ConcurrentGCThread::stsJoin();
+ SuspendibleThreadSet::join();
}
// at this point everyone should have synced up and not be doing any
// more work
@@ -1024,11 +1024,11 @@ void ConcurrentMark::enter_second_sync_barrier(uint worker_id) {
}
if (concurrent()) {
- ConcurrentGCThread::stsLeave();
+ SuspendibleThreadSet::leave();
}
_second_overflow_barrier_sync.enter();
if (concurrent()) {
- ConcurrentGCThread::stsJoin();
+ SuspendibleThreadSet::join();
}
// at this point everything should be re-initialized and ready to go
@@ -1076,7 +1076,7 @@ public:
double start_vtime = os::elapsedVTime();
- ConcurrentGCThread::stsJoin();
+ SuspendibleThreadSet::join();
assert(worker_id < _cm->active_tasks(), "invariant");
CMTask* the_task = _cm->task(worker_id);
@@ -1103,9 +1103,9 @@ public:
if (!_cm->has_aborted() && the_task->has_aborted()) {
sleep_time_ms =
(jlong) (elapsed_vtime_sec * _cm->sleep_factor() * 1000.0);
- ConcurrentGCThread::stsLeave();
+ SuspendibleThreadSet::leave();
os::sleep(Thread::current(), sleep_time_ms, false);
- ConcurrentGCThread::stsJoin();
+ SuspendibleThreadSet::join();
}
double end_time2_sec = os::elapsedTime();
double elapsed_time2_sec = end_time2_sec - start_time_sec;
@@ -1123,7 +1123,7 @@ public:
the_task->record_end_time();
guarantee(!the_task->has_aborted() || _cm->has_aborted(), "invariant");
- ConcurrentGCThread::stsLeave();
+ SuspendibleThreadSet::leave();
double end_vtime = os::elapsedVTime();
_cm->update_accum_task_vtime(worker_id, end_vtime - start_vtime);
@@ -2655,7 +2655,6 @@ public:
str = " O";
} else {
HeapRegion* hr = _g1h->heap_region_containing(obj);
- guarantee(hr != NULL, "invariant");
bool over_tams = _g1h->allocated_since_marking(obj, hr, _vo);
bool marked = _g1h->is_marked(obj, _vo);
@@ -3302,21 +3301,17 @@ void ConcurrentMark::print_on_error(outputStream* st) const {
// We take a break if someone is trying to stop the world.
bool ConcurrentMark::do_yield_check(uint worker_id) {
- if (should_yield()) {
+ if (SuspendibleThreadSet::should_yield()) {
if (worker_id == 0) {
_g1h->g1_policy()->record_concurrent_pause();
}
- cmThread()->yield();
+ SuspendibleThreadSet::yield();
return true;
} else {
return false;
}
}
-bool ConcurrentMark::should_yield() {
- return cmThread()->should_yield();
-}
-
bool ConcurrentMark::containing_card_is_marked(void* p) {
size_t offset = pointer_delta(p, _g1h->reserved_region().start(), 1);
return _card_bm.at(offset >> CardTableModRefBS::card_shift);
@@ -3417,9 +3412,8 @@ G1CMOopClosure::G1CMOopClosure(G1CollectedHeap* g1h,
}
void CMTask::setup_for_region(HeapRegion* hr) {
- // Separated the asserts so that we know which one fires.
assert(hr != NULL,
- "claim_region() should have filtered out continues humongous regions");
+ "claim_region() should have filtered out NULL regions");
assert(!hr->continuesHumongous(),
"claim_region() should have filtered out continues humongous regions");
@@ -3605,7 +3599,7 @@ void CMTask::regular_clock_call() {
#endif // _MARKING_STATS_
// (4) We check whether we should yield. If we have to, then we abort.
- if (_cm->should_yield()) {
+ if (SuspendibleThreadSet::should_yield()) {
// We should yield. To do this we abort the task. The caller is
// responsible for yielding.
set_has_aborted();
@@ -3754,7 +3748,7 @@ void CMTask::drain_local_queue(bool partially) {
if (_task_queue->size() > target_size) {
if (_cm->verbose_high()) {
- gclog_or_tty->print_cr("[%u] draining local queue, target size = %d",
+ gclog_or_tty->print_cr("[%u] draining local queue, target size = " SIZE_FORMAT,
_worker_id, target_size);
}
@@ -3782,7 +3776,7 @@ void CMTask::drain_local_queue(bool partially) {
}
if (_cm->verbose_high()) {
- gclog_or_tty->print_cr("[%u] drained local queue, size = %d",
+ gclog_or_tty->print_cr("[%u] drained local queue, size = %u",
_worker_id, _task_queue->size());
}
}
@@ -3810,7 +3804,7 @@ void CMTask::drain_global_stack(bool partially) {
if (_cm->mark_stack_size() > target_size) {
if (_cm->verbose_low()) {
- gclog_or_tty->print_cr("[%u] draining global_stack, target size %d",
+ gclog_or_tty->print_cr("[%u] draining global_stack, target size " SIZE_FORMAT,
_worker_id, target_size);
}
@@ -3820,7 +3814,7 @@ void CMTask::drain_global_stack(bool partially) {
}
if (_cm->verbose_low()) {
- gclog_or_tty->print_cr("[%u] drained global stack, size = %d",
+ gclog_or_tty->print_cr("[%u] drained global stack, size = " SIZE_FORMAT,
_worker_id, _cm->mark_stack_size());
}
}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp
index 355bddfa2e0..21327485863 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMark.hpp
@@ -814,7 +814,6 @@ public:
}
inline bool do_yield_check(uint worker_i = 0);
- inline bool should_yield();
// Called to abort the marking cycle after a Full GC takes place.
void abort();
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp
index ee53c3ba6e3..5dce0653242 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp
@@ -89,6 +89,10 @@ void ConcurrentMarkThread::run() {
while (!_should_terminate) {
// wait until started is set.
sleepBeforeNextCycle();
+ if (_should_terminate) {
+ break;
+ }
+
{
ResourceMark rm;
HandleMark hm;
@@ -190,9 +194,8 @@ void ConcurrentMarkThread::run() {
} else {
// We don't want to update the marking status if a GC pause
// is already underway.
- _sts.join();
+ SuspendibleThreadSetJoiner sts;
g1h->set_marking_complete();
- _sts.leave();
}
// Check if cleanup set the free_regions_coming flag. If it
@@ -262,11 +265,12 @@ void ConcurrentMarkThread::run() {
// record_concurrent_mark_cleanup_completed() (and, in fact, it's
// not needed any more as the concurrent mark state has been
// already reset).
- _sts.join();
- if (!cm()->has_aborted()) {
- g1_policy->record_concurrent_mark_cleanup_completed();
+ {
+ SuspendibleThreadSetJoiner sts;
+ if (!cm()->has_aborted()) {
+ g1_policy->record_concurrent_mark_cleanup_completed();
+ }
}
- _sts.leave();
if (cm()->has_aborted()) {
if (G1Log::fine()) {
@@ -278,36 +282,43 @@ void ConcurrentMarkThread::run() {
// We now want to allow clearing of the marking bitmap to be
// suspended by a collection pause.
- _sts.join();
- _cm->clearNextBitmap();
- _sts.leave();
+ {
+ SuspendibleThreadSetJoiner sts;
+ _cm->clearNextBitmap();
+ }
}
// Update the number of full collections that have been
// completed. This will also notify the FullGCCount_lock in case a
// Java thread is waiting for a full GC to happen (e.g., it
// called System.gc() with +ExplicitGCInvokesConcurrent).
- _sts.join();
- g1h->increment_old_marking_cycles_completed(true /* concurrent */);
- g1h->register_concurrent_cycle_end();
- _sts.leave();
+ {
+ SuspendibleThreadSetJoiner sts;
+ g1h->increment_old_marking_cycles_completed(true /* concurrent */);
+ g1h->register_concurrent_cycle_end();
+ }
}
assert(_should_terminate, "just checking");
terminate();
}
-
-void ConcurrentMarkThread::yield() {
- _sts.yield("Concurrent Mark");
-}
-
void ConcurrentMarkThread::stop() {
- // it is ok to take late safepoints here, if needed
- MutexLockerEx mu(Terminator_lock);
- _should_terminate = true;
- while (!_has_terminated) {
- Terminator_lock->wait();
+ {
+ MutexLockerEx ml(Terminator_lock);
+ _should_terminate = true;
+ }
+
+ {
+ MutexLockerEx ml(CGC_lock, Mutex::_no_safepoint_check_flag);
+ CGC_lock->notify_all();
+ }
+
+ {
+ MutexLockerEx ml(Terminator_lock);
+ while (!_has_terminated) {
+ Terminator_lock->wait();
+ }
}
}
@@ -327,11 +338,14 @@ void ConcurrentMarkThread::sleepBeforeNextCycle() {
assert(!in_progress(), "should have been cleared");
MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
- while (!started()) {
+ while (!started() && !_should_terminate) {
CGC_lock->wait(Mutex::_no_safepoint_check_flag);
}
- set_in_progress();
- clear_started();
+
+ if (started()) {
+ set_in_progress();
+ clear_started();
+ }
}
// Note: As is the case with CMS - this method, although exported
diff --git a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.hpp b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.hpp
index 5f3d9ee451a..caa7f429c6e 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/concurrentMarkThread.hpp
@@ -89,9 +89,6 @@ class ConcurrentMarkThread: public ConcurrentGCThread {
// that started() is set and set in_progress().
bool during_cycle() { return started() || in_progress(); }
- // Yield for GC
- void yield();
-
// shutdown
void stop();
};
diff --git a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp
index 1168343c097..6e84e514aa7 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.cpp
@@ -70,7 +70,7 @@ bool DirtyCardQueue::apply_closure_to_buffer(CardTableEntryClosure* cl,
DirtyCardQueueSet::DirtyCardQueueSet(bool notify_when_complete) :
PtrQueueSet(notify_when_complete),
- _closure(NULL),
+ _mut_process_closure(NULL),
_shared_dirty_card_queue(this, true /*perm*/),
_free_ids(NULL),
_processed_buffers_mut(0), _processed_buffers_rs_thread(0)
@@ -83,10 +83,11 @@ uint DirtyCardQueueSet::num_par_ids() {
return (uint)os::processor_count();
}
-void DirtyCardQueueSet::initialize(Monitor* cbl_mon, Mutex* fl_lock,
+void DirtyCardQueueSet::initialize(CardTableEntryClosure* cl, Monitor* cbl_mon, Mutex* fl_lock,
int process_completed_threshold,
int max_completed_queue,
Mutex* lock, PtrQueueSet* fl_owner) {
+ _mut_process_closure = cl;
PtrQueueSet::initialize(cbl_mon, fl_lock, process_completed_threshold,
max_completed_queue, fl_owner);
set_buffer_size(G1UpdateBufferSize);
@@ -98,18 +99,15 @@ void DirtyCardQueueSet::handle_zero_index_for_thread(JavaThread* t) {
t->dirty_card_queue().handle_zero_index();
}
-void DirtyCardQueueSet::set_closure(CardTableEntryClosure* closure) {
- _closure = closure;
-}
-
-void DirtyCardQueueSet::iterate_closure_all_threads(bool consume,
+void DirtyCardQueueSet::iterate_closure_all_threads(CardTableEntryClosure* cl,
+ bool consume,
uint worker_i) {
assert(SafepointSynchronize::is_at_safepoint(), "Must be at safepoint.");
for(JavaThread* t = Threads::first(); t; t = t->next()) {
- bool b = t->dirty_card_queue().apply_closure(_closure, consume);
+ bool b = t->dirty_card_queue().apply_closure(cl, consume);
guarantee(b, "Should not be interrupted.");
}
- bool b = shared_dirty_card_queue()->apply_closure(_closure,
+ bool b = shared_dirty_card_queue()->apply_closure(cl,
consume,
worker_i);
guarantee(b, "Should not be interrupted.");
@@ -143,7 +141,7 @@ bool DirtyCardQueueSet::mut_process_buffer(void** buf) {
bool b = false;
if (worker_i != UINT_MAX) {
- b = DirtyCardQueue::apply_closure_to_buffer(_closure, buf, 0,
+ b = DirtyCardQueue::apply_closure_to_buffer(_mut_process_closure, buf, 0,
_sz, true, worker_i);
if (b) Atomic::inc(&_processed_buffers_mut);
@@ -218,18 +216,11 @@ bool DirtyCardQueueSet::apply_closure_to_completed_buffer(CardTableEntryClosure*
return res;
}
-bool DirtyCardQueueSet::apply_closure_to_completed_buffer(uint worker_i,
- int stop_at,
- bool during_pause) {
- return apply_closure_to_completed_buffer(_closure, worker_i,
- stop_at, during_pause);
-}
-
-void DirtyCardQueueSet::apply_closure_to_all_completed_buffers() {
+void DirtyCardQueueSet::apply_closure_to_all_completed_buffers(CardTableEntryClosure* cl) {
BufferNode* nd = _completed_buffers_head;
while (nd != NULL) {
bool b =
- DirtyCardQueue::apply_closure_to_buffer(_closure,
+ DirtyCardQueue::apply_closure_to_buffer(cl,
BufferNode::make_buffer_from_node(nd),
0, _sz, false);
guarantee(b, "Should not stop early.");
@@ -237,6 +228,24 @@ void DirtyCardQueueSet::apply_closure_to_all_completed_buffers() {
}
}
+void DirtyCardQueueSet::par_apply_closure_to_all_completed_buffers(CardTableEntryClosure* cl) {
+ BufferNode* nd = _cur_par_buffer_node;
+ while (nd != NULL) {
+ BufferNode* next = (BufferNode*)nd->next();
+ BufferNode* actual = (BufferNode*)Atomic::cmpxchg_ptr((void*)next, (volatile void*)&_cur_par_buffer_node, (void*)nd);
+ if (actual == nd) {
+ bool b =
+ DirtyCardQueue::apply_closure_to_buffer(cl,
+ BufferNode::make_buffer_from_node(actual),
+ 0, _sz, false);
+ guarantee(b, "Should not stop early.");
+ nd = next;
+ } else {
+ nd = actual;
+ }
+ }
+}
+
// Deallocates any completed log buffers
void DirtyCardQueueSet::clear() {
BufferNode* buffers_to_delete = NULL;
diff --git a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp
index 0412c8953a0..ac066a08143 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/dirtyCardQueue.hpp
@@ -73,7 +73,8 @@ public:
class DirtyCardQueueSet: public PtrQueueSet {
- CardTableEntryClosure* _closure;
+ // The closure used in mut_process_buffer().
+ CardTableEntryClosure* _mut_process_closure;
DirtyCardQueue _shared_dirty_card_queue;
@@ -88,10 +89,12 @@ class DirtyCardQueueSet: public PtrQueueSet {
jint _processed_buffers_mut;
jint _processed_buffers_rs_thread;
+ // Current buffer node used for parallel iteration.
+ BufferNode* volatile _cur_par_buffer_node;
public:
DirtyCardQueueSet(bool notify_when_complete = true);
- void initialize(Monitor* cbl_mon, Mutex* fl_lock,
+ void initialize(CardTableEntryClosure* cl, Monitor* cbl_mon, Mutex* fl_lock,
int process_completed_threshold,
int max_completed_queue,
Mutex* lock, PtrQueueSet* fl_owner = NULL);
@@ -102,32 +105,14 @@ public:
static void handle_zero_index_for_thread(JavaThread* t);
- // Register "blk" as "the closure" for all queues. Only one such closure
- // is allowed. The "apply_closure_to_completed_buffer" method will apply
- // this closure to a completed buffer, and "iterate_closure_all_threads"
- // applies it to partially-filled buffers (the latter should only be done
- // with the world stopped).
- void set_closure(CardTableEntryClosure* closure);
-
- // If there is a registered closure for buffers, apply it to all entries
- // in all currently-active buffers. This should only be applied at a
- // safepoint. (Currently must not be called in parallel; this should
- // change in the future.) If "consume" is true, processed entries are
- // discarded.
- void iterate_closure_all_threads(bool consume = true,
+ // Apply the given closure to all entries in all currently-active buffers.
+ // This should only be applied at a safepoint. (Currently must not be called
+ // in parallel; this should change in the future.) If "consume" is true,
+ // processed entries are discarded.
+ void iterate_closure_all_threads(CardTableEntryClosure* cl,
+ bool consume = true,
uint worker_i = 0);
- // If there exists some completed buffer, pop it, then apply the
- // registered closure to all its elements, nulling out those elements
- // processed. If all elements are processed, returns "true". If no
- // completed buffers exist, returns false. If a completed buffer exists,
- // but is only partially completed before a "yield" happens, the
- // partially completed buffer (with its processed elements set to NULL)
- // is returned to the completed buffer set, and this call returns false.
- bool apply_closure_to_completed_buffer(uint worker_i = 0,
- int stop_at = 0,
- bool during_pause = false);
-
// If there exists some completed buffer, pop it, then apply the
// specified closure to all its elements, nulling out those elements
// processed. If all elements are processed, returns "true". If no
@@ -149,7 +134,12 @@ public:
// Applies the current closure to all completed buffers,
// non-consumptively.
- void apply_closure_to_all_completed_buffers();
+ void apply_closure_to_all_completed_buffers(CardTableEntryClosure* cl);
+
+ void reset_for_par_iteration() { _cur_par_buffer_node = _completed_buffers_head; }
+ // Applies the current closure to all completed buffers, non-consumptively.
+ // Parallel version.
+ void par_apply_closure_to_all_completed_buffers(CardTableEntryClosure* cl);
DirtyCardQueue* shared_dirty_card_queue() {
return &_shared_dirty_card_queue;
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp
index 7b23022777f..1130278fa91 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.cpp
@@ -45,32 +45,27 @@ void G1CodeRootChunk::nmethods_do(CodeBlobClosure* cl) {
}
}
-FreeList G1CodeRootSet::_free_list;
-size_t G1CodeRootSet::_num_chunks_handed_out = 0;
-
-G1CodeRootChunk* G1CodeRootSet::new_chunk() {
- G1CodeRootChunk* result = _free_list.get_chunk_at_head();
- if (result == NULL) {
- result = new G1CodeRootChunk();
- }
- G1CodeRootSet::_num_chunks_handed_out++;
- result->reset();
- return result;
+G1CodeRootChunkManager::G1CodeRootChunkManager() : _free_list(), _num_chunks_handed_out(0) {
+ _free_list.initialize();
+ _free_list.set_size(G1CodeRootChunk::word_size());
}
-void G1CodeRootSet::free_chunk(G1CodeRootChunk* chunk) {
- _free_list.return_chunk_at_head(chunk);
- G1CodeRootSet::_num_chunks_handed_out--;
+size_t G1CodeRootChunkManager::fl_mem_size() {
+ return _free_list.count() * _free_list.size();
}
-void G1CodeRootSet::free_all_chunks(FreeList* list) {
- G1CodeRootSet::_num_chunks_handed_out -= list->count();
+void G1CodeRootChunkManager::free_all_chunks(FreeList* list) {
+ _num_chunks_handed_out -= list->count();
_free_list.prepend(list);
}
-void G1CodeRootSet::purge_chunks(size_t keep_ratio) {
- size_t keep = G1CodeRootSet::_num_chunks_handed_out * keep_ratio / 100;
+void G1CodeRootChunkManager::free_chunk(G1CodeRootChunk* chunk) {
+ _free_list.return_chunk_at_head(chunk);
+ _num_chunks_handed_out--;
+}
+void G1CodeRootChunkManager::purge_chunks(size_t keep_ratio) {
+ size_t keep = _num_chunks_handed_out * keep_ratio / 100;
if (keep >= (size_t)_free_list.count()) {
return;
}
@@ -88,20 +83,51 @@ void G1CodeRootSet::purge_chunks(size_t keep_ratio) {
}
}
-size_t G1CodeRootSet::static_mem_size() {
- return sizeof(_free_list) + sizeof(_num_chunks_handed_out);
+size_t G1CodeRootChunkManager::static_mem_size() {
+ return sizeof(G1CodeRootChunkManager);
}
-size_t G1CodeRootSet::fl_mem_size() {
- return _free_list.count() * _free_list.size();
+
+G1CodeRootChunk* G1CodeRootChunkManager::new_chunk() {
+ G1CodeRootChunk* result = _free_list.get_chunk_at_head();
+ if (result == NULL) {
+ result = new G1CodeRootChunk();
+ }
+ _num_chunks_handed_out++;
+ result->reset();
+ return result;
}
-void G1CodeRootSet::initialize() {
- _free_list.initialize();
- _free_list.set_size(G1CodeRootChunk::word_size());
+#ifndef PRODUCT
+
+size_t G1CodeRootChunkManager::num_chunks_handed_out() const {
+ return _num_chunks_handed_out;
}
-G1CodeRootSet::G1CodeRootSet() : _list(), _length(0) {
+size_t G1CodeRootChunkManager::num_free_chunks() const {
+ return (size_t)_free_list.count();
+}
+
+#endif
+
+G1CodeRootChunkManager G1CodeRootSet::_default_chunk_manager;
+
+void G1CodeRootSet::purge_chunks(size_t keep_ratio) {
+ _default_chunk_manager.purge_chunks(keep_ratio);
+}
+
+size_t G1CodeRootSet::free_chunks_static_mem_size() {
+ return _default_chunk_manager.static_mem_size();
+}
+
+size_t G1CodeRootSet::free_chunks_mem_size() {
+ return _default_chunk_manager.fl_mem_size();
+}
+
+G1CodeRootSet::G1CodeRootSet(G1CodeRootChunkManager* manager) : _manager(manager), _list(), _length(0) {
+ if (_manager == NULL) {
+ _manager = &_default_chunk_manager;
+ }
_list.initialize();
_list.set_size(G1CodeRootChunk::word_size());
}
@@ -187,28 +213,38 @@ void G1CodeRootSet::nmethods_do(CodeBlobClosure* blk) const {
}
}
+size_t G1CodeRootSet::static_mem_size() {
+ return sizeof(G1CodeRootSet);
+}
+
size_t G1CodeRootSet::mem_size() {
- return sizeof(this) + _list.count() * _list.size();
+ return G1CodeRootSet::static_mem_size() + _list.count() * _list.size();
}
#ifndef PRODUCT
void G1CodeRootSet::test() {
- initialize();
+ G1CodeRootChunkManager mgr;
- assert(_free_list.count() == 0, "Free List must be empty");
- assert(_num_chunks_handed_out == 0, "No elements must have been handed out yet");
+ assert(mgr.num_chunks_handed_out() == 0, "Must not have handed out chunks yet");
+
+ assert(G1CodeRootChunkManager::static_mem_size() > sizeof(void*),
+ err_msg("The chunk manager's static memory usage seems too small, is only "SIZE_FORMAT" bytes.", G1CodeRootChunkManager::static_mem_size()));
// The number of chunks that we allocate for purge testing.
size_t const num_chunks = 10;
+
{
- G1CodeRootSet set1;
+ G1CodeRootSet set1(&mgr);
assert(set1.is_empty(), "Code root set must be initially empty but is not.");
+ assert(G1CodeRootSet::static_mem_size() > sizeof(void*),
+ err_msg("The code root set's static memory usage seems too small, is only "SIZE_FORMAT" bytes", G1CodeRootSet::static_mem_size()));
+
set1.add((nmethod*)1);
- assert(_num_chunks_handed_out == 1,
+ assert(mgr.num_chunks_handed_out() == 1,
err_msg("Must have allocated and handed out one chunk, but handed out "
- SIZE_FORMAT" chunks", _num_chunks_handed_out));
+ SIZE_FORMAT" chunks", mgr.num_chunks_handed_out()));
assert(set1.length() == 1, err_msg("Added exactly one element, but set contains "
SIZE_FORMAT" elements", set1.length()));
@@ -217,19 +253,19 @@ void G1CodeRootSet::test() {
for (uint i = 0; i < G1CodeRootChunk::word_size() + 1; i++) {
set1.add((nmethod*)1);
}
- assert(_num_chunks_handed_out == 1,
+ assert(mgr.num_chunks_handed_out() == 1,
err_msg("Duplicate detection must have prevented allocation of further "
- "chunks but contains "SIZE_FORMAT, _num_chunks_handed_out));
+ "chunks but allocated "SIZE_FORMAT, mgr.num_chunks_handed_out()));
assert(set1.length() == 1,
err_msg("Duplicate detection should not have increased the set size but "
"is "SIZE_FORMAT, set1.length()));
size_t num_total_after_add = G1CodeRootChunk::word_size() + 1;
for (size_t i = 0; i < num_total_after_add - 1; i++) {
- set1.add((nmethod*)(2 + i));
+ set1.add((nmethod*)(uintptr_t)(2 + i));
}
- assert(_num_chunks_handed_out > 1,
- "After adding more code roots, more than one chunks should have been handed out");
+ assert(mgr.num_chunks_handed_out() > 1,
+ "After adding more code roots, more than one additional chunk should have been handed out");
assert(set1.length() == num_total_after_add,
err_msg("After adding in total "SIZE_FORMAT" distinct code roots, they "
"need to be in the set, but there are only "SIZE_FORMAT,
@@ -242,27 +278,27 @@ void G1CodeRootSet::test() {
assert(num_popped == num_total_after_add,
err_msg("Managed to pop "SIZE_FORMAT" code roots, but only "SIZE_FORMAT" "
"were added", num_popped, num_total_after_add));
- assert(_num_chunks_handed_out == 0,
+ assert(mgr.num_chunks_handed_out() == 0,
err_msg("After popping all elements, all chunks must have been returned "
- "but are still "SIZE_FORMAT, _num_chunks_handed_out));
+ "but there are still "SIZE_FORMAT" additional", mgr.num_chunks_handed_out()));
- purge_chunks(0);
- assert(_free_list.count() == 0,
+ mgr.purge_chunks(0);
+ assert(mgr.num_free_chunks() == 0,
err_msg("After purging everything, the free list must be empty but still "
- "contains "SIZE_FORMAT" chunks", _free_list.count()));
+ "contains "SIZE_FORMAT" chunks", mgr.num_free_chunks()));
// Add some more handed out chunks.
size_t i = 0;
- while (_num_chunks_handed_out < num_chunks) {
+ while (mgr.num_chunks_handed_out() < num_chunks) {
set1.add((nmethod*)i);
i++;
}
{
// Generate chunks on the free list.
- G1CodeRootSet set2;
+ G1CodeRootSet set2(&mgr);
size_t i = 0;
- while (_num_chunks_handed_out < num_chunks * 2) {
+ while (mgr.num_chunks_handed_out() < (num_chunks * 2)) {
set2.add((nmethod*)i);
i++;
}
@@ -270,45 +306,45 @@ void G1CodeRootSet::test() {
// num_chunks elements on the free list.
}
- assert(_num_chunks_handed_out == num_chunks,
+ assert(mgr.num_chunks_handed_out() == num_chunks,
err_msg("Deletion of the second set must have resulted in giving back "
- "those, but there is still "SIZE_FORMAT" handed out, expecting "
- SIZE_FORMAT, _num_chunks_handed_out, num_chunks));
- assert((size_t)_free_list.count() == num_chunks,
+ "those, but there are still "SIZE_FORMAT" additional handed out, expecting "
+ SIZE_FORMAT, mgr.num_chunks_handed_out(), num_chunks));
+ assert(mgr.num_free_chunks() == num_chunks,
err_msg("After freeing "SIZE_FORMAT" chunks, they must be on the free list "
- "but there are only "SIZE_FORMAT, num_chunks, _free_list.count()));
+ "but there are only "SIZE_FORMAT, num_chunks, mgr.num_free_chunks()));
size_t const test_percentage = 50;
- purge_chunks(test_percentage);
- assert(_num_chunks_handed_out == num_chunks,
+ mgr.purge_chunks(test_percentage);
+ assert(mgr.num_chunks_handed_out() == num_chunks,
err_msg("Purging must not hand out chunks but there are "SIZE_FORMAT,
- _num_chunks_handed_out));
- assert((size_t)_free_list.count() == (ssize_t)(num_chunks * test_percentage / 100),
+ mgr.num_chunks_handed_out()));
+ assert(mgr.num_free_chunks() == (size_t)(mgr.num_chunks_handed_out() * test_percentage / 100),
err_msg("Must have purged "SIZE_FORMAT" percent of "SIZE_FORMAT" chunks"
- "but there are "SSIZE_FORMAT, test_percentage, num_chunks,
- _free_list.count()));
+ "but there are "SIZE_FORMAT, test_percentage, num_chunks,
+ mgr.num_free_chunks()));
// Purge the remainder of the chunks on the free list.
- purge_chunks(0);
- assert(_free_list.count() == 0, "Free List must be empty");
- assert(_num_chunks_handed_out == num_chunks,
+ mgr.purge_chunks(0);
+ assert(mgr.num_free_chunks() == 0, "Free List must be empty");
+ assert(mgr.num_chunks_handed_out() == num_chunks,
err_msg("Expected to be "SIZE_FORMAT" chunks handed out from the first set "
- "but there are "SIZE_FORMAT, num_chunks, _num_chunks_handed_out));
+ "but there are "SIZE_FORMAT, num_chunks, mgr.num_chunks_handed_out()));
// Exit of the scope of the set1 object will call the destructor that generates
// num_chunks additional elements on the free list.
- }
+ }
- assert(_num_chunks_handed_out == 0,
+ assert(mgr.num_chunks_handed_out() == 0,
err_msg("Deletion of the only set must have resulted in no chunks handed "
- "out, but there is still "SIZE_FORMAT" handed out", _num_chunks_handed_out));
- assert((size_t)_free_list.count() == num_chunks,
+ "out, but there is still "SIZE_FORMAT" handed out", mgr.num_chunks_handed_out()));
+ assert(mgr.num_free_chunks() == num_chunks,
err_msg("After freeing "SIZE_FORMAT" chunks, they must be on the free list "
- "but there are only "SSIZE_FORMAT, num_chunks, _free_list.count()));
+ "but there are only "SIZE_FORMAT, num_chunks, mgr.num_free_chunks()));
// Restore initial state.
- purge_chunks(0);
- assert(_free_list.count() == 0, "Free List must be empty");
- assert(_num_chunks_handed_out == 0, "No elements must have been handed out yet");
+ mgr.purge_chunks(0);
+ assert(mgr.num_free_chunks() == 0, "Free List must be empty");
+ assert(mgr.num_chunks_handed_out() == 0, "No additional elements must have been handed out yet");
}
void TestCodeCacheRemSet_test() {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.hpp
index ad8025c4b03..84008213dbc 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CodeCacheRemSet.hpp
@@ -128,19 +128,45 @@ class G1CodeRootChunk : public CHeapObj {
}
};
+// Manages free chunks.
+class G1CodeRootChunkManager VALUE_OBJ_CLASS_SPEC {
+ private:
+ // Global free chunk list management
+ FreeList _free_list;
+ // Total number of chunks handed out
+ size_t _num_chunks_handed_out;
+
+ public:
+ G1CodeRootChunkManager();
+
+ G1CodeRootChunk* new_chunk();
+ void free_chunk(G1CodeRootChunk* chunk);
+ // Free all elements of the given list.
+ void free_all_chunks(FreeList* list);
+
+ void initialize();
+ void purge_chunks(size_t keep_ratio);
+
+ static size_t static_mem_size();
+ size_t fl_mem_size();
+
+#ifndef PRODUCT
+ size_t num_chunks_handed_out() const;
+ size_t num_free_chunks() const;
+#endif
+};
+
// Implements storage for a set of code roots.
// All methods that modify the set are not thread-safe except if otherwise noted.
class G1CodeRootSet VALUE_OBJ_CLASS_SPEC {
private:
- // Global free chunk list management
- static FreeList _free_list;
- // Total number of chunks handed out
- static size_t _num_chunks_handed_out;
+ // Global default free chunk manager instance.
+ static G1CodeRootChunkManager _default_chunk_manager;
- static G1CodeRootChunk* new_chunk();
- static void free_chunk(G1CodeRootChunk* chunk);
+ G1CodeRootChunk* new_chunk() { return _manager->new_chunk(); }
+ void free_chunk(G1CodeRootChunk* chunk) { _manager->free_chunk(chunk); }
// Free all elements of the given list.
- static void free_all_chunks(FreeList* list);
+ void free_all_chunks(FreeList* list) { _manager->free_all_chunks(list); }
// Return the chunk that contains the given nmethod, NULL otherwise.
// Scans the list of chunks backwards, as this method is used to add new
@@ -150,16 +176,18 @@ class G1CodeRootSet VALUE_OBJ_CLASS_SPEC {
size_t _length;
FreeList _list;
+ G1CodeRootChunkManager* _manager;
public:
- G1CodeRootSet();
+ // If an instance is initialized with a chunk manager of NULL, use the global
+ // default one.
+ G1CodeRootSet(G1CodeRootChunkManager* manager = NULL);
~G1CodeRootSet();
- static void initialize();
static void purge_chunks(size_t keep_ratio);
- static size_t static_mem_size();
- static size_t fl_mem_size();
+ static size_t free_chunks_static_mem_size();
+ static size_t free_chunks_mem_size();
// Search for the code blob from the recently allocated ones to find duplicates more quickly, as this
// method is likely to be repeatedly called with the same nmethod.
@@ -179,6 +207,8 @@ class G1CodeRootSet VALUE_OBJ_CLASS_SPEC {
// Length in elements
size_t length() const { return _length; }
+ // Static data memory size in bytes of this set.
+ static size_t static_mem_size();
// Memory size in bytes taken by this set.
size_t mem_size();
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
index c501cbc987b..7d57183a20a 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp
@@ -57,6 +57,7 @@
#include "oops/oop.inline.hpp"
#include "oops/oop.pcgc.inline.hpp"
#include "runtime/vmThread.hpp"
+#include "utilities/globalDefinitions.hpp"
#include "utilities/ticks.hpp"
size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
@@ -92,56 +93,54 @@ size_t G1CollectedHeap::_humongous_object_threshold_in_words = 0;
// Local to this file.
class RefineCardTableEntryClosure: public CardTableEntryClosure {
- SuspendibleThreadSet* _sts;
- G1RemSet* _g1rs;
- ConcurrentG1Refine* _cg1r;
bool _concurrent;
public:
- RefineCardTableEntryClosure(SuspendibleThreadSet* sts,
- G1RemSet* g1rs,
- ConcurrentG1Refine* cg1r) :
- _sts(sts), _g1rs(g1rs), _cg1r(cg1r), _concurrent(true)
- {}
+ RefineCardTableEntryClosure() : _concurrent(true) { }
+
bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
- bool oops_into_cset = _g1rs->refine_card(card_ptr, worker_i, false);
+ bool oops_into_cset = G1CollectedHeap::heap()->g1_rem_set()->refine_card(card_ptr, worker_i, false);
// This path is executed by the concurrent refine or mutator threads,
// concurrently, and so we do not care if card_ptr contains references
// that point into the collection set.
assert(!oops_into_cset, "should be");
- if (_concurrent && _sts->should_yield()) {
+ if (_concurrent && SuspendibleThreadSet::should_yield()) {
// Caller will actually yield.
return false;
}
// Otherwise, we finished successfully; return true.
return true;
}
+
void set_concurrent(bool b) { _concurrent = b; }
};
class ClearLoggedCardTableEntryClosure: public CardTableEntryClosure {
- int _calls;
- G1CollectedHeap* _g1h;
+ size_t _num_processed;
CardTableModRefBS* _ctbs;
int _histo[256];
-public:
+
+ public:
ClearLoggedCardTableEntryClosure() :
- _calls(0), _g1h(G1CollectedHeap::heap()), _ctbs(_g1h->g1_barrier_set())
+ _num_processed(0), _ctbs(G1CollectedHeap::heap()->g1_barrier_set())
{
for (int i = 0; i < 256; i++) _histo[i] = 0;
}
+
bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
- if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
- _calls++;
- unsigned char* ujb = (unsigned char*)card_ptr;
- int ind = (int)(*ujb);
- _histo[ind]++;
- *card_ptr = -1;
- }
+ unsigned char* ujb = (unsigned char*)card_ptr;
+ int ind = (int)(*ujb);
+ _histo[ind]++;
+
+ *card_ptr = (jbyte)CardTableModRefBS::clean_card_val();
+ _num_processed++;
+
return true;
}
- int calls() { return _calls; }
+
+ size_t num_processed() { return _num_processed; }
+
void print_histo() {
gclog_or_tty->print_cr("Card table value histogram:");
for (int i = 0; i < 256; i++) {
@@ -152,22 +151,20 @@ public:
}
};
-class RedirtyLoggedCardTableEntryClosure: public CardTableEntryClosure {
- int _calls;
- G1CollectedHeap* _g1h;
- CardTableModRefBS* _ctbs;
-public:
- RedirtyLoggedCardTableEntryClosure() :
- _calls(0), _g1h(G1CollectedHeap::heap()), _ctbs(_g1h->g1_barrier_set()) {}
+class RedirtyLoggedCardTableEntryClosure : public CardTableEntryClosure {
+ private:
+ size_t _num_processed;
+
+ public:
+ RedirtyLoggedCardTableEntryClosure() : CardTableEntryClosure(), _num_processed(0) { }
bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
- if (_g1h->is_in_reserved(_ctbs->addr_for(card_ptr))) {
- _calls++;
- *card_ptr = 0;
- }
+ *card_ptr = CardTableModRefBS::dirty_card_val();
+ _num_processed++;
return true;
}
- int calls() { return _calls; }
+
+ size_t num_processed() const { return _num_processed; }
};
YoungList::YoungList(G1CollectedHeap* g1h) :
@@ -431,6 +428,9 @@ HeapRegion* G1CollectedHeap::pop_dirty_cards_region()
void G1CollectedHeap::stop_conc_gc_threads() {
_cg1r->stop();
_cmThread->stop();
+ if (G1StringDedup::is_enabled()) {
+ G1StringDedup::stop();
+ }
}
#ifdef ASSERT
@@ -445,24 +445,18 @@ void G1CollectedHeap::stop_conc_gc_threads() {
// implementation of is_scavengable() for G1 will indicate that
// all nmethods must be scanned during a partial collection.
bool G1CollectedHeap::is_in_partial_collection(const void* p) {
- HeapRegion* hr = heap_region_containing(p);
- return hr != NULL && hr->in_collection_set();
+ if (p == NULL) {
+ return false;
+ }
+ return heap_region_containing(p)->in_collection_set();
}
#endif
// Returns true if the reference points to an object that
// can move in an incremental collection.
bool G1CollectedHeap::is_scavengable(const void* p) {
- G1CollectedHeap* g1h = G1CollectedHeap::heap();
- G1CollectorPolicy* g1p = g1h->g1_policy();
HeapRegion* hr = heap_region_containing(p);
- if (hr == NULL) {
- // null
- assert(p == NULL, err_msg("Not NULL " PTR_FORMAT ,p));
- return false;
- } else {
- return !hr->isHumongous();
- }
+ return !hr->isHumongous();
}
void G1CollectedHeap::check_ct_logs_at_safepoint() {
@@ -476,9 +470,8 @@ void G1CollectedHeap::check_ct_logs_at_safepoint() {
// First clear the logged cards.
ClearLoggedCardTableEntryClosure clear;
- dcqs.set_closure(&clear);
- dcqs.apply_closure_to_all_completed_buffers();
- dcqs.iterate_closure_all_threads(false);
+ dcqs.apply_closure_to_all_completed_buffers(&clear);
+ dcqs.iterate_closure_all_threads(&clear, false);
clear.print_histo();
// Now ensure that there's no dirty cards.
@@ -491,13 +484,13 @@ void G1CollectedHeap::check_ct_logs_at_safepoint() {
guarantee(count2.n() == 0, "Card table should be clean.");
RedirtyLoggedCardTableEntryClosure redirty;
- JavaThread::dirty_card_queue_set().set_closure(&redirty);
- dcqs.apply_closure_to_all_completed_buffers();
- dcqs.iterate_closure_all_threads(false);
+ dcqs.apply_closure_to_all_completed_buffers(&redirty);
+ dcqs.iterate_closure_all_threads(&redirty, false);
gclog_or_tty->print_cr("Log entries = %d, dirty cards = %d.",
- clear.calls(), orig_count);
- guarantee(redirty.calls() == clear.calls(),
- "Or else mechanism is broken.");
+ clear.num_processed(), orig_count);
+ guarantee(redirty.num_processed() == clear.num_processed(),
+ err_msg("Redirtied "SIZE_FORMAT" cards, bug cleared "SIZE_FORMAT,
+ redirty.num_processed(), clear.num_processed()));
CountNonCleanMemRegionClosure count3(this);
ct_bs->mod_card_iterate(&count3);
@@ -506,8 +499,6 @@ void G1CollectedHeap::check_ct_logs_at_safepoint() {
orig_count, count3.n());
guarantee(count3.n() >= orig_count, "Should have restored them all.");
}
-
- JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
}
// Private class members.
@@ -1512,9 +1503,6 @@ bool G1CollectedHeap::do_collection(bool explicit_gc,
assert(g1_policy()->collection_set() == NULL, "must be");
g1_policy()->start_incremental_cset_building();
- // Clear the _cset_fast_test bitmap in anticipation of adding
- // regions to the incremental collection set for the next
- // evacuation pause.
clear_cset_fast_test();
init_mutator_alloc_region();
@@ -1934,8 +1922,7 @@ G1CollectedHeap::G1CollectedHeap(G1CollectorPolicy* policy_) :
_old_marking_cycles_started(0),
_old_marking_cycles_completed(0),
_concurrent_cycle_started(false),
- _in_cset_fast_test(NULL),
- _in_cset_fast_test_base(NULL),
+ _in_cset_fast_test(),
_dirty_cards_region_list(NULL),
_worker_cset_start_region(NULL),
_worker_cset_start_region_time_stamp(NULL),
@@ -2005,7 +1992,9 @@ jint G1CollectedHeap::initialize() {
Universe::check_alignment(max_byte_size, HeapRegion::GrainBytes, "g1 heap");
Universe::check_alignment(max_byte_size, heap_alignment, "g1 heap");
- _cg1r = new ConcurrentG1Refine(this);
+ _refine_cte_cl = new RefineCardTableEntryClosure();
+
+ _cg1r = new ConcurrentG1Refine(this, _refine_cte_cl);
// Reserve the maximum.
@@ -2077,20 +2066,7 @@ jint G1CollectedHeap::initialize() {
_g1h = this;
- _in_cset_fast_test_length = max_regions();
- _in_cset_fast_test_base =
- NEW_C_HEAP_ARRAY(bool, (size_t) _in_cset_fast_test_length, mtGC);
-
- // We're biasing _in_cset_fast_test to avoid subtracting the
- // beginning of the heap every time we want to index; basically
- // it's the same with what we do with the card table.
- _in_cset_fast_test = _in_cset_fast_test_base -
- ((uintx) _g1_reserved.start() >> HeapRegion::LogOfHRGrainBytes);
-
- // Clear the _cset_fast_test bitmap in anticipation of adding
- // regions to the incremental collection set for the first
- // evacuation pause.
- clear_cset_fast_test();
+ _in_cset_fast_test.initialize(_g1_reserved.start(), _g1_reserved.end(), HeapRegion::GrainBytes);
// Create the ConcurrentMark data structure and thread.
// (Must do this late, so that "max_regions" is defined.)
@@ -2113,25 +2089,21 @@ jint G1CollectedHeap::initialize() {
// Perform any initialization actions delegated to the policy.
g1_policy()->init();
- _refine_cte_cl =
- new RefineCardTableEntryClosure(ConcurrentG1RefineThread::sts(),
- g1_rem_set(),
- concurrent_g1_refine());
- JavaThread::dirty_card_queue_set().set_closure(_refine_cte_cl);
-
JavaThread::satb_mark_queue_set().initialize(SATB_Q_CBL_mon,
SATB_Q_FL_lock,
G1SATBProcessCompletedThreshold,
Shared_SATB_Q_lock);
- JavaThread::dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
+ JavaThread::dirty_card_queue_set().initialize(_refine_cte_cl,
+ DirtyCardQ_CBL_mon,
DirtyCardQ_FL_lock,
concurrent_g1_refine()->yellow_zone(),
concurrent_g1_refine()->red_zone(),
Shared_DirtyCardQ_lock);
if (G1DeferredRSUpdate) {
- dirty_card_queue_set().initialize(DirtyCardQ_CBL_mon,
+ dirty_card_queue_set().initialize(NULL, // Should never be called by the Java code
+ DirtyCardQ_CBL_mon,
DirtyCardQ_FL_lock,
-1, // never trigger processing
-1, // no limit on length
@@ -2141,7 +2113,8 @@ jint G1CollectedHeap::initialize() {
// Initialize the card queue set used to hold cards containing
// references into the collection set.
- _into_cset_dirty_card_queue_set.initialize(DirtyCardQ_CBL_mon,
+ _into_cset_dirty_card_queue_set.initialize(NULL, // Should never be called by the Java code
+ DirtyCardQ_CBL_mon,
DirtyCardQ_FL_lock,
-1, // never trigger processing
-1, // no limit on length
@@ -2178,6 +2151,23 @@ jint G1CollectedHeap::initialize() {
return JNI_OK;
}
+void G1CollectedHeap::stop() {
+#if 0
+ // Stopping concurrent worker threads is currently disabled until
+ // some bugs in concurrent mark has been resolve. Without fixing
+ // those bugs first we risk haning during VM exit when trying to
+ // stop these threads.
+
+ // Abort any ongoing concurrent root region scanning and stop all
+ // concurrent threads. We do this to make sure these threads do
+ // not continue to execute and access resources (e.g. gclog_or_tty)
+ // that are destroyed during shutdown.
+ _cm->root_regions()->abort();
+ _cm->root_regions()->wait_until_scan_finished();
+ stop_conc_gc_threads();
+#endif
+}
+
size_t G1CollectedHeap::conservative_max_heap_alignment() {
return HeapRegion::max_region_size();
}
@@ -2963,21 +2953,16 @@ CompactibleSpace* G1CollectedHeap::first_compactible_space() {
Space* G1CollectedHeap::space_containing(const void* addr) const {
- Space* res = heap_region_containing(addr);
- return res;
+ return heap_region_containing(addr);
}
HeapWord* G1CollectedHeap::block_start(const void* addr) const {
Space* sp = space_containing(addr);
- if (sp != NULL) {
- return sp->block_start(addr);
- }
- return NULL;
+ return sp->block_start(addr);
}
size_t G1CollectedHeap::block_size(const HeapWord* addr) const {
Space* sp = space_containing(addr);
- assert(sp != NULL, "block_size of address outside of heap");
return sp->block_size(addr);
}
@@ -3212,7 +3197,7 @@ class VerifyKlassClosure: public KlassClosure {
_young_ref_counter_closure.reset_count();
k->oops_do(&_young_ref_counter_closure);
if (_young_ref_counter_closure.count() > 0) {
- guarantee(k->has_modified_oops(), err_msg("Klass %p, has young refs but is not dirty.", k));
+ guarantee(k->has_modified_oops(), err_msg("Klass " PTR_FORMAT ", has young refs but is not dirty.", k));
}
}
};
@@ -3296,7 +3281,7 @@ public:
int *val;
for (cur = start; cur < end; cur++) {
val = (int *) cur;
- gclog_or_tty->print("\t "PTR_FORMAT":"PTR_FORMAT"\n", val, *val);
+ gclog_or_tty->print("\t "PTR_FORMAT":%d\n", val, *val);
}
}
}
@@ -4125,9 +4110,6 @@ G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
// Start a new incremental collection set for the next pause.
g1_policy()->start_incremental_cset_building();
- // Clear the _cset_fast_test bitmap in anticipation of adding
- // regions to the incremental collection set for the next
- // evacuation pause.
clear_cset_fast_test();
_young_list->reset_sampled_info();
@@ -4304,7 +4286,7 @@ G1CollectedHeap::do_collection_pause_at_safepoint(double target_pause_time_ms) {
// this point does not assume that we are the only GC thread
// running. Note: of course, the actual marking work will
// not start until the safepoint itself is released in
- // ConcurrentGCThread::safepoint_desynchronize().
+ // SuspendibleThreadSet::desynchronize().
doConcurrentMark();
}
@@ -4571,7 +4553,7 @@ HeapWord* G1CollectedHeap::par_allocate_during_gc(GCAllocPurpose purpose,
}
G1ParGCAllocBuffer::G1ParGCAllocBuffer(size_t gclab_word_size) :
- ParGCAllocBuffer(gclab_word_size), _retired(false) { }
+ ParGCAllocBuffer(gclab_word_size), _retired(true) { }
G1ParScanThreadState::G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp)
: _g1h(g1h),
@@ -4694,30 +4676,19 @@ G1ParClosureSuper::G1ParClosureSuper(G1CollectedHeap* g1,
_worker_id(par_scan_state->queue_num()) { }
void G1ParCopyHelper::mark_object(oop obj) {
-#ifdef ASSERT
- HeapRegion* hr = _g1->heap_region_containing(obj);
- assert(hr != NULL, "sanity");
- assert(!hr->in_collection_set(), "should not mark objects in the CSet");
-#endif // ASSERT
+ assert(!_g1->heap_region_containing(obj)->in_collection_set(), "should not mark objects in the CSet");
// We know that the object is not moving so it's safe to read its size.
_cm->grayRoot(obj, (size_t) obj->size(), _worker_id);
}
void G1ParCopyHelper::mark_forwarded_object(oop from_obj, oop to_obj) {
-#ifdef ASSERT
assert(from_obj->is_forwarded(), "from obj should be forwarded");
assert(from_obj->forwardee() == to_obj, "to obj should be the forwardee");
assert(from_obj != to_obj, "should not be self-forwarded");
- HeapRegion* from_hr = _g1->heap_region_containing(from_obj);
- assert(from_hr != NULL, "sanity");
- assert(from_hr->in_collection_set(), "from obj should be in the CSet");
-
- HeapRegion* to_hr = _g1->heap_region_containing(to_obj);
- assert(to_hr != NULL, "sanity");
- assert(!to_hr->in_collection_set(), "should not mark objects in the CSet");
-#endif // ASSERT
+ assert(_g1->heap_region_containing(from_obj)->in_collection_set(), "from obj should be in the CSet");
+ assert(!_g1->heap_region_containing(to_obj)->in_collection_set(), "should not mark objects in the CSet");
// The object might be in the process of being copied by another
// worker so we cannot trust that its to-space image is
@@ -4935,8 +4906,6 @@ void G1ParEvacuateFollowersClosure::do_void() {
pss->trim_queue();
}
} while (!offer_termination());
-
- pss->retire_alloc_buffers();
}
class G1KlassScanClosure : public KlassClosure {
@@ -5273,11 +5242,25 @@ void G1CollectedHeap::unlink_string_and_symbol_table(BoolObjectClosure* is_alive
}
}
-class RedirtyLoggedCardTableEntryFastClosure : public CardTableEntryClosure {
-public:
- bool do_card_ptr(jbyte* card_ptr, uint worker_i) {
- *card_ptr = CardTableModRefBS::dirty_card_val();
- return true;
+class G1RedirtyLoggedCardsTask : public AbstractGangTask {
+ private:
+ DirtyCardQueueSet* _queue;
+ public:
+ G1RedirtyLoggedCardsTask(DirtyCardQueueSet* queue) : AbstractGangTask("Redirty Cards"), _queue(queue) { }
+
+ virtual void work(uint worker_id) {
+ double start_time = os::elapsedTime();
+
+ RedirtyLoggedCardTableEntryClosure cl;
+ if (G1CollectedHeap::heap()->use_parallel_gc_threads()) {
+ _queue->par_apply_closure_to_all_completed_buffers(&cl);
+ } else {
+ _queue->apply_closure_to_all_completed_buffers(&cl);
+ }
+
+ G1GCPhaseTimes* timer = G1CollectedHeap::heap()->g1_policy()->phase_times();
+ timer->record_redirty_logged_cards_time_ms(worker_id, (os::elapsedTime() - start_time) * 1000.0);
+ timer->record_redirty_logged_cards_processed_cards(worker_id, cl.num_processed());
}
};
@@ -5285,9 +5268,18 @@ void G1CollectedHeap::redirty_logged_cards() {
guarantee(G1DeferredRSUpdate, "Must only be called when using deferred RS updates.");
double redirty_logged_cards_start = os::elapsedTime();
- RedirtyLoggedCardTableEntryFastClosure redirty;
- dirty_card_queue_set().set_closure(&redirty);
- dirty_card_queue_set().apply_closure_to_all_completed_buffers();
+ uint n_workers = (G1CollectedHeap::use_parallel_gc_threads() ?
+ _g1h->workers()->active_workers() : 1);
+
+ G1RedirtyLoggedCardsTask redirty_task(&dirty_card_queue_set());
+ dirty_card_queue_set().reset_for_par_iteration();
+ if (use_parallel_gc_threads()) {
+ set_par_threads(n_workers);
+ workers()->run_task(&redirty_task);
+ set_par_threads(0);
+ } else {
+ redirty_task.work(0);
+ }
DirtyCardQueueSet& dcq = JavaThread::dirty_card_queue_set();
dcq.merge_bufferlists(&dirty_card_queue_set());
@@ -5762,10 +5754,8 @@ void G1CollectedHeap::process_discovered_references(uint no_of_gc_workers) {
}
_gc_tracer_stw->report_gc_reference_stats(stats);
- // We have completed copying any necessary live referent objects
- // (that were not copied during the actual pause) so we can
- // retire any active alloc buffers
- pss.retire_alloc_buffers();
+
+ // We have completed copying any necessary live referent objects.
assert(pss.refs()->is_empty(), "both queue and overflow should be empty");
double ref_proc_time = os::elapsedTime() - ref_proc_start;
@@ -6456,11 +6446,7 @@ void G1CollectedHeap::set_refine_cte_cl_concurrency(bool concurrent) {
bool G1CollectedHeap::is_in_closed_subset(const void* p) const {
HeapRegion* hr = heap_region_containing(p);
- if (hr == NULL) {
- return false;
- } else {
- return hr->is_in(p);
- }
+ return hr->is_in(p);
}
// Methods for the mutator alloc region
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp
index 4e8e30f4f2c..743fc291975 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp
@@ -28,6 +28,7 @@
#include "gc_implementation/g1/concurrentMark.hpp"
#include "gc_implementation/g1/evacuationInfo.hpp"
#include "gc_implementation/g1/g1AllocRegion.hpp"
+#include "gc_implementation/g1/g1BiasedArray.hpp"
#include "gc_implementation/g1/g1HRPrinter.hpp"
#include "gc_implementation/g1/g1MonitoringSupport.hpp"
#include "gc_implementation/g1/g1RemSet.hpp"
@@ -197,6 +198,16 @@ public:
bool do_object_b(oop p);
};
+// Instances of this class are used for quick tests on whether a reference points
+// into the collection set. Each of the array's elements denotes whether the
+// corresponding region is in the collection set.
+class G1FastCSetBiasedMappedArray : public G1BiasedMappedArray {
+ protected:
+ bool default_value() const { return false; }
+ public:
+ void clear() { G1BiasedMappedArray::clear(); }
+};
+
class RefineCardTableEntryClosure;
class G1CollectedHeap : public SharedHeap {
@@ -353,26 +364,10 @@ private:
// than the current allocation region.
size_t _summary_bytes_used;
- // This is used for a quick test on whether a reference points into
- // the collection set or not. Basically, we have an array, with one
- // byte per region, and that byte denotes whether the corresponding
- // region is in the collection set or not. The entry corresponding
- // the bottom of the heap, i.e., region 0, is pointed to by
- // _in_cset_fast_test_base. The _in_cset_fast_test field has been
- // biased so that it actually points to address 0 of the address
- // space, to make the test as fast as possible (we can simply shift
- // the address to address into it, instead of having to subtract the
- // bottom of the heap from the address before shifting it; basically
- // it works in the same way the card table works).
- bool* _in_cset_fast_test;
-
- // The allocated array used for the fast test on whether a reference
- // points into the collection set or not. This field is also used to
- // free the array.
- bool* _in_cset_fast_test_base;
-
- // The length of the _in_cset_fast_test_base array.
- uint _in_cset_fast_test_length;
+ // This array is used for a quick test on whether a reference points into
+ // the collection set or not. Each of the array's elements denotes whether the
+ // corresponding region is in the collection set or not.
+ G1FastCSetBiasedMappedArray _in_cset_fast_test;
volatile unsigned _gc_time_stamp;
@@ -695,12 +690,7 @@ public:
// We register a region with the fast "in collection set" test. We
// simply set to true the array slot corresponding to this region.
void register_region_with_in_cset_fast_test(HeapRegion* r) {
- assert(_in_cset_fast_test_base != NULL, "sanity");
- assert(r->in_collection_set(), "invariant");
- uint index = r->hrs_index();
- assert(index < _in_cset_fast_test_length, "invariant");
- assert(!_in_cset_fast_test_base[index], "invariant");
- _in_cset_fast_test_base[index] = true;
+ _in_cset_fast_test.set_by_index(r->hrs_index(), true);
}
// This is a fast test on whether a reference points into the
@@ -709,9 +699,7 @@ public:
inline bool in_cset_fast_test(oop obj);
void clear_cset_fast_test() {
- assert(_in_cset_fast_test_base != NULL, "sanity");
- memset(_in_cset_fast_test_base, false,
- (size_t) _in_cset_fast_test_length * sizeof(bool));
+ _in_cset_fast_test.clear();
}
// This is called at the start of either a concurrent cycle or a Full
@@ -1077,6 +1065,8 @@ public:
// specified by the policy object.
jint initialize();
+ virtual void stop();
+
// Return the (conservative) maximum heap alignment for any G1 heap
static size_t conservative_max_heap_alignment();
@@ -1390,17 +1380,15 @@ public:
// space containing a given address, or else returns NULL.
virtual Space* space_containing(const void* addr) const;
- // A G1CollectedHeap will contain some number of heap regions. This
- // finds the region containing a given address, or else returns NULL.
- template
- inline HeapRegion* heap_region_containing(const T addr) const;
-
- // Like the above, but requires "addr" to be in the heap (to avoid a
- // null-check), and unlike the above, may return an continuing humongous
- // region.
+ // Returns the HeapRegion that contains addr. addr must not be NULL.
template
inline HeapRegion* heap_region_containing_raw(const T addr) const;
+ // Returns the HeapRegion that contains addr. addr must not be NULL.
+ // If addr is within a humongous continues region, it returns its humongous start region.
+ template
+ inline HeapRegion* heap_region_containing(const T addr) const;
+
// A CollectedHeap is divided into a dense sequence of "blocks"; that is,
// each address in the (reserved) heap is a member of exactly
// one block. The defining characteristic of a block is that it is
@@ -1542,7 +1530,6 @@ public:
// the region to which the object belongs. An object is dead
// iff a) it was not allocated since the last mark and b) it
// is not marked.
-
bool is_obj_dead(const oop obj, const HeapRegion* hr) const {
return
!hr->obj_allocated_since_prev_marking(obj) &&
@@ -1552,7 +1539,6 @@ public:
// This function returns true when an object has been
// around since the previous marking and hasn't yet
// been marked during this marking.
-
bool is_obj_ill(const oop obj, const HeapRegion* hr) const {
return
!hr->obj_allocated_since_next_marking(obj) &&
@@ -1698,15 +1684,19 @@ private:
public:
G1ParGCAllocBuffer(size_t gclab_word_size);
+ virtual ~G1ParGCAllocBuffer() {
+ guarantee(_retired, "Allocation buffer has not been retired");
+ }
- void set_buf(HeapWord* buf) {
+ virtual void set_buf(HeapWord* buf) {
ParGCAllocBuffer::set_buf(buf);
_retired = false;
}
- void retire(bool end_of_gc, bool retain) {
- if (_retired)
+ virtual void retire(bool end_of_gc, bool retain) {
+ if (_retired) {
return;
+ }
ParGCAllocBuffer::retire(end_of_gc, retain);
_retired = true;
}
@@ -1776,6 +1766,7 @@ public:
G1ParScanThreadState(G1CollectedHeap* g1h, uint queue_num, ReferenceProcessor* rp);
~G1ParScanThreadState() {
+ retire_alloc_buffers();
FREE_C_HEAP_ARRAY(size_t, _surviving_young_words_base, mtGC);
}
@@ -1886,6 +1877,7 @@ public:
return _surviving_young_words;
}
+private:
void retire_alloc_buffers() {
for (int ap = 0; ap < GCAllocPurposeCount; ++ap) {
size_t waste = _alloc_buffers[ap]->words_remaining();
@@ -1895,8 +1887,8 @@ public:
false /* retain */);
}
}
-private:
- #define G1_PARTIAL_ARRAY_MASK 0x2
+
+#define G1_PARTIAL_ARRAY_MASK 0x2
inline bool has_partial_array_mask(oop* ref) const {
return ((uintptr_t)ref & G1_PARTIAL_ARRAY_MASK) == G1_PARTIAL_ARRAY_MASK;
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp
index e3b8fd061a3..b7169604b35 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp
@@ -42,21 +42,22 @@ inline HeapRegion* G1CollectedHeap::region_at(uint index) const { return _hrs.at
template
inline HeapRegion*
-G1CollectedHeap::heap_region_containing(const T addr) const {
- HeapRegion* hr = _hrs.addr_to_region((HeapWord*) addr);
- // hr can be null if addr in perm_gen
- if (hr != NULL && hr->continuesHumongous()) {
- hr = hr->humongous_start_region();
- }
- return hr;
+G1CollectedHeap::heap_region_containing_raw(const T addr) const {
+ assert(addr != NULL, "invariant");
+ assert(_g1_reserved.contains((const void*) addr),
+ err_msg("Address "PTR_FORMAT" is outside of the heap ranging from ["PTR_FORMAT" to "PTR_FORMAT")",
+ (void*)addr, _g1_reserved.start(), _g1_reserved.end()));
+ return _hrs.addr_to_region((HeapWord*) addr);
}
template
inline HeapRegion*
-G1CollectedHeap::heap_region_containing_raw(const T addr) const {
- assert(_g1_reserved.contains((const void*) addr), "invariant");
- HeapRegion* res = _hrs.addr_to_region_unsafe((HeapWord*) addr);
- return res;
+G1CollectedHeap::heap_region_containing(const T addr) const {
+ HeapRegion* hr = heap_region_containing_raw(addr);
+ if (hr->continuesHumongous()) {
+ return hr->humongous_start_region();
+ }
+ return hr;
}
inline void G1CollectedHeap::old_set_remove(HeapRegion* hr) {
@@ -134,8 +135,7 @@ G1CollectedHeap::dirty_young_block(HeapWord* start, size_t word_size) {
// have to keep calling heap_region_containing_raw() in the
// asserts below.
DEBUG_ONLY(HeapRegion* containing_hr = heap_region_containing_raw(start);)
- assert(containing_hr != NULL && start != NULL && word_size > 0,
- "pre-condition");
+ assert(word_size > 0, "pre-condition");
assert(containing_hr->is_in(start), "it should contain start");
assert(containing_hr->is_young(), "it should be young");
assert(!containing_hr->isHumongous(), "it should not be humongous");
@@ -164,12 +164,7 @@ inline bool G1CollectedHeap::isMarkedNext(oop obj) const {
// collection set or not. Assume that the reference
// points into the heap.
inline bool G1CollectedHeap::in_cset_fast_test(oop obj) {
- assert(_in_cset_fast_test != NULL, "sanity");
- assert(_g1_committed.contains((HeapWord*) obj), err_msg("Given reference outside of heap, is "PTR_FORMAT, (HeapWord*)obj));
- // no need to subtract the bottom of the heap from obj,
- // _in_cset_fast_test is biased
- uintx index = cast_from_oop(obj) >> HeapRegion::LogOfHRGrainBytes;
- bool ret = _in_cset_fast_test[index];
+ bool ret = _in_cset_fast_test.get_by_address((HeapWord*)obj);
// let's make sure the result is consistent with what the slower
// test returns
assert( ret || !obj_in_cs(obj), "sanity");
@@ -251,8 +246,10 @@ inline void G1CollectedHeap::reset_evacuation_should_fail() {
#endif // #ifndef PRODUCT
inline bool G1CollectedHeap::is_in_young(const oop obj) {
- HeapRegion* hr = heap_region_containing(obj);
- return hr != NULL && hr->is_young();
+ if (obj == NULL) {
+ return false;
+ }
+ return heap_region_containing(obj)->is_young();
}
// We don't need barriers for initializing stores to objects
@@ -265,21 +262,17 @@ inline bool G1CollectedHeap::can_elide_initializing_store_barrier(oop new_obj) {
}
inline bool G1CollectedHeap::is_obj_dead(const oop obj) const {
- const HeapRegion* hr = heap_region_containing(obj);
- if (hr == NULL) {
- if (obj == NULL) return false;
- else return true;
+ if (obj == NULL) {
+ return false;
}
- else return is_obj_dead(obj, hr);
+ return is_obj_dead(obj, heap_region_containing(obj));
}
inline bool G1CollectedHeap::is_obj_ill(const oop obj) const {
- const HeapRegion* hr = heap_region_containing(obj);
- if (hr == NULL) {
- if (obj == NULL) return false;
- else return true;
+ if (obj == NULL) {
+ return false;
}
- else return is_obj_ill(obj, hr);
+ return is_obj_ill(obj, heap_region_containing(obj));
}
template inline void G1ParScanThreadState::immediate_rs_update(HeapRegion* from, T* p, int tid) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
index 5fbf7101209..c4c3432ad43 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.cpp
@@ -170,6 +170,8 @@ G1GCPhaseTimes::G1GCPhaseTimes(uint max_gc_threads) :
_last_gc_worker_end_times_ms(_max_gc_threads, "%.1lf", false),
_last_gc_worker_times_ms(_max_gc_threads, "%.1lf"),
_last_gc_worker_other_times_ms(_max_gc_threads, "%.1lf"),
+ _last_redirty_logged_cards_time_ms(_max_gc_threads, "%.1lf"),
+ _last_redirty_logged_cards_processed_cards(_max_gc_threads, SIZE_FORMAT),
_cur_string_dedup_queue_fixup_worker_times_ms(_max_gc_threads, "%.1lf"),
_cur_string_dedup_table_fixup_worker_times_ms(_max_gc_threads, "%.1lf")
{
@@ -195,6 +197,10 @@ void G1GCPhaseTimes::note_gc_start(uint active_gc_threads) {
_last_gc_worker_end_times_ms.reset();
_last_gc_worker_times_ms.reset();
_last_gc_worker_other_times_ms.reset();
+
+ _last_redirty_logged_cards_time_ms.reset();
+ _last_redirty_logged_cards_processed_cards.reset();
+
}
void G1GCPhaseTimes::note_gc_end() {
@@ -230,6 +236,9 @@ void G1GCPhaseTimes::note_gc_end() {
_last_gc_worker_times_ms.verify();
_last_gc_worker_other_times_ms.verify();
+
+ _last_redirty_logged_cards_time_ms.verify();
+ _last_redirty_logged_cards_processed_cards.verify();
}
void G1GCPhaseTimes::note_string_dedup_fixup_start() {
@@ -349,6 +358,10 @@ void G1GCPhaseTimes::print(double pause_time_sec) {
print_stats(2, "Ref Enq", _cur_ref_enq_time_ms);
if (G1DeferredRSUpdate) {
print_stats(2, "Redirty Cards", _recorded_redirty_logged_cards_time_ms);
+ if (G1Log::finest()) {
+ _last_redirty_logged_cards_time_ms.print(3, "Parallel Redirty");
+ _last_redirty_logged_cards_processed_cards.print(3, "Redirtied Cards");
+ }
}
print_stats(2, "Free CSet",
(_recorded_young_free_cset_time_ms +
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.hpp
index e47c389f97d..221a7a1240d 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1GCPhaseTimes.hpp
@@ -151,6 +151,8 @@ class G1GCPhaseTimes : public CHeapObj {
double _recorded_young_cset_choice_time_ms;
double _recorded_non_young_cset_choice_time_ms;
+ WorkerDataArray _last_redirty_logged_cards_time_ms;
+ WorkerDataArray _last_redirty_logged_cards_processed_cards;
double _recorded_redirty_logged_cards_time_ms;
double _recorded_young_free_cset_time_ms;
@@ -293,6 +295,14 @@ class G1GCPhaseTimes : public CHeapObj {
_recorded_non_young_cset_choice_time_ms = time_ms;
}
+ void record_redirty_logged_cards_time_ms(uint worker_i, double time_ms) {
+ _last_redirty_logged_cards_time_ms.set(worker_i, time_ms);
+ }
+
+ void record_redirty_logged_cards_processed_cards(uint worker_i, size_t processed_buffers) {
+ _last_redirty_logged_cards_processed_cards.set(worker_i, processed_buffers);
+ }
+
void record_redirty_logged_cards_time_ms(double time_ms) {
_recorded_redirty_logged_cards_time_ms = time_ms;
}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp
index 998d478a5c5..1fa7639729c 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1OopClosures.inline.hpp
@@ -125,9 +125,7 @@ inline void G1RootRegionScanClosure::do_oop_nv(T* p) {
if (!oopDesc::is_null(heap_oop)) {
oop obj = oopDesc::decode_heap_oop_not_null(heap_oop);
HeapRegion* hr = _g1h->heap_region_containing((HeapWord*) obj);
- if (hr != NULL) {
- _cm->grayRoot(obj, obj->size(), _worker_id, hr);
- }
+ _cm->grayRoot(obj, obj->size(), _worker_id, hr);
}
}
@@ -154,57 +152,63 @@ inline void G1InvokeIfNotTriggeredClosure::do_oop_nv(T* p) {
template
inline void G1UpdateRSOrPushRefOopClosure::do_oop_nv(T* p) {
oop obj = oopDesc::load_decode_heap_oop(p);
+ if (obj == NULL) {
+ return;
+ }
+
#ifdef ASSERT
// can't do because of races
// assert(obj == NULL || obj->is_oop(), "expected an oop");
// Do the safe subset of is_oop
- if (obj != NULL) {
#ifdef CHECK_UNHANDLED_OOPS
- oopDesc* o = obj.obj();
+ oopDesc* o = obj.obj();
#else
- oopDesc* o = obj;
+ oopDesc* o = obj;
#endif // CHECK_UNHANDLED_OOPS
- assert((intptr_t)o % MinObjAlignmentInBytes == 0, "not oop aligned");
- assert(Universe::heap()->is_in_reserved(obj), "must be in heap");
- }
+ assert((intptr_t)o % MinObjAlignmentInBytes == 0, "not oop aligned");
+ assert(Universe::heap()->is_in_reserved(obj), "must be in heap");
#endif // ASSERT
assert(_from != NULL, "from region must be non-NULL");
assert(_from->is_in_reserved(p), "p is not in from");
HeapRegion* to = _g1->heap_region_containing(obj);
- if (to != NULL && _from != to) {
- // The _record_refs_into_cset flag is true during the RSet
- // updating part of an evacuation pause. It is false at all
- // other times:
- // * rebuilding the remembered sets after a full GC
- // * during concurrent refinement.
- // * updating the remembered sets of regions in the collection
- // set in the event of an evacuation failure (when deferred
- // updates are enabled).
+ if (_from == to) {
+ // Normally this closure should only be called with cross-region references.
+ // But since Java threads are manipulating the references concurrently and we
+ // reload the values things may have changed.
+ return;
+ }
- if (_record_refs_into_cset && to->in_collection_set()) {
- // We are recording references that point into the collection
- // set and this particular reference does exactly that...
- // If the referenced object has already been forwarded
- // to itself, we are handling an evacuation failure and
- // we have already visited/tried to copy this object
- // there is no need to retry.
- if (!self_forwarded(obj)) {
- assert(_push_ref_cl != NULL, "should not be null");
- // Push the reference in the refs queue of the G1ParScanThreadState
- // instance for this worker thread.
- _push_ref_cl->do_oop(p);
- }
+ // The _record_refs_into_cset flag is true during the RSet
+ // updating part of an evacuation pause. It is false at all
+ // other times:
+ // * rebuilding the remembered sets after a full GC
+ // * during concurrent refinement.
+ // * updating the remembered sets of regions in the collection
+ // set in the event of an evacuation failure (when deferred
+ // updates are enabled).
- // Deferred updates to the CSet are either discarded (in the normal case),
- // or processed (if an evacuation failure occurs) at the end
- // of the collection.
- // See G1RemSet::cleanup_after_oops_into_collection_set_do().
- return;
+ if (_record_refs_into_cset && to->in_collection_set()) {
+ // We are recording references that point into the collection
+ // set and this particular reference does exactly that...
+ // If the referenced object has already been forwarded
+ // to itself, we are handling an evacuation failure and
+ // we have already visited/tried to copy this object
+ // there is no need to retry.
+ if (!self_forwarded(obj)) {
+ assert(_push_ref_cl != NULL, "should not be null");
+ // Push the reference in the refs queue of the G1ParScanThreadState
+ // instance for this worker thread.
+ _push_ref_cl->do_oop(p);
}
+ // Deferred updates to the CSet are either discarded (in the normal case),
+ // or processed (if an evacuation failure occurs) at the end
+ // of the collection.
+ // See G1RemSet::cleanup_after_oops_into_collection_set_do().
+ } else {
// We either don't care about pushing references that point into the
// collection set (i.e. we're not during an evacuation pause) _or_
// the reference doesn't point into the collection set. Either way
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp
index 15d4ab689a7..58212625c82 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.cpp
@@ -36,6 +36,7 @@
#include "gc_implementation/g1/heapRegionRemSet.hpp"
#include "memory/iterator.hpp"
#include "oops/oop.inline.hpp"
+#include "utilities/globalDefinitions.hpp"
#include "utilities/intHisto.hpp"
#define CARD_REPEAT_HISTO 0
@@ -163,7 +164,7 @@ public:
void printCard(HeapRegion* card_region, size_t card_index,
HeapWord* card_start) {
gclog_or_tty->print_cr("T %u Region [" PTR_FORMAT ", " PTR_FORMAT ") "
- "RS names card %p: "
+ "RS names card " SIZE_FORMAT_HEX ": "
"[" PTR_FORMAT ", " PTR_FORMAT ")",
_worker_i,
card_region->bottom(), card_region->end(),
@@ -209,7 +210,6 @@ public:
#endif
HeapRegion* card_region = _g1h->heap_region_containing(card_start);
- assert(card_region != NULL, "Yielding cards not in the heap?");
_cards++;
if (!card_region->is_on_dirty_cards_region_list()) {
@@ -404,7 +404,6 @@ public:
HeapWord* start = _ct_bs->addr_for(card_ptr);
// And find the region containing it.
HeapRegion* r = _g1->heap_region_containing(start);
- assert(r != NULL, "unexpected null");
// Scan oops in the card looking for references into the collection set
// Don't use addr_for(card_ptr + 1) which can ask for
@@ -566,11 +565,6 @@ bool G1RemSet::refine_card(jbyte* card_ptr, uint worker_i,
HeapWord* start = _ct_bs->addr_for(card_ptr);
// And find the region containing it.
HeapRegion* r = _g1->heap_region_containing(start);
- if (r == NULL) {
- // Again no need to return that this card contains refs that
- // point into the collection set.
- return false; // Not in the G1 heap (might be in perm, for example.)
- }
// Why do we have to check here whether a card is on a young region,
// given that we dirty young regions and, as a result, the
@@ -623,10 +617,6 @@ bool G1RemSet::refine_card(jbyte* card_ptr, uint worker_i,
start = _ct_bs->addr_for(card_ptr);
r = _g1->heap_region_containing(start);
- if (r == NULL) {
- // Not in the G1 heap
- return false;
- }
// Checking whether the region we got back from the cache
// is young here is inappropriate. The region could have been
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp
index 79f4df9251a..cf90d9ca23c 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSet.inline.hpp
@@ -45,26 +45,28 @@ inline void G1RemSet::write_ref(HeapRegion* from, T* p) {
template
inline void G1RemSet::par_write_ref(HeapRegion* from, T* p, int tid) {
oop obj = oopDesc::load_decode_heap_oop(p);
+ if (obj == NULL) {
+ return;
+ }
+
#ifdef ASSERT
// can't do because of races
// assert(obj == NULL || obj->is_oop(), "expected an oop");
// Do the safe subset of is_oop
- if (obj != NULL) {
#ifdef CHECK_UNHANDLED_OOPS
- oopDesc* o = obj.obj();
+ oopDesc* o = obj.obj();
#else
- oopDesc* o = obj;
+ oopDesc* o = obj;
#endif // CHECK_UNHANDLED_OOPS
- assert((intptr_t)o % MinObjAlignmentInBytes == 0, "not oop aligned");
- assert(Universe::heap()->is_in_reserved(obj), "must be in heap");
- }
+ assert((intptr_t)o % MinObjAlignmentInBytes == 0, "not oop aligned");
+ assert(Universe::heap()->is_in_reserved(obj), "must be in heap");
#endif // ASSERT
assert(from == NULL || from->is_in_reserved(p), "p is not in from");
HeapRegion* to = _g1->heap_region_containing(obj);
- if (to != NULL && from != to) {
+ if (from != to) {
assert(to->rem_set() != NULL, "Need per-region 'into' remsets.");
to->rem_set()->add_reference(p, tid);
}
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.cpp
index b1f8e01524e..d353d7ebd2d 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.cpp
@@ -44,6 +44,11 @@ void G1StringDedup::initialize() {
}
}
+void G1StringDedup::stop() {
+ assert(is_enabled(), "String deduplication not enabled");
+ G1StringDedupThread::stop();
+}
+
bool G1StringDedup::is_candidate_from_mark(oop obj) {
if (java_lang_String::is_instance(obj)) {
bool from_young = G1CollectedHeap::heap()->heap_region_containing_raw(obj)->is_young();
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.hpp
index 80af6b661d2..68f700f6585 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedup.hpp
@@ -110,8 +110,12 @@ public:
return _enabled;
}
+ // Initialize string deduplication.
static void initialize();
+ // Stop the deduplication thread.
+ static void stop();
+
// Immediately deduplicates the given String object, bypassing the
// the deduplication queue.
static void deduplicate(oop java_string);
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
index 330b5a434c2..8ae53e353bc 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.cpp
@@ -35,6 +35,7 @@ const size_t G1StringDedupQueue::_max_cache_size = 0; // Max cache size p
G1StringDedupQueue::G1StringDedupQueue() :
_cursor(0),
+ _cancel(false),
_empty(true),
_dropped(0) {
_nqueues = MAX2(ParallelGCThreads, (size_t)1);
@@ -55,11 +56,17 @@ void G1StringDedupQueue::create() {
void G1StringDedupQueue::wait() {
MonitorLockerEx ml(StringDedupQueue_lock, Mutex::_no_safepoint_check_flag);
- while (_queue->_empty) {
+ while (_queue->_empty && !_queue->_cancel) {
ml.wait(Mutex::_no_safepoint_check_flag);
}
}
+void G1StringDedupQueue::cancel_wait() {
+ MonitorLockerEx ml(StringDedupQueue_lock, Mutex::_no_safepoint_check_flag);
+ _queue->_cancel = true;
+ ml.notify();
+}
+
void G1StringDedupQueue::push(uint worker_id, oop java_string) {
assert(SafepointSynchronize::is_at_safepoint(), "Must be at safepoint");
assert(worker_id < _queue->_nqueues, "Invalid queue");
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.hpp
index 1690247b769..99f555b7076 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupQueue.hpp
@@ -65,6 +65,7 @@ private:
G1StringDedupWorkerQueue* _queues;
size_t _nqueues;
size_t _cursor;
+ bool _cancel;
volatile bool _empty;
// Statistics counter, only used for logging.
@@ -81,6 +82,9 @@ public:
// Blocks and waits for the queue to become non-empty.
static void wait();
+ // Wakes up any thread blocked waiting for the queue to become non-empty.
+ static void cancel_wait();
+
// Pushes a deduplication candidate onto a specific GC worker queue.
static void push(uint worker_id, oop java_string);
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
index 7263220a391..e59efa7b829 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
@@ -73,42 +73,60 @@ void G1StringDedupThread::run() {
// Wait for the queue to become non-empty
G1StringDedupQueue::wait();
-
- // Include this thread in safepoints
- stsJoin();
-
- stat.mark_exec();
-
- // Process the queue
- for (;;) {
- oop java_string = G1StringDedupQueue::pop();
- if (java_string == NULL) {
- break;
- }
-
- G1StringDedupTable::deduplicate(java_string, stat);
-
- // Safepoint this thread if needed
- if (stsShouldYield()) {
- stat.mark_block();
- stsYield(NULL);
- stat.mark_unblock();
- }
+ if (_should_terminate) {
+ break;
}
- G1StringDedupTable::trim_entry_cache();
+ {
+ // Include thread in safepoints
+ SuspendibleThreadSetJoiner sts;
- stat.mark_done();
+ stat.mark_exec();
- // Print statistics
- total_stat.add(stat);
- print(gclog_or_tty, stat, total_stat);
+ // Process the queue
+ for (;;) {
+ oop java_string = G1StringDedupQueue::pop();
+ if (java_string == NULL) {
+ break;
+ }
- // Exclude this thread from safepoints
- stsLeave();
+ G1StringDedupTable::deduplicate(java_string, stat);
+
+ // Safepoint this thread if needed
+ if (sts.should_yield()) {
+ stat.mark_block();
+ sts.yield();
+ stat.mark_unblock();
+ }
+ }
+
+ G1StringDedupTable::trim_entry_cache();
+
+ stat.mark_done();
+
+ // Print statistics
+ total_stat.add(stat);
+ print(gclog_or_tty, stat, total_stat);
+ }
}
- ShouldNotReachHere();
+ terminate();
+}
+
+void G1StringDedupThread::stop() {
+ {
+ MonitorLockerEx ml(Terminator_lock);
+ _thread->_should_terminate = true;
+ }
+
+ G1StringDedupQueue::cancel_wait();
+
+ {
+ MonitorLockerEx ml(Terminator_lock);
+ while (!_thread->_has_terminated) {
+ ml.wait();
+ }
+ }
}
void G1StringDedupThread::print(outputStream* st, const G1StringDedupStat& last_stat, const G1StringDedupStat& total_stat) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.hpp
index 8a93058fd1e..eb60a0b7614 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.hpp
@@ -47,6 +47,8 @@ private:
public:
static void create();
+ static void stop();
+
static G1StringDedupThread* thread();
virtual void run();
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
index b810312ec9d..016e7b0109d 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp
@@ -167,7 +167,7 @@ public:
// Mem size in bytes.
size_t mem_size() const {
- return sizeof(this) + _bm.size_in_words() * HeapWordSize;
+ return sizeof(PerRegionTable) + _bm.size_in_words() * HeapWordSize;
}
// Requires "from" to be in "hr()".
@@ -491,7 +491,7 @@ void OtherRegionsTable::add_reference(OopOrNarrowOopStar from, int tid) {
} else {
if (G1TraceHeapRegionRememberedSet) {
gclog_or_tty->print_cr(" [tid %d] sparse table entry "
- "overflow(f: %d, t: %d)",
+ "overflow(f: %d, t: %u)",
tid, from_hrs_ind, cur_hrs_ind);
}
}
@@ -610,7 +610,7 @@ PerRegionTable* OtherRegionsTable::delete_region_table() {
_n_coarse_entries++;
if (G1TraceHeapRegionRememberedSet) {
gclog_or_tty->print("Coarsened entry in region [" PTR_FORMAT "...] "
- "for region [" PTR_FORMAT "...] (%d coarse entries).\n",
+ "for region [" PTR_FORMAT "...] (" SIZE_FORMAT " coarse entries).\n",
hr()->bottom(),
max->hr()->bottom(),
_n_coarse_entries);
@@ -733,7 +733,7 @@ size_t OtherRegionsTable::mem_size() const {
sum += (sizeof(PerRegionTable*) * _max_fine_entries);
sum += (_coarse_map.size_in_words() * HeapWordSize);
sum += (_sparse_table.mem_size());
- sum += sizeof(*this) - sizeof(_sparse_table); // Avoid double counting above.
+ sum += sizeof(OtherRegionsTable) - sizeof(_sparse_table); // Avoid double counting above.
return sum;
}
@@ -768,30 +768,6 @@ void OtherRegionsTable::clear() {
clear_fcc();
}
-void OtherRegionsTable::clear_incoming_entry(HeapRegion* from_hr) {
- MutexLockerEx x(_m, Mutex::_no_safepoint_check_flag);
- size_t hrs_ind = (size_t) from_hr->hrs_index();
- size_t ind = hrs_ind & _mod_max_fine_entries_mask;
- if (del_single_region_table(ind, from_hr)) {
- assert(!_coarse_map.at(hrs_ind), "Inv");
- } else {
- _coarse_map.par_at_put(hrs_ind, 0);
- }
- // Check to see if any of the fcc entries come from here.
- uint hr_ind = hr()->hrs_index();
- for (uint tid = 0; tid < HeapRegionRemSet::num_par_rem_sets(); tid++) {
- int fcc_ent = FromCardCache::at(tid, hr_ind);
- if (fcc_ent != FromCardCache::InvalidCard) {
- HeapWord* card_addr = (HeapWord*)
- (uintptr_t(fcc_ent) << CardTableModRefBS::card_shift);
- if (hr()->is_in_reserved(card_addr)) {
- // Clear the from card cache.
- FromCardCache::set(tid, hr_ind, FromCardCache::InvalidCard);
- }
- }
- }
-}
-
bool OtherRegionsTable::del_single_region_table(size_t ind,
HeapRegion* hr) {
assert(0 <= ind && ind < _max_fine_entries, "Preconditions.");
@@ -821,7 +797,6 @@ bool OtherRegionsTable::contains_reference(OopOrNarrowOopStar from) const {
bool OtherRegionsTable::contains_reference_locked(OopOrNarrowOopStar from) const {
HeapRegion* hr = _g1h->heap_region_containing_raw(from);
- if (hr == NULL) return false;
RegionIdx_t hr_ind = (RegionIdx_t) hr->hrs_index();
// Is this region in the coarse map?
if (_coarse_map.at(hr_ind)) return true;
@@ -903,10 +878,12 @@ void HeapRegionRemSet::print() {
}
if (iter.n_yielded() != occupied()) {
gclog_or_tty->print_cr("Yielded disagrees with occupied:");
- gclog_or_tty->print_cr(" %6d yielded (%6d coarse, %6d fine).",
+ gclog_or_tty->print_cr(" " SIZE_FORMAT_W(6) " yielded (" SIZE_FORMAT_W(6)
+ " coarse, " SIZE_FORMAT_W(6) " fine).",
iter.n_yielded(),
iter.n_yielded_coarse(), iter.n_yielded_fine());
- gclog_or_tty->print_cr(" %6d occ (%6d coarse, %6d fine).",
+ gclog_or_tty->print_cr(" " SIZE_FORMAT_W(6) " occ (" SIZE_FORMAT_W(6)
+ " coarse, " SIZE_FORMAT_W(6) " fine).",
occupied(), occ_coarse(), occ_fine());
}
guarantee(iter.n_yielded() == occupied(),
@@ -1046,20 +1023,16 @@ size_t HeapRegionRemSet::strong_code_roots_mem_size() {
return _code_roots.mem_size();
}
-//-------------------- Iteration --------------------
-
HeapRegionRemSetIterator:: HeapRegionRemSetIterator(HeapRegionRemSet* hrrs) :
_hrrs(hrrs),
_g1h(G1CollectedHeap::heap()),
_coarse_map(&hrrs->_other_regions._coarse_map),
- _fine_grain_regions(hrrs->_other_regions._fine_grain_regions),
_bosa(hrrs->bosa()),
_is(Sparse),
// Set these values so that we increment to the first region.
_coarse_cur_region_index(-1),
_coarse_cur_region_cur_card(HeapRegion::CardsPerRegion-1),
- _cur_region_cur_card(0),
- _fine_array_index(-1),
+ _cur_card_in_prt(HeapRegion::CardsPerRegion),
_fine_cur_prt(NULL),
_n_yielded_coarse(0),
_n_yielded_fine(0),
@@ -1091,58 +1064,59 @@ bool HeapRegionRemSetIterator::coarse_has_next(size_t& card_index) {
return true;
}
-void HeapRegionRemSetIterator::fine_find_next_non_null_prt() {
- // Otherwise, find the next bucket list in the array.
- _fine_array_index++;
- while (_fine_array_index < (int) OtherRegionsTable::_max_fine_entries) {
- _fine_cur_prt = _fine_grain_regions[_fine_array_index];
- if (_fine_cur_prt != NULL) return;
- else _fine_array_index++;
- }
- assert(_fine_cur_prt == NULL, "Loop post");
-}
-
bool HeapRegionRemSetIterator::fine_has_next(size_t& card_index) {
if (fine_has_next()) {
- _cur_region_cur_card =
- _fine_cur_prt->_bm.get_next_one_offset(_cur_region_cur_card + 1);
+ _cur_card_in_prt =
+ _fine_cur_prt->_bm.get_next_one_offset(_cur_card_in_prt + 1);
}
- while (!fine_has_next()) {
- if (_cur_region_cur_card == (size_t) HeapRegion::CardsPerRegion) {
- _cur_region_cur_card = 0;
- _fine_cur_prt = _fine_cur_prt->collision_list_next();
+ if (_cur_card_in_prt == HeapRegion::CardsPerRegion) {
+ // _fine_cur_prt may still be NULL in case if there are not PRTs at all for
+ // the remembered set.
+ if (_fine_cur_prt == NULL || _fine_cur_prt->next() == NULL) {
+ return false;
}
- if (_fine_cur_prt == NULL) {
- fine_find_next_non_null_prt();
- if (_fine_cur_prt == NULL) return false;
- }
- assert(_fine_cur_prt != NULL && _cur_region_cur_card == 0,
- "inv.");
- HeapWord* r_bot =
- _fine_cur_prt->hr()->bottom();
- _cur_region_card_offset = _bosa->index_for(r_bot);
- _cur_region_cur_card = _fine_cur_prt->_bm.get_next_one_offset(0);
+ PerRegionTable* next_prt = _fine_cur_prt->next();
+ switch_to_prt(next_prt);
+ _cur_card_in_prt = _fine_cur_prt->_bm.get_next_one_offset(_cur_card_in_prt + 1);
}
- assert(fine_has_next(), "Or else we exited the loop via the return.");
- card_index = _cur_region_card_offset + _cur_region_cur_card;
+
+ card_index = _cur_region_card_offset + _cur_card_in_prt;
+ guarantee(_cur_card_in_prt < HeapRegion::CardsPerRegion,
+ err_msg("Card index "SIZE_FORMAT" must be within the region", _cur_card_in_prt));
return true;
}
bool HeapRegionRemSetIterator::fine_has_next() {
- return
- _fine_cur_prt != NULL &&
- _cur_region_cur_card < HeapRegion::CardsPerRegion;
+ return _cur_card_in_prt != HeapRegion::CardsPerRegion;
+}
+
+void HeapRegionRemSetIterator::switch_to_prt(PerRegionTable* prt) {
+ assert(prt != NULL, "Cannot switch to NULL prt");
+ _fine_cur_prt = prt;
+
+ HeapWord* r_bot = _fine_cur_prt->hr()->bottom();
+ _cur_region_card_offset = _bosa->index_for(r_bot);
+
+ // The bitmap scan for the PRT always scans from _cur_region_cur_card + 1.
+ // To avoid special-casing this start case, and not miss the first bitmap
+ // entry, initialize _cur_region_cur_card with -1 instead of 0.
+ _cur_card_in_prt = (size_t)-1;
}
bool HeapRegionRemSetIterator::has_next(size_t& card_index) {
switch (_is) {
- case Sparse:
+ case Sparse: {
if (_sparse_iter.has_next(card_index)) {
_n_yielded_sparse++;
return true;
}
// Otherwise, deliberate fall-through
_is = Fine;
+ PerRegionTable* initial_fine_prt = _hrrs->_other_regions._first_all_fine_prts;
+ if (initial_fine_prt != NULL) {
+ switch_to_prt(_hrrs->_other_regions._first_all_fine_prts);
+ }
+ }
case Fine:
if (fine_has_next(card_index)) {
_n_yielded_fine++;
@@ -1274,6 +1248,11 @@ HeapRegionRemSet::finish_cleanup_task(HRRSCleanupTask* hrrs_cleanup_task) {
#ifndef PRODUCT
void PerRegionTable::test_fl_mem_size() {
PerRegionTable* dummy = alloc(NULL);
+
+ size_t min_prt_size = sizeof(void*) + dummy->bm()->size_in_words() * HeapWordSize;
+ assert(dummy->mem_size() > min_prt_size,
+ err_msg("PerRegionTable memory usage is suspiciously small, only has "SIZE_FORMAT" bytes. "
+ "Should be at least "SIZE_FORMAT" bytes.", dummy->mem_size(), min_prt_size));
free(dummy);
guarantee(dummy->mem_size() == fl_mem_size(), "fl_mem_size() does not return the correct element size");
// try to reset the state
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.hpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.hpp
index 0a080dbbf45..64a02ead2ea 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionRemSet.hpp
@@ -206,9 +206,6 @@ public:
// Specifically clear the from_card_cache.
void clear_fcc();
- // "from_hr" is being cleared; remove any entries from it.
- void clear_incoming_entry(HeapRegion* from_hr);
-
void do_cleanup_work(HRRSCleanupTask* hrrs_cleanup_task);
// Declare the heap size (in # of regions) to the OtherRegionsTable.
@@ -338,20 +335,20 @@ public:
return _other_regions.mem_size()
// This correction is necessary because the above includes the second
// part.
- + (sizeof(this) - sizeof(OtherRegionsTable))
+ + (sizeof(HeapRegionRemSet) - sizeof(OtherRegionsTable))
+ strong_code_roots_mem_size();
}
// Returns the memory occupancy of all static data structures associated
// with remembered sets.
static size_t static_mem_size() {
- return OtherRegionsTable::static_mem_size() + G1CodeRootSet::static_mem_size();
+ return OtherRegionsTable::static_mem_size() + G1CodeRootSet::free_chunks_static_mem_size();
}
// Returns the memory occupancy of all free_list data structures associated
// with remembered sets.
static size_t fl_mem_size() {
- return OtherRegionsTable::fl_mem_size() + G1CodeRootSet::fl_mem_size();
+ return OtherRegionsTable::fl_mem_size() + G1CodeRootSet::free_chunks_mem_size();
}
bool contains_reference(OopOrNarrowOopStar from) const {
@@ -396,7 +393,6 @@ public:
// Declare the heap size (in # of regions) to the HeapRegionRemSet(s).
// (Uses it to initialize from_card_cache).
static void init_heap(uint max_regions) {
- G1CodeRootSet::initialize();
OtherRegionsTable::init_from_card_cache(max_regions);
}
@@ -429,26 +425,24 @@ public:
};
class HeapRegionRemSetIterator : public StackObj {
-
- // The region RSet over which we're iterating.
+ private:
+ // The region RSet over which we are iterating.
HeapRegionRemSet* _hrrs;
// Local caching of HRRS fields.
const BitMap* _coarse_map;
- PerRegionTable** _fine_grain_regions;
G1BlockOffsetSharedArray* _bosa;
G1CollectedHeap* _g1h;
- // The number yielded since initialization.
+ // The number of cards yielded since initialization.
size_t _n_yielded_fine;
size_t _n_yielded_coarse;
size_t _n_yielded_sparse;
- // Indicates what granularity of table that we're currently iterating over.
+ // Indicates what granularity of table that we are currently iterating over.
// We start iterating over the sparse table, progress to the fine grain
// table, and then finish with the coarse table.
- // See HeapRegionRemSetIterator::has_next().
enum IterState {
Sparse,
Fine,
@@ -456,38 +450,30 @@ class HeapRegionRemSetIterator : public StackObj {
};
IterState _is;
- // In both kinds of iteration, heap offset of first card of current
- // region.
+ // For both Coarse and Fine remembered set iteration this contains the
+ // first card number of the heap region we currently iterate over.
size_t _cur_region_card_offset;
- // Card offset within cur region.
- size_t _cur_region_cur_card;
- // Coarse table iteration fields:
-
- // Current region index;
+ // Current region index for the Coarse remembered set iteration.
int _coarse_cur_region_index;
size_t _coarse_cur_region_cur_card;
bool coarse_has_next(size_t& card_index);
- // Fine table iteration fields:
-
- // Index of bucket-list we're working on.
- int _fine_array_index;
-
- // Per Region Table we're doing within current bucket list.
+ // The PRT we are currently iterating over.
PerRegionTable* _fine_cur_prt;
+ // Card offset within the current PRT.
+ size_t _cur_card_in_prt;
- /* SparsePRT::*/ SparsePRTIter _sparse_iter;
-
- void fine_find_next_non_null_prt();
-
+ // Update internal variables when switching to the given PRT.
+ void switch_to_prt(PerRegionTable* prt);
bool fine_has_next();
bool fine_has_next(size_t& card_index);
-public:
- // We require an iterator to be initialized before use, so the
- // constructor does little.
+ // The Sparse remembered set iterator.
+ SparsePRTIter _sparse_iter;
+
+ public:
HeapRegionRemSetIterator(HeapRegionRemSet* hrrs);
// If there remains one or more cards to be yielded, returns true and
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp
index c047dccab0d..62638a8f9b3 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.cpp
@@ -240,7 +240,6 @@ void HeapRegionSeq::verify_optional() {
// Asserts will fire if i is >= _length
HeapWord* addr = hr->bottom();
guarantee(addr_to_region(addr) == hr, "sanity");
- guarantee(addr_to_region_unsafe(addr) == hr, "sanity");
} else {
guarantee(hr->is_empty(), "sanity");
guarantee(!hr->isHumongous(), "sanity");
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.hpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.hpp
index 4f14926f34f..888b2ce5289 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.hpp
@@ -110,10 +110,6 @@ class HeapRegionSeq: public CHeapObj {
// HeapRegion, otherwise return NULL.
inline HeapRegion* addr_to_region(HeapWord* addr) const;
- // Return the HeapRegion that corresponds to the given
- // address. Assume the address is valid.
- inline HeapRegion* addr_to_region_unsafe(HeapWord* addr) const;
-
// Return the number of regions that have been committed in the heap.
uint length() const { return _committed_length; }
diff --git a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.inline.hpp b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.inline.hpp
index 0ee93e45b6e..429457a488f 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.inline.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/heapRegionSeq.inline.hpp
@@ -28,21 +28,17 @@
#include "gc_implementation/g1/heapRegion.hpp"
#include "gc_implementation/g1/heapRegionSeq.hpp"
-inline HeapRegion* HeapRegionSeq::addr_to_region_unsafe(HeapWord* addr) const {
+inline HeapRegion* HeapRegionSeq::addr_to_region(HeapWord* addr) const {
+ assert(addr < heap_end(),
+ err_msg("addr: "PTR_FORMAT" end: "PTR_FORMAT, addr, heap_end()));
+ assert(addr >= heap_bottom(),
+ err_msg("addr: "PTR_FORMAT" bottom: "PTR_FORMAT, addr, heap_bottom()));
+
HeapRegion* hr = _regions.get_by_address(addr);
assert(hr != NULL, "invariant");
return hr;
}
-inline HeapRegion* HeapRegionSeq::addr_to_region(HeapWord* addr) const {
- if (addr != NULL && addr < heap_end()) {
- assert(addr >= heap_bottom(),
- err_msg("addr: "PTR_FORMAT" bottom: "PTR_FORMAT, addr, heap_bottom()));
- return addr_to_region_unsafe(addr);
- }
- return NULL;
-}
-
inline HeapRegion* HeapRegionSeq::at(uint index) const {
assert(index < length(), "pre-condition");
HeapRegion* hr = _regions.get_by_index(index);
diff --git a/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp b/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp
index 627c6803902..11f30c36283 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/sparsePRT.cpp
@@ -370,7 +370,7 @@ bool RSHashTable::contains_card(RegionIdx_t region_index, CardIdx_t card_index)
}
size_t RSHashTable::mem_size() const {
- return sizeof(this) +
+ return sizeof(RSHashTable) +
capacity() * (SparsePRTEntry::size() + sizeof(int));
}
@@ -472,7 +472,7 @@ SparsePRT::~SparsePRT() {
size_t SparsePRT::mem_size() const {
// We ignore "_cur" here, because it either = _next, or else it is
// on the deleted list.
- return sizeof(this) + _next->mem_size();
+ return sizeof(SparsePRT) + _next->mem_size();
}
bool SparsePRT::add_card(RegionIdx_t region_id, CardIdx_t card_index) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/survRateGroup.cpp b/hotspot/src/share/vm/gc_implementation/g1/survRateGroup.cpp
index 1232cf390e8..49e4e01fa9e 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/survRateGroup.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/survRateGroup.cpp
@@ -187,10 +187,10 @@ SurvRateGroup::all_surviving_words_recorded(bool propagate) {
#ifndef PRODUCT
void
SurvRateGroup::print() {
- gclog_or_tty->print_cr("Surv Rate Group: %s (%d entries)",
+ gclog_or_tty->print_cr("Surv Rate Group: %s (" SIZE_FORMAT " entries)",
_name, _region_num);
for (size_t i = 0; i < _region_num; ++i) {
- gclog_or_tty->print_cr(" age %4d surv rate %6.2lf %% pred %6.2lf %%",
+ gclog_or_tty->print_cr(" age " SIZE_FORMAT_W(4) " surv rate %6.2lf %% pred %6.2lf %%",
i, _surv_rate[i] * 100.0,
_g1p->get_new_prediction(_surv_rate_pred[i]) * 100.0);
}
@@ -203,14 +203,15 @@ SurvRateGroup::print_surv_rate_summary() {
return;
gclog_or_tty->print_cr("");
- gclog_or_tty->print_cr("%s Rate Summary (for up to age %d)", _name, length-1);
+ gclog_or_tty->print_cr("%s Rate Summary (for up to age " SIZE_FORMAT ")", _name, length-1);
gclog_or_tty->print_cr(" age range survival rate (avg) samples (avg)");
gclog_or_tty->print_cr(" ---------------------------------------------------------");
size_t index = 0;
size_t limit = MIN2((int) length, 10);
while (index < limit) {
- gclog_or_tty->print_cr(" %4d %6.2lf%% %6.2lf",
+ gclog_or_tty->print_cr(" " SIZE_FORMAT_W(4)
+ " %6.2lf%% %6.2lf",
index, _summary_surv_rates[index]->avg() * 100.0,
(double) _summary_surv_rates[index]->num());
++index;
@@ -228,7 +229,8 @@ SurvRateGroup::print_surv_rate_summary() {
++index;
if (index == length || num % 10 == 0) {
- gclog_or_tty->print_cr(" %4d .. %4d %6.2lf%% %6.2lf",
+ gclog_or_tty->print_cr(" " SIZE_FORMAT_W(4) " .. " SIZE_FORMAT_W(4)
+ " %6.2lf%% %6.2lf",
(index-1) / 10 * 10, index-1, sum / (double) num,
(double) samples / (double) num);
sum = 0.0;
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/adjoiningGenerations.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/adjoiningGenerations.cpp
index c3e1231353b..468871ea5fc 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/adjoiningGenerations.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/adjoiningGenerations.cpp
@@ -143,7 +143,8 @@ void AdjoiningGenerations::request_old_gen_expansion(size_t expand_in_bytes) {
if (TraceAdaptiveGCBoundary) {
gclog_or_tty->print_cr("Before expansion of old gen with boundary move");
- gclog_or_tty->print_cr(" Requested change: 0x%x Attempted change: 0x%x",
+ gclog_or_tty->print_cr(" Requested change: " SIZE_FORMAT_HEX
+ " Attempted change: " SIZE_FORMAT_HEX,
expand_in_bytes, change_in_bytes);
if (!PrintHeapAtGC) {
Universe::print_on(gclog_or_tty);
@@ -201,7 +202,7 @@ bool AdjoiningGenerations::request_young_gen_expansion(size_t expand_in_bytes) {
if (TraceAdaptiveGCBoundary) {
gclog_or_tty->print_cr("Before expansion of young gen with boundary move");
- gclog_or_tty->print_cr(" Requested change: 0x%x Attempted change: 0x%x",
+ gclog_or_tty->print_cr(" Requested change: " SIZE_FORMAT_HEX " Attempted change: " SIZE_FORMAT_HEX,
expand_in_bytes, change_in_bytes);
if (!PrintHeapAtGC) {
Universe::print_on(gclog_or_tty);
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSOldGen.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSOldGen.cpp
index 829cb3cfe47..d1a169b89b3 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSOldGen.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSOldGen.cpp
@@ -127,22 +127,22 @@ size_t ASPSOldGen::available_for_contraction() {
size_t result_aligned = align_size_down(result, gen_alignment);
if (PrintAdaptiveSizePolicy && Verbose) {
gclog_or_tty->print_cr("\nASPSOldGen::available_for_contraction:"
- " %d K / 0x%x", result_aligned/K, result_aligned);
- gclog_or_tty->print_cr(" reserved().byte_size() %d K / 0x%x ",
+ " " SIZE_FORMAT " K / " SIZE_FORMAT_HEX, result_aligned/K, result_aligned);
+ gclog_or_tty->print_cr(" reserved().byte_size() " SIZE_FORMAT " K / " SIZE_FORMAT_HEX,
reserved().byte_size()/K, reserved().byte_size());
size_t working_promoted = (size_t) policy->avg_promoted()->padded_average();
- gclog_or_tty->print_cr(" padded promoted %d K / 0x%x",
+ gclog_or_tty->print_cr(" padded promoted " SIZE_FORMAT " K / " SIZE_FORMAT_HEX,
working_promoted/K, working_promoted);
- gclog_or_tty->print_cr(" used %d K / 0x%x",
+ gclog_or_tty->print_cr(" used " SIZE_FORMAT " K / " SIZE_FORMAT_HEX,
used_in_bytes()/K, used_in_bytes());
- gclog_or_tty->print_cr(" min_gen_size() %d K / 0x%x",
+ gclog_or_tty->print_cr(" min_gen_size() " SIZE_FORMAT " K / " SIZE_FORMAT_HEX,
min_gen_size()/K, min_gen_size());
- gclog_or_tty->print_cr(" max_contraction %d K / 0x%x",
+ gclog_or_tty->print_cr(" max_contraction " SIZE_FORMAT " K / " SIZE_FORMAT_HEX,
max_contraction/K, max_contraction);
- gclog_or_tty->print_cr(" without alignment %d K / 0x%x",
+ gclog_or_tty->print_cr(" without alignment " SIZE_FORMAT " K / " SIZE_FORMAT_HEX,
policy->promo_increment(max_contraction)/K,
policy->promo_increment(max_contraction));
- gclog_or_tty->print_cr(" alignment 0x%x", gen_alignment);
+ gclog_or_tty->print_cr(" alignment " SIZE_FORMAT_HEX, gen_alignment);
}
assert(result_aligned <= max_contraction, "arithmetic is wrong");
return result_aligned;
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp
index af5893bcc7b..f403a3a3a62 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/asPSYoungGen.cpp
@@ -112,11 +112,11 @@ size_t ASPSYoungGen::available_for_contraction() {
size_t result = policy->eden_increment_aligned_down(max_contraction);
size_t result_aligned = align_size_down(result, gen_alignment);
if (PrintAdaptiveSizePolicy && Verbose) {
- gclog_or_tty->print_cr("ASPSYoungGen::available_for_contraction: %d K",
+ gclog_or_tty->print_cr("ASPSYoungGen::available_for_contraction: " SIZE_FORMAT " K",
result_aligned/K);
- gclog_or_tty->print_cr(" max_contraction %d K", max_contraction/K);
- gclog_or_tty->print_cr(" eden_avail %d K", eden_avail/K);
- gclog_or_tty->print_cr(" gen_avail %d K", gen_avail/K);
+ gclog_or_tty->print_cr(" max_contraction " SIZE_FORMAT " K", max_contraction/K);
+ gclog_or_tty->print_cr(" eden_avail " SIZE_FORMAT " K", eden_avail/K);
+ gclog_or_tty->print_cr(" gen_avail " SIZE_FORMAT " K", gen_avail/K);
}
return result_aligned;
}
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/gcTaskManager.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/gcTaskManager.cpp
index 331c4e70f99..bf3e3bf001f 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/gcTaskManager.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/gcTaskManager.cpp
@@ -487,7 +487,7 @@ void GCTaskManager::set_active_gang() {
if (TraceDynamicGCThreads) {
gclog_or_tty->print_cr("GCTaskManager::set_active_gang(): "
"all_workers_active() %d workers %d "
- "active %d ParallelGCThreads %d ",
+ "active %d ParallelGCThreads " UINTX_FORMAT,
all_workers_active(), workers(), active_workers(),
ParallelGCThreads);
}
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/objectStartArray.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/objectStartArray.hpp
index 34d64a5c5d8..459cd9c8792 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/objectStartArray.hpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/objectStartArray.hpp
@@ -128,8 +128,6 @@ class ObjectStartArray : public CHeapObj {
// When doing MT offsets, we can't assert this.
//assert(offset > *block, "Found backwards allocation");
*block = (jbyte)offset;
-
- // tty->print_cr("[%p]", p);
}
// Optimized for finding the first object that crosses into
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
index 14be13a2660..10932e6b9e6 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
@@ -264,7 +264,7 @@ void StealRegionCompactionTask::do_it(GCTaskManager* manager, uint which) {
cm->set_region_stack(ParCompactionManager::region_list(which_stack_index));
if (TraceDynamicGCThreads) {
gclog_or_tty->print_cr("StealRegionCompactionTask::do_it "
- "region_stack_index %d region_stack = 0x%x "
+ "region_stack_index %d region_stack = " PTR_FORMAT " "
" empty (%d) use all workers %d",
which_stack_index, ParCompactionManager::region_list(which_stack_index),
cm->region_stack()->is_empty(),
@@ -366,7 +366,7 @@ void DrainStacksCompactionTask::do_it(GCTaskManager* manager, uint which) {
if (TraceDynamicGCThreads) {
void* old_region_stack = (void*) cm->region_stack();
int old_region_stack_index = cm->region_stack_index();
- gclog_or_tty->print_cr("Pushing region stack 0x%x/%d",
+ gclog_or_tty->print_cr("Pushing region stack " PTR_FORMAT "/%d",
old_region_stack, old_region_stack_index);
}
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psAdaptiveSizePolicy.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psAdaptiveSizePolicy.cpp
index 5b3dd89e7b3..f28b7458c6d 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psAdaptiveSizePolicy.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psAdaptiveSizePolicy.cpp
@@ -379,7 +379,7 @@ void PSAdaptiveSizePolicy::compute_eden_space_size(
gclog_or_tty->print_cr(
"PSAdaptiveSizePolicy::compute_eden_space_size: gc time limit"
" gc_cost: %f "
- " GCTimeLimit: %d",
+ " GCTimeLimit: " UINTX_FORMAT,
gc_cost(), GCTimeLimit);
}
}
@@ -586,7 +586,7 @@ void PSAdaptiveSizePolicy::compute_old_gen_free_space(
gclog_or_tty->print_cr(
"PSAdaptiveSizePolicy::compute_old_gen_free_space: gc time limit"
" gc_cost: %f "
- " GCTimeLimit: %d",
+ " GCTimeLimit: " UINTX_FORMAT,
gc_cost(), GCTimeLimit);
}
}
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp
index 8bdea558dbf..cdfc31911ee 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psMarkSweep.cpp
@@ -270,7 +270,8 @@ bool PSMarkSweep::invoke_no_policy(bool clear_all_softrefs) {
gclog_or_tty->print_cr(" collection: %d ",
heap->total_collections());
if (Verbose) {
- gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d",
+ gclog_or_tty->print("old_gen_capacity: " SIZE_FORMAT
+ " young_gen_capacity: " SIZE_FORMAT,
old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
}
}
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
index 5acc96d61be..e93f612e4bd 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
@@ -1428,7 +1428,7 @@ PSParallelCompact::compute_dense_prefix(const SpaceId id,
"space_cap=" SIZE_FORMAT,
space_live, space_used,
space_capacity);
- tty->print_cr("dead_wood_limiter(%6.4f, %d)=%6.4f "
+ tty->print_cr("dead_wood_limiter(%6.4f, " SIZE_FORMAT ")=%6.4f "
"dead_wood_max=" SIZE_FORMAT " dead_wood_limit=" SIZE_FORMAT,
density, min_percent_free, limiter,
dead_wood_max, dead_wood_limit);
@@ -2106,7 +2106,8 @@ bool PSParallelCompact::invoke_no_policy(bool maximum_heap_compaction) {
gclog_or_tty->print_cr(" collection: %d ",
heap->total_collections());
if (Verbose) {
- gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d",
+ gclog_or_tty->print("old_gen_capacity: " SIZE_FORMAT
+ " young_gen_capacity: " SIZE_FORMAT,
old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
}
}
@@ -2559,7 +2560,7 @@ void PSParallelCompact::enqueue_region_draining_tasks(GCTaskQueue* q,
if (TraceParallelOldGCCompactionPhase) {
if (Verbose && (fillable_regions & 7) != 0) gclog_or_tty->cr();
- gclog_or_tty->print_cr("%u initially fillable regions", fillable_regions);
+ gclog_or_tty->print_cr(SIZE_FORMAT " initially fillable regions", fillable_regions);
}
}
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp
index e8a88cb3518..01b404eac55 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psPromotionManager.cpp
@@ -330,7 +330,7 @@ oop PSPromotionManager::oop_promotion_failed(oop obj, markOop obj_mark) {
#ifndef PRODUCT
if (TraceScavenge) {
- gclog_or_tty->print_cr("{%s %s 0x%x (%d)}",
+ gclog_or_tty->print_cr("{%s %s " PTR_FORMAT " (%d)}",
"promotion-failure",
obj->klass()->internal_name(),
(void *)obj, obj->size());
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp
index a5d008ee11c..de18bd00d05 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.cpp
@@ -510,7 +510,8 @@ bool PSScavenge::invoke_no_policy() {
heap->total_collections());
if (Verbose) {
- gclog_or_tty->print("old_gen_capacity: %d young_gen_capacity: %d",
+ gclog_or_tty->print("old_gen_capacity: " SIZE_FORMAT
+ " young_gen_capacity: " SIZE_FORMAT,
old_gen->capacity_in_bytes(), young_gen->capacity_in_bytes());
}
}
@@ -728,7 +729,7 @@ void PSScavenge::clean_up_failed_promotion() {
young_gen->object_iterate(&unforward_closure);
if (PrintGC && Verbose) {
- gclog_or_tty->print_cr("Restoring %d marks", _preserved_oop_stack.size());
+ gclog_or_tty->print_cr("Restoring " SIZE_FORMAT " marks", _preserved_oop_stack.size());
}
// Restore any saved marks.
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.inline.hpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.inline.hpp
index 0835f4f1f84..3b8447988cb 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.inline.hpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psScavenge.inline.hpp
@@ -31,6 +31,7 @@
#include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
#include "gc_implementation/parallelScavenge/psScavenge.hpp"
#include "memory/iterator.hpp"
+#include "utilities/globalDefinitions.hpp"
inline void PSScavenge::save_to_space_top_before_gc() {
ParallelScavengeHeap* heap = (ParallelScavengeHeap*)Universe::heap();
@@ -178,7 +179,7 @@ class PSScavengeKlassClosure: public KlassClosure {
#ifndef PRODUCT
if (TraceScavenge) {
ResourceMark rm;
- gclog_or_tty->print_cr("PSScavengeKlassClosure::do_klass %p, %s, dirty: %s",
+ gclog_or_tty->print_cr("PSScavengeKlassClosure::do_klass " PTR_FORMAT ", %s, dirty: %s",
klass,
klass->external_name(),
klass->has_modified_oops() ? "true" : "false");
diff --git a/hotspot/src/share/vm/gc_implementation/shared/adaptiveSizePolicy.cpp b/hotspot/src/share/vm/gc_implementation/shared/adaptiveSizePolicy.cpp
index 8c9ca0a9fd9..dfce8b559be 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/adaptiveSizePolicy.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/adaptiveSizePolicy.cpp
@@ -168,9 +168,9 @@ int AdaptiveSizePolicy::calc_default_active_workers(uintx total_workers,
if (TraceDynamicGCThreads) {
gclog_or_tty->print_cr("GCTaskManager::calc_default_active_workers() : "
- "active_workers(): %d new_active_workers: %d "
- "prev_active_workers: %d\n"
- " active_workers_by_JT: %d active_workers_by_heap_size: %d",
+ "active_workers(): " UINTX_FORMAT " new_active_workers: " UINTX_FORMAT " "
+ "prev_active_workers: " UINTX_FORMAT "\n"
+ " active_workers_by_JT: " UINTX_FORMAT " active_workers_by_heap_size: " UINTX_FORMAT,
active_workers, new_active_workers, prev_active_workers,
active_workers_by_JT, active_workers_by_heap_size);
}
@@ -545,12 +545,12 @@ void AdaptiveSizePolicy::check_gc_overhead_limit(
if (UseGCOverheadLimit && PrintGCDetails && Verbose) {
if (gc_overhead_limit_exceeded()) {
gclog_or_tty->print_cr(" GC is exceeding overhead limit "
- "of %d%%", GCTimeLimit);
+ "of " UINTX_FORMAT "%%", GCTimeLimit);
reset_gc_overhead_limit_count();
} else if (print_gc_overhead_limit_would_be_exceeded) {
assert(gc_overhead_limit_count() > 0, "Should not be printing");
gclog_or_tty->print_cr(" GC would exceed overhead limit "
- "of %d%% %d consecutive time(s)",
+ "of " UINTX_FORMAT "%% %d consecutive time(s)",
GCTimeLimit, gc_overhead_limit_count());
}
}
diff --git a/hotspot/src/share/vm/gc_implementation/shared/allocationStats.hpp b/hotspot/src/share/vm/gc_implementation/shared/allocationStats.hpp
index 87ced750d35..d2282df167e 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/allocationStats.hpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/allocationStats.hpp
@@ -120,8 +120,9 @@ class AllocationStats VALUE_OBJ_CLASS_SPEC {
float delta_ise = (CMSExtrapolateSweep ? intra_sweep_estimate : 0.0);
_desired = (ssize_t)(new_rate * (inter_sweep_estimate + delta_ise));
if (PrintFLSStatistics > 1) {
- gclog_or_tty->print_cr("demand: %d, old_rate: %f, current_rate: %f, new_rate: %f, old_desired: %d, new_desired: %d",
- demand, old_rate, rate, new_rate, old_desired, _desired);
+ gclog_or_tty->print_cr("demand: " SSIZE_FORMAT ", old_rate: %f, current_rate: %f, "
+ "new_rate: %f, old_desired: " SSIZE_FORMAT ", new_desired: " SSIZE_FORMAT,
+ demand, old_rate, rate, new_rate, old_desired, _desired);
}
}
}
diff --git a/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.cpp b/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.cpp
index b0c6e95191a..8a105bfa3fb 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.cpp
@@ -37,21 +37,10 @@
int ConcurrentGCThread::_CGC_flag = CGC_nil;
-SuspendibleThreadSet ConcurrentGCThread::_sts;
-
ConcurrentGCThread::ConcurrentGCThread() :
_should_terminate(false), _has_terminated(false) {
- _sts.initialize();
};
-void ConcurrentGCThread::safepoint_synchronize() {
- _sts.suspend_all();
-}
-
-void ConcurrentGCThread::safepoint_desynchronize() {
- _sts.resume_all();
-}
-
void ConcurrentGCThread::create_and_start() {
if (os::create_thread(this, os::cgc_thread)) {
// XXX: need to set this to low priority
@@ -92,78 +81,6 @@ void ConcurrentGCThread::terminate() {
ThreadLocalStorage::set_thread(NULL);
}
-
-void SuspendibleThreadSet::initialize_work() {
- MutexLocker x(STS_init_lock);
- if (!_initialized) {
- _m = new Monitor(Mutex::leaf,
- "SuspendibleThreadSetLock", true);
- _async = 0;
- _async_stop = false;
- _async_stopped = 0;
- _initialized = true;
- }
-}
-
-void SuspendibleThreadSet::join() {
- initialize();
- MutexLockerEx x(_m, Mutex::_no_safepoint_check_flag);
- while (_async_stop) _m->wait(Mutex::_no_safepoint_check_flag);
- _async++;
- assert(_async > 0, "Huh.");
-}
-
-void SuspendibleThreadSet::leave() {
- assert(_initialized, "Must be initialized.");
- MutexLockerEx x(_m, Mutex::_no_safepoint_check_flag);
- _async--;
- assert(_async >= 0, "Huh.");
- if (_async_stop) _m->notify_all();
-}
-
-void SuspendibleThreadSet::yield(const char* id) {
- assert(_initialized, "Must be initialized.");
- if (_async_stop) {
- MutexLockerEx x(_m, Mutex::_no_safepoint_check_flag);
- if (_async_stop) {
- _async_stopped++;
- assert(_async_stopped > 0, "Huh.");
- if (_async_stopped == _async) {
- if (ConcGCYieldTimeout > 0) {
- double now = os::elapsedTime();
- guarantee((now - _suspend_all_start) * 1000.0 <
- (double)ConcGCYieldTimeout,
- "Long delay; whodunit?");
- }
- }
- _m->notify_all();
- while (_async_stop) _m->wait(Mutex::_no_safepoint_check_flag);
- _async_stopped--;
- assert(_async >= 0, "Huh");
- _m->notify_all();
- }
- }
-}
-
-void SuspendibleThreadSet::suspend_all() {
- initialize(); // If necessary.
- if (ConcGCYieldTimeout > 0) {
- _suspend_all_start = os::elapsedTime();
- }
- MutexLockerEx x(_m, Mutex::_no_safepoint_check_flag);
- assert(!_async_stop, "Only one at a time.");
- _async_stop = true;
- while (_async_stopped < _async) _m->wait(Mutex::_no_safepoint_check_flag);
-}
-
-void SuspendibleThreadSet::resume_all() {
- assert(_initialized, "Must be initialized.");
- MutexLockerEx x(_m, Mutex::_no_safepoint_check_flag);
- assert(_async_stopped == _async, "Huh.");
- _async_stop = false;
- _m->notify_all();
-}
-
static void _sltLoop(JavaThread* thread, TRAPS) {
SurrogateLockerThread* slt = (SurrogateLockerThread*)thread;
slt->loop();
@@ -283,30 +200,3 @@ void SurrogateLockerThread::loop() {
}
assert(!_monitor.owned_by_self(), "Should unlock before exit.");
}
-
-
-// ===== STS Access From Outside CGCT =====
-
-void ConcurrentGCThread::stsYield(const char* id) {
- assert( Thread::current()->is_ConcurrentGC_thread(),
- "only a conc GC thread can call this" );
- _sts.yield(id);
-}
-
-bool ConcurrentGCThread::stsShouldYield() {
- assert( Thread::current()->is_ConcurrentGC_thread(),
- "only a conc GC thread can call this" );
- return _sts.should_yield();
-}
-
-void ConcurrentGCThread::stsJoin() {
- assert( Thread::current()->is_ConcurrentGC_thread(),
- "only a conc GC thread can call this" );
- _sts.join();
-}
-
-void ConcurrentGCThread::stsLeave() {
- assert( Thread::current()->is_ConcurrentGC_thread(),
- "only a conc GC thread can call this" );
- _sts.leave();
-}
diff --git a/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.hpp b/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.hpp
index 4172a95cced..4b82ed629f0 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.hpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/concurrentGCThread.hpp
@@ -26,55 +26,8 @@
#define SHARE_VM_GC_IMPLEMENTATION_SHARED_CONCURRENTGCTHREAD_HPP
#include "utilities/macros.hpp"
-#if INCLUDE_ALL_GCS
+#include "gc_implementation/shared/suspendibleThreadSet.hpp"
#include "runtime/thread.hpp"
-#endif // INCLUDE_ALL_GCS
-
-class VoidClosure;
-
-// A SuspendibleThreadSet is (obviously) a set of threads that can be
-// suspended. A thread can join and later leave the set, and periodically
-// yield. If some thread (not in the set) requests, via suspend_all, that
-// the threads be suspended, then the requesting thread is blocked until
-// all the threads in the set have yielded or left the set. (Threads may
-// not enter the set when an attempted suspension is in progress.) The
-// suspending thread later calls resume_all, allowing the suspended threads
-// to continue.
-
-class SuspendibleThreadSet {
- Monitor* _m;
- int _async;
- bool _async_stop;
- int _async_stopped;
- bool _initialized;
- double _suspend_all_start;
-
- void initialize_work();
-
- public:
- SuspendibleThreadSet() : _initialized(false) {}
-
- // Add the current thread to the set. May block if a suspension
- // is in progress.
- void join();
- // Removes the current thread from the set.
- void leave();
- // Returns "true" iff an suspension is in progress.
- bool should_yield() { return _async_stop; }
- // Suspends the current thread if a suspension is in progress (for
- // the duration of the suspension.)
- void yield(const char* id);
- // Return when all threads in the set are suspended.
- void suspend_all();
- // Allow suspended threads to resume.
- void resume_all();
- // Redundant initializations okay.
- void initialize() {
- // Double-check dirty read idiom.
- if (!_initialized) initialize_work();
- }
-};
-
class ConcurrentGCThread: public NamedThread {
friend class VMStructs;
@@ -96,9 +49,6 @@ protected:
static int set_CGC_flag(int b) { return _CGC_flag |= b; }
static int reset_CGC_flag(int b) { return _CGC_flag &= ~b; }
- // All instances share this one set.
- static SuspendibleThreadSet _sts;
-
// Create and start the thread (setting it's priority high.)
void create_and_start();
@@ -121,25 +71,6 @@ public:
// Tester
bool is_ConcurrentGC_thread() const { return true; }
-
- static void safepoint_synchronize();
- static void safepoint_desynchronize();
-
- // All overridings should probably do _sts::yield, but we allow
- // overriding for distinguished debugging messages. Default is to do
- // nothing.
- virtual void yield() {}
-
- bool should_yield() { return _sts.should_yield(); }
-
- // they are prefixed by sts since there are already yield() and
- // should_yield() (non-static) methods in this class and it was an
- // easy way to differentiate them.
- static void stsYield(const char* id);
- static bool stsShouldYield();
- static void stsJoin();
- static void stsLeave();
-
};
// The SurrogateLockerThread is used by concurrent GC threads for
diff --git a/hotspot/src/share/vm/gc_implementation/shared/markSweep.cpp b/hotspot/src/share/vm/gc_implementation/shared/markSweep.cpp
index 67d8a5ac8ec..b4bc3f9aea5 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/markSweep.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/markSweep.cpp
@@ -131,7 +131,7 @@ void MarkSweep::restore_marks() {
assert(_preserved_oop_stack.size() == _preserved_mark_stack.size(),
"inconsistent preserved oop stacks");
if (PrintGC && Verbose) {
- gclog_or_tty->print_cr("Restoring %d marks",
+ gclog_or_tty->print_cr("Restoring " SIZE_FORMAT " marks",
_preserved_count + _preserved_oop_stack.size());
}
diff --git a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
index e198590ef4b..20a7a6aa789 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp
@@ -888,7 +888,9 @@ void MutableNUMASpace::print_on(outputStream* st) const {
for (int i = 0; i < lgrp_spaces()->length(); i++) {
lgrp_spaces()->at(i)->accumulate_statistics(page_size());
}
- st->print(" local/remote/unbiased/uncommitted: %dK/%dK/%dK/%dK, large/small pages: %d/%d\n",
+ st->print(" local/remote/unbiased/uncommitted: " SIZE_FORMAT "K/"
+ SIZE_FORMAT "K/" SIZE_FORMAT "K/" SIZE_FORMAT
+ "K, large/small pages: " SIZE_FORMAT "/" SIZE_FORMAT "\n",
ls->space_stats()->_local_space / K,
ls->space_stats()->_remote_space / K,
ls->space_stats()->_unbiased_space / K,
diff --git a/hotspot/src/share/vm/gc_implementation/shared/parGCAllocBuffer.cpp b/hotspot/src/share/vm/gc_implementation/shared/parGCAllocBuffer.cpp
index acea112174f..2198a86aff6 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/parGCAllocBuffer.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/parGCAllocBuffer.cpp
@@ -27,6 +27,7 @@
#include "memory/sharedHeap.hpp"
#include "oops/arrayOop.hpp"
#include "oops/oop.inline.hpp"
+#include "utilities/globalDefinitions.hpp"
ParGCAllocBuffer::ParGCAllocBuffer(size_t desired_plab_sz_) :
_word_sz(desired_plab_sz_), _bottom(NULL), _top(NULL),
@@ -112,7 +113,7 @@ void PLABStats::adjust_desired_plab_sz(uint no_of_gc_workers) {
}
_used = _allocated - _wasted - _unused;
size_t plab_sz = _used/(target_refills*no_of_gc_workers);
- if (PrintPLAB) gclog_or_tty->print(" (plab_sz = %d ", plab_sz);
+ if (PrintPLAB) gclog_or_tty->print(" (plab_sz = " SIZE_FORMAT " ", plab_sz);
// Take historical weighted average
_filter.sample(plab_sz);
// Clip from above and below, and align to object boundary
@@ -120,7 +121,7 @@ void PLABStats::adjust_desired_plab_sz(uint no_of_gc_workers) {
plab_sz = MIN2(max_size(), plab_sz);
plab_sz = align_object_size(plab_sz);
// Latch the result
- if (PrintPLAB) gclog_or_tty->print(" desired_plab_sz = %d) ", plab_sz);
+ if (PrintPLAB) gclog_or_tty->print(" desired_plab_sz = " SIZE_FORMAT ") ", plab_sz);
_desired_plab_sz = plab_sz;
// Now clear the accumulators for next round:
// note this needs to be fixed in the case where we
@@ -132,8 +133,9 @@ void PLABStats::adjust_desired_plab_sz(uint no_of_gc_workers) {
#ifndef PRODUCT
void ParGCAllocBuffer::print() {
- gclog_or_tty->print("parGCAllocBuffer: _bottom: %p _top: %p _end: %p _hard_end: %p"
- "_retained: %c _retained_filler: [%p,%p)\n",
+ gclog_or_tty->print("parGCAllocBuffer: _bottom: " PTR_FORMAT " _top: " PTR_FORMAT
+ " _end: " PTR_FORMAT " _hard_end: " PTR_FORMAT " _retained: %c"
+ " _retained_filler: [" PTR_FORMAT "," PTR_FORMAT ")\n",
_bottom, _top, _end, _hard_end,
"FT"[_retained], _retained_filler.start(), _retained_filler.end());
}
diff --git a/hotspot/src/share/vm/gc_implementation/shared/parGCAllocBuffer.hpp b/hotspot/src/share/vm/gc_implementation/shared/parGCAllocBuffer.hpp
index 2eecbed31fc..3677ee26e28 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/parGCAllocBuffer.hpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/parGCAllocBuffer.hpp
@@ -60,6 +60,7 @@ public:
// Initializes the buffer to be empty, but with the given "word_sz".
// Must get initialized with "set_buf" for an allocation to succeed.
ParGCAllocBuffer(size_t word_sz);
+ virtual ~ParGCAllocBuffer() {}
static const size_t min_size() {
return ThreadLocalAllocBuffer::min_size();
@@ -113,7 +114,7 @@ public:
}
// Sets the space of the buffer to be [buf, space+word_sz()).
- void set_buf(HeapWord* buf) {
+ virtual void set_buf(HeapWord* buf) {
_bottom = buf;
_top = _bottom;
_hard_end = _bottom + word_sz();
@@ -158,7 +159,7 @@ public:
// Fills in the unallocated portion of the buffer with a garbage object.
// If "end_of_gc" is TRUE, is after the last use in the GC. IF "retain"
// is true, attempt to re-use the unused portion in the next GC.
- void retire(bool end_of_gc, bool retain);
+ virtual void retire(bool end_of_gc, bool retain);
void print() PRODUCT_RETURN;
};
@@ -238,14 +239,14 @@ public:
void undo_allocation(HeapWord* obj, size_t word_sz);
- void set_buf(HeapWord* buf_start) {
+ virtual void set_buf(HeapWord* buf_start) {
ParGCAllocBuffer::set_buf(buf_start);
_true_end = _hard_end;
_bt.set_region(MemRegion(buf_start, word_sz()));
_bt.initialize_threshold();
}
- void retire(bool end_of_gc, bool retain);
+ virtual void retire(bool end_of_gc, bool retain);
MemRegion range() {
return MemRegion(_top, _true_end);
diff --git a/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.cpp b/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.cpp
index 2de5846ab1b..c2b42873a7c 100644
--- a/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.cpp
+++ b/hotspot/src/share/vm/gc_implementation/shared/spaceDecorator.cpp
@@ -84,7 +84,7 @@ void SpaceMangler::mangle_region(MemRegion mr) {
assert(ZapUnusedHeapArea, "Mangling should not be in use");
#ifdef ASSERT
if(TraceZapUnusedHeapArea) {
- gclog_or_tty->print("Mangling [0x%x to 0x%x)", mr.start(), mr.end());
+ gclog_or_tty->print("Mangling [" PTR_FORMAT " to " PTR_FORMAT ")", mr.start(), mr.end());
}
Copy::fill_to_words(mr.start(), mr.word_size(), badHeapWord);
if(TraceZapUnusedHeapArea) {
diff --git a/hotspot/src/share/vm/gc_implementation/shared/suspendibleThreadSet.cpp b/hotspot/src/share/vm/gc_implementation/shared/suspendibleThreadSet.cpp
new file mode 100644
index 00000000000..6bb719724c1
--- /dev/null
+++ b/hotspot/src/share/vm/gc_implementation/shared/suspendibleThreadSet.cpp
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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/suspendibleThreadSet.hpp"
+#include "runtime/mutexLocker.hpp"
+#include "runtime/thread.inline.hpp"
+
+uint SuspendibleThreadSet::_nthreads = 0;
+uint SuspendibleThreadSet::_nthreads_stopped = 0;
+bool SuspendibleThreadSet::_suspend_all = false;
+double SuspendibleThreadSet::_suspend_all_start = 0.0;
+
+void SuspendibleThreadSet::join() {
+ MonitorLockerEx ml(STS_lock, Mutex::_no_safepoint_check_flag);
+ while (_suspend_all) {
+ ml.wait(Mutex::_no_safepoint_check_flag);
+ }
+ _nthreads++;
+}
+
+void SuspendibleThreadSet::leave() {
+ MonitorLockerEx ml(STS_lock, Mutex::_no_safepoint_check_flag);
+ assert(_nthreads > 0, "Invalid");
+ _nthreads--;
+ if (_suspend_all) {
+ ml.notify_all();
+ }
+}
+
+void SuspendibleThreadSet::yield() {
+ if (_suspend_all) {
+ MonitorLockerEx ml(STS_lock, Mutex::_no_safepoint_check_flag);
+ if (_suspend_all) {
+ _nthreads_stopped++;
+ if (_nthreads_stopped == _nthreads) {
+ if (ConcGCYieldTimeout > 0) {
+ double now = os::elapsedTime();
+ guarantee((now - _suspend_all_start) * 1000.0 < (double)ConcGCYieldTimeout, "Long delay");
+ }
+ }
+ ml.notify_all();
+ while (_suspend_all) {
+ ml.wait(Mutex::_no_safepoint_check_flag);
+ }
+ assert(_nthreads_stopped > 0, "Invalid");
+ _nthreads_stopped--;
+ ml.notify_all();
+ }
+ }
+}
+
+void SuspendibleThreadSet::synchronize() {
+ assert(Thread::current()->is_VM_thread(), "Must be the VM thread");
+ if (ConcGCYieldTimeout > 0) {
+ _suspend_all_start = os::elapsedTime();
+ }
+ MonitorLockerEx ml(STS_lock, Mutex::_no_safepoint_check_flag);
+ assert(!_suspend_all, "Only one at a time");
+ _suspend_all = true;
+ while (_nthreads_stopped < _nthreads) {
+ ml.wait(Mutex::_no_safepoint_check_flag);
+ }
+}
+
+void SuspendibleThreadSet::desynchronize() {
+ assert(Thread::current()->is_VM_thread(), "Must be the VM thread");
+ MonitorLockerEx ml(STS_lock, Mutex::_no_safepoint_check_flag);
+ assert(_nthreads_stopped == _nthreads, "Invalid");
+ _suspend_all = false;
+ ml.notify_all();
+}
diff --git a/hotspot/src/share/vm/gc_implementation/shared/suspendibleThreadSet.hpp b/hotspot/src/share/vm/gc_implementation/shared/suspendibleThreadSet.hpp
new file mode 100644
index 00000000000..5d76ef2b99c
--- /dev/null
+++ b/hotspot/src/share/vm/gc_implementation/shared/suspendibleThreadSet.hpp
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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_GC_IMPLEMENTATION_SHARED_SUSPENDIBLETHREADSET_HPP
+#define SHARE_VM_GC_IMPLEMENTATION_SHARED_SUSPENDIBLETHREADSET_HPP
+
+#include "memory/allocation.hpp"
+
+// A SuspendibleThreadSet is a set of threads that can be suspended.
+// A thread can join and later leave the set, and periodically yield.
+// If some thread (not in the set) requests, via synchronize(), that
+// the threads be suspended, then the requesting thread is blocked
+// until all the threads in the set have yielded or left the set. Threads
+// may not enter the set when an attempted suspension is in progress. The
+// suspending thread later calls desynchronize(), allowing the suspended
+// threads to continue.
+class SuspendibleThreadSet : public AllStatic {
+private:
+ static uint _nthreads;
+ static uint _nthreads_stopped;
+ static bool _suspend_all;
+ static double _suspend_all_start;
+
+public:
+ // Add the current thread to the set. May block if a suspension is in progress.
+ static void join();
+
+ // Removes the current thread from the set.
+ static void leave();
+
+ // Returns true if an suspension is in progress.
+ static bool should_yield() { return _suspend_all; }
+
+ // Suspends the current thread if a suspension is in progress.
+ static void yield();
+
+ // Returns when all threads in the set are suspended.
+ static void synchronize();
+
+ // Resumes all suspended threads in the set.
+ static void desynchronize();
+};
+
+class SuspendibleThreadSetJoiner : public StackObj {
+public:
+ SuspendibleThreadSetJoiner() {
+ SuspendibleThreadSet::join();
+ }
+
+ ~SuspendibleThreadSetJoiner() {
+ SuspendibleThreadSet::leave();
+ }
+
+ bool should_yield() {
+ return SuspendibleThreadSet::should_yield();
+ }
+
+ void yield() {
+ SuspendibleThreadSet::yield();
+ }
+};
+
+#endif // SHARE_VM_GC_IMPLEMENTATION_SHARED_SUSPENDIBLETHREADSET_HPP
diff --git a/hotspot/src/share/vm/gc_interface/collectedHeap.hpp b/hotspot/src/share/vm/gc_interface/collectedHeap.hpp
index ecf50c9b2a9..d3c2fba9276 100644
--- a/hotspot/src/share/vm/gc_interface/collectedHeap.hpp
+++ b/hotspot/src/share/vm/gc_interface/collectedHeap.hpp
@@ -208,6 +208,9 @@ class CollectedHeap : public CHeapObj {
// This is the correct place to place such initialization methods.
virtual void post_initialize() = 0;
+ // Stop any onging concurrent work and prepare for exit.
+ virtual void stop() {}
+
MemRegion reserved_region() const { return _reserved; }
address base() const { return (address)reserved_region().start(); }
diff --git a/hotspot/src/share/vm/memory/binaryTreeDictionary.cpp b/hotspot/src/share/vm/memory/binaryTreeDictionary.cpp
index 8198c2f927c..e975324ad40 100644
--- a/hotspot/src/share/vm/memory/binaryTreeDictionary.cpp
+++ b/hotspot/src/share/vm/memory/binaryTreeDictionary.cpp
@@ -1205,13 +1205,13 @@ void BinaryTreeDictionary::report_statistics() const {
"------------------------------------\n");
size_t total_size = total_chunk_size(debug_only(NULL));
size_t free_blocks = num_free_blocks();
- gclog_or_tty->print("Total Free Space: %d\n", total_size);
- gclog_or_tty->print("Max Chunk Size: %d\n", max_chunk_size());
- gclog_or_tty->print("Number of Blocks: %d\n", free_blocks);
+ gclog_or_tty->print("Total Free Space: " SIZE_FORMAT "\n", total_size);
+ gclog_or_tty->print("Max Chunk Size: " SIZE_FORMAT "\n", max_chunk_size());
+ gclog_or_tty->print("Number of Blocks: " SIZE_FORMAT "\n", free_blocks);
if (free_blocks > 0) {
- gclog_or_tty->print("Av. Block Size: %d\n", total_size/free_blocks);
+ gclog_or_tty->print("Av. Block Size: " SIZE_FORMAT "\n", total_size/free_blocks);
}
- gclog_or_tty->print("Tree Height: %d\n", tree_height());
+ gclog_or_tty->print("Tree Height: " SIZE_FORMAT "\n", tree_height());
}
// Print census information - counts, births, deaths, etc.
diff --git a/hotspot/src/share/vm/memory/defNewGeneration.cpp b/hotspot/src/share/vm/memory/defNewGeneration.cpp
index b4cf451f10e..000be1f8bf3 100644
--- a/hotspot/src/share/vm/memory/defNewGeneration.cpp
+++ b/hotspot/src/share/vm/memory/defNewGeneration.cpp
@@ -44,6 +44,7 @@
#include "runtime/java.hpp"
#include "runtime/thread.inline.hpp"
#include "utilities/copy.hpp"
+#include "utilities/globalDefinitions.hpp"
#include "utilities/stack.inline.hpp"
//
@@ -131,7 +132,7 @@ void KlassScanClosure::do_klass(Klass* klass) {
#ifndef PRODUCT
if (TraceScavenge) {
ResourceMark rm;
- gclog_or_tty->print_cr("KlassScanClosure::do_klass %p, %s, dirty: %s",
+ gclog_or_tty->print_cr("KlassScanClosure::do_klass " PTR_FORMAT ", %s, dirty: %s",
klass,
klass->external_name(),
klass->has_modified_oops() ? "true" : "false");
@@ -511,7 +512,7 @@ void DefNewGeneration::space_iterate(SpaceClosure* blk,
HeapWord* DefNewGeneration::allocate_from_space(size_t size) {
HeapWord* result = NULL;
if (Verbose && PrintGCDetails) {
- gclog_or_tty->print("DefNewGeneration::allocate_from_space(%u):"
+ gclog_or_tty->print("DefNewGeneration::allocate_from_space(" SIZE_FORMAT "):"
" will_fail: %s"
" heap_lock: %s"
" free: " SIZE_FORMAT,
@@ -756,7 +757,7 @@ void DefNewGeneration::preserve_mark_if_necessary(oop obj, markOop m) {
void DefNewGeneration::handle_promotion_failure(oop old) {
if (PrintPromotionFailure && !_promotion_failed) {
- gclog_or_tty->print(" (promotion failure size = " SIZE_FORMAT ") ",
+ gclog_or_tty->print(" (promotion failure size = %d) ",
old->size());
}
_promotion_failed = true;
diff --git a/hotspot/src/share/vm/memory/generation.cpp b/hotspot/src/share/vm/memory/generation.cpp
index 11ba05fed8d..5d3ad791473 100644
--- a/hotspot/src/share/vm/memory/generation.cpp
+++ b/hotspot/src/share/vm/memory/generation.cpp
@@ -573,8 +573,8 @@ void CardGeneration::compute_new_size() {
maximum_desired_capacity / (double) K);
gclog_or_tty->print_cr(" "
" shrink_bytes: %.1fK"
- " current_shrink_factor: %d"
- " new shrink factor: %d"
+ " current_shrink_factor: " SIZE_FORMAT
+ " new shrink factor: " SIZE_FORMAT
" _min_heap_delta_bytes: %.1fK",
shrink_bytes / (double) K,
current_shrink_factor,
diff --git a/hotspot/src/share/vm/memory/sharedHeap.cpp b/hotspot/src/share/vm/memory/sharedHeap.cpp
index 9de74e25c7c..b59635c9f33 100644
--- a/hotspot/src/share/vm/memory/sharedHeap.cpp
+++ b/hotspot/src/share/vm/memory/sharedHeap.cpp
@@ -257,7 +257,7 @@ void SharedHeap::print_size_transition(outputStream* out,
size_t bytes_before,
size_t bytes_after,
size_t capacity) {
- out->print(" %d%s->%d%s(%d%s)",
+ out->print(" " SIZE_FORMAT "%s->" SIZE_FORMAT "%s(" SIZE_FORMAT "%s)",
byte_size_in_proper_unit(bytes_before),
proper_unit_for_byte_size(bytes_before),
byte_size_in_proper_unit(bytes_after),
diff --git a/hotspot/src/share/vm/oops/methodData.hpp b/hotspot/src/share/vm/oops/methodData.hpp
index b10f0052580..efd05cb5ade 100644
--- a/hotspot/src/share/vm/oops/methodData.hpp
+++ b/hotspot/src/share/vm/oops/methodData.hpp
@@ -1012,6 +1012,11 @@ public:
static ByteSize argument_type_offset(int i) {
return in_ByteSize(argument_type_local_offset(i) * DataLayout::cell_size);
}
+
+ static ByteSize return_only_size() {
+ return ReturnTypeEntry::size() + in_ByteSize(header_cell_count() * DataLayout::cell_size);
+ }
+
};
// CallTypeData
@@ -2143,7 +2148,6 @@ private:
static bool profile_jsr292(methodHandle m, int bci);
static int profile_arguments_flag();
- static bool profile_arguments_jsr292_only();
static bool profile_all_arguments();
static bool profile_arguments_for_invoke(methodHandle m, int bci);
static int profile_return_flag();
@@ -2442,6 +2446,7 @@ public:
static bool profile_parameters_for_method(methodHandle m);
static bool profile_arguments();
+ static bool profile_arguments_jsr292_only();
static bool profile_return();
static bool profile_parameters();
static bool profile_return_jsr292_only();
diff --git a/hotspot/src/share/vm/opto/superword.cpp b/hotspot/src/share/vm/opto/superword.cpp
index cd53a971bff..49a0dae9ece 100644
--- a/hotspot/src/share/vm/opto/superword.cpp
+++ b/hotspot/src/share/vm/opto/superword.cpp
@@ -1266,8 +1266,9 @@ void SuperWord::co_locate_pack(Node_List* pk) {
memops.clear();
for (DUIterator i = upper_insert_pt->outs(); upper_insert_pt->has_out(i); i++) {
Node* use = upper_insert_pt->out(i);
- if (!use->is_Store())
+ if (use->is_Mem() && !use->is_Store()) {
memops.push(use);
+ }
}
MemNode* lower_insert_pt = last;
diff --git a/hotspot/src/share/vm/runtime/globals.hpp b/hotspot/src/share/vm/runtime/globals.hpp
index 8dcc17edaf2..ae4cc4e2149 100644
--- a/hotspot/src/share/vm/runtime/globals.hpp
+++ b/hotspot/src/share/vm/runtime/globals.hpp
@@ -1931,6 +1931,10 @@ class CommandLineFlags {
"not just one of the generations (e.g., G1). A value of 0 " \
"denotes 'do constant GC cycles'.") \
\
+ manageable(intx, CMSTriggerInterval, -1, \
+ "Commence a CMS collection cycle (at least) every so many " \
+ "milliseconds (0 permanently, -1 disabled)") \
+ \
product(bool, UseCMSInitiatingOccupancyOnly, false, \
"Only use occupancy as a criterion for starting a CMS collection")\
\
diff --git a/hotspot/src/share/vm/runtime/java.cpp b/hotspot/src/share/vm/runtime/java.cpp
index 231f3fe7249..cddfd3d1ffc 100644
--- a/hotspot/src/share/vm/runtime/java.cpp
+++ b/hotspot/src/share/vm/runtime/java.cpp
@@ -499,6 +499,9 @@ void before_exit(JavaThread * thread) {
os::infinite_sleep();
}
+ // Stop any ongoing concurrent GC work
+ Universe::heap()->stop();
+
// Terminate watcher thread - must before disenrolling any periodic task
if (PeriodicTask::num_tasks() > 0)
WatcherThread::stop();
diff --git a/hotspot/src/share/vm/runtime/mutexLocker.cpp b/hotspot/src/share/vm/runtime/mutexLocker.cpp
index a798bd8d5b4..136bc4d28fe 100644
--- a/hotspot/src/share/vm/runtime/mutexLocker.cpp
+++ b/hotspot/src/share/vm/runtime/mutexLocker.cpp
@@ -69,7 +69,7 @@ Monitor* Safepoint_lock = NULL;
Monitor* SerializePage_lock = NULL;
Monitor* Threads_lock = NULL;
Monitor* CGC_lock = NULL;
-Mutex* STS_init_lock = NULL;
+Monitor* STS_lock = NULL;
Monitor* SLT_lock = NULL;
Monitor* iCMS_lock = NULL;
Monitor* FullGCCount_lock = NULL;
@@ -173,7 +173,7 @@ void mutex_init() {
def(tty_lock , Mutex , event, true ); // allow to lock in VM
def(CGC_lock , Monitor, special, true ); // coordinate between fore- and background GC
- def(STS_init_lock , Mutex, leaf, true );
+ def(STS_lock , Monitor, leaf, true );
if (UseConcMarkSweepGC) {
def(iCMS_lock , Monitor, special, true ); // CMS incremental mode start/stop notification
}
diff --git a/hotspot/src/share/vm/runtime/mutexLocker.hpp b/hotspot/src/share/vm/runtime/mutexLocker.hpp
index 9ee61bff653..611083f4ba2 100644
--- a/hotspot/src/share/vm/runtime/mutexLocker.hpp
+++ b/hotspot/src/share/vm/runtime/mutexLocker.hpp
@@ -79,7 +79,7 @@ extern Monitor* Threads_lock; // a lock on the Threads table
// (also used by Safepoints too to block threads creation/destruction)
extern Monitor* CGC_lock; // used for coordination between
// fore- & background GC threads.
-extern Mutex* STS_init_lock; // coordinate initialization of SuspendibleThreadSets.
+extern Monitor* STS_lock; // used for joining/leaving SuspendibleThreadSet.
extern Monitor* SLT_lock; // used in CMS GC for acquiring PLL
extern Monitor* iCMS_lock; // CMS incremental mode start/stop notification
extern Monitor* FullGCCount_lock; // in support of "concurrent" full gc
diff --git a/hotspot/src/share/vm/runtime/safepoint.cpp b/hotspot/src/share/vm/runtime/safepoint.cpp
index cc335d0d83f..7e7f36788f1 100644
--- a/hotspot/src/share/vm/runtime/safepoint.cpp
+++ b/hotspot/src/share/vm/runtime/safepoint.cpp
@@ -75,7 +75,7 @@
#endif
#if INCLUDE_ALL_GCS
#include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
-#include "gc_implementation/shared/concurrentGCThread.hpp"
+#include "gc_implementation/shared/suspendibleThreadSet.hpp"
#endif // INCLUDE_ALL_GCS
#ifdef COMPILER1
#include "c1/c1_globals.hpp"
@@ -110,7 +110,7 @@ void SafepointSynchronize::begin() {
// more-general mechanism below. DLD (01/05).
ConcurrentMarkSweepThread::synchronize(false);
} else if (UseG1GC) {
- ConcurrentGCThread::safepoint_synchronize();
+ SuspendibleThreadSet::synchronize();
}
#endif // INCLUDE_ALL_GCS
@@ -486,7 +486,7 @@ void SafepointSynchronize::end() {
if (UseConcMarkSweepGC) {
ConcurrentMarkSweepThread::desynchronize(false);
} else if (UseG1GC) {
- ConcurrentGCThread::safepoint_desynchronize();
+ SuspendibleThreadSet::desynchronize();
}
#endif // INCLUDE_ALL_GCS
// record this time so VMThread can keep track how much time has elapsed
diff --git a/hotspot/src/share/vm/utilities/globalDefinitions.hpp b/hotspot/src/share/vm/utilities/globalDefinitions.hpp
index df2a8a30253..ca9bc2f16a6 100644
--- a/hotspot/src/share/vm/utilities/globalDefinitions.hpp
+++ b/hotspot/src/share/vm/utilities/globalDefinitions.hpp
@@ -1324,10 +1324,12 @@ inline int build_int_from_shorts( jushort low, jushort high ) {
#define PTR_FORMAT "0x%08" PRIxPTR
#endif // _LP64
-#define SSIZE_FORMAT "%" PRIdPTR
-#define SIZE_FORMAT "%" PRIuPTR
-#define SSIZE_FORMAT_W(width) "%" #width PRIdPTR
-#define SIZE_FORMAT_W(width) "%" #width PRIuPTR
+#define SSIZE_FORMAT "%" PRIdPTR
+#define SIZE_FORMAT "%" PRIuPTR
+#define SIZE_FORMAT_HEX "0x%" PRIxPTR
+#define SSIZE_FORMAT_W(width) "%" #width PRIdPTR
+#define SIZE_FORMAT_W(width) "%" #width PRIuPTR
+#define SIZE_FORMAT_HEX_W(width) "0x%" #width PRIxPTR
#define INTX_FORMAT "%" PRIdPTR
#define UINTX_FORMAT "%" PRIuPTR
diff --git a/hotspot/test/TEST.groups b/hotspot/test/TEST.groups
index 4fe50e2f146..1053faa7f16 100644
--- a/hotspot/test/TEST.groups
+++ b/hotspot/test/TEST.groups
@@ -1,5 +1,5 @@
#
-# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -127,10 +127,12 @@ needs_compact3 = \
gc/6581734/Test6581734.java \
gc/7072527/TestFullGCCount.java \
gc/g1/TestHumongousAllocInitialMark.java \
+ gc/g1/TestHumongousShrinkHeap.java \
gc/arguments/TestG1HeapRegionSize.java \
gc/metaspace/TestMetaspaceMemoryPool.java \
gc/arguments/TestDynMinHeapFreeRatio.java \
gc/arguments/TestDynMaxHeapFreeRatio.java \
+ gc/parallelScavenge/TestDynShrinkHeap.java \
runtime/InternalApi/ThreadCpuTimesDeadlock.java \
serviceability/threads/TestFalseDeadLock.java \
compiler/tiered/NonTieredLevelsTest.java \
diff --git a/hotspot/test/gc/g1/TestGCLogMessages.java b/hotspot/test/gc/g1/TestGCLogMessages.java
index 06ce2ca6d2d..0d5ba41fac9 100644
--- a/hotspot/test/gc/g1/TestGCLogMessages.java
+++ b/hotspot/test/gc/g1/TestGCLogMessages.java
@@ -23,7 +23,7 @@
/*
* @test TestPrintGCDetails
- * @bug 8035406 8027295 8035398
+ * @bug 8035406 8027295 8035398 8019342
* @summary Ensure that the PrintGCDetails output for a minor GC with G1
* includes the expected necessary messages.
* @key gc
@@ -48,6 +48,8 @@ public class TestGCLogMessages {
OutputAnalyzer output = new OutputAnalyzer(pb.start());
output.shouldNotContain("[Redirty Cards");
+ output.shouldNotContain("[Parallel Redirty");
+ output.shouldNotContain("[Redirtied Cards");
output.shouldNotContain("[Code Root Purge");
output.shouldNotContain("[String Dedup Fixup");
output.shouldNotContain("[Young Free CSet");
@@ -63,6 +65,8 @@ public class TestGCLogMessages {
output = new OutputAnalyzer(pb.start());
output.shouldContain("[Redirty Cards");
+ output.shouldNotContain("[Parallel Redirty");
+ output.shouldNotContain("[Redirtied Cards");
output.shouldContain("[Code Root Purge");
output.shouldContain("[String Dedup Fixup");
output.shouldNotContain("[Young Free CSet");
@@ -80,6 +84,8 @@ public class TestGCLogMessages {
output = new OutputAnalyzer(pb.start());
output.shouldContain("[Redirty Cards");
+ output.shouldContain("[Parallel Redirty");
+ output.shouldContain("[Redirtied Cards");
output.shouldContain("[Code Root Purge");
output.shouldContain("[String Dedup Fixup");
output.shouldContain("[Young Free CSet");
diff --git a/hotspot/test/gc/g1/TestHumongousShrinkHeap.java b/hotspot/test/gc/g1/TestHumongousShrinkHeap.java
new file mode 100644
index 00000000000..c790c6464bd
--- /dev/null
+++ b/hotspot/test/gc/g1/TestHumongousShrinkHeap.java
@@ -0,0 +1,131 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test TestHumongousShrinkHeap
+ * @bug 8036025
+ * @summary Verify that heap shrinks after GC in the presence of fragmentation due to humongous objects
+ * @library /testlibrary
+ * @run main/othervm -XX:MinHeapFreeRatio=10 -XX:MaxHeapFreeRatio=50 -XX:+UseG1GC -XX:G1HeapRegionSize=1M -verbose:gc TestHumongousShrinkHeap
+ */
+
+import java.lang.management.ManagementFactory;
+import java.lang.management.MemoryUsage;
+import java.util.ArrayList;
+import java.util.List;
+import sun.management.ManagementFactoryHelper;
+import static com.oracle.java.testlibrary.Asserts.*;
+
+public class TestHumongousShrinkHeap {
+
+ public static final String MIN_FREE_RATIO_FLAG_NAME = "MinHeapFreeRatio";
+ public static final String MAX_FREE_RATIO_FLAG_NAME = "MaxHeapFreeRatio";
+
+ private static final ArrayList> garbage = new ArrayList<>();
+ private static final int PAGE_SIZE = 1024 * 1024; // 1M
+ private static final int PAGES_NUM = 5;
+
+
+ public static void main(String[] args) {
+ new TestHumongousShrinkHeap().test();
+ }
+
+ private final void test() {
+ System.gc();
+ MemoryUsagePrinter.printMemoryUsage("init");
+
+ eat();
+ MemoryUsagePrinter.printMemoryUsage("eaten");
+ MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
+
+ free();
+ MemoryUsagePrinter.printMemoryUsage("free");
+ MemoryUsage muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
+
+ assertLessThan(muFree.getCommitted(), muFull.getCommitted(), String.format(
+ "committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+ + "%s = %s%n%s = %s",
+ MIN_FREE_RATIO_FLAG_NAME,
+ ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
+ MAX_FREE_RATIO_FLAG_NAME,
+ ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
+ ));
+ }
+
+ private void eat() {
+ int HumongousObjectSize = Math.round(.9f * PAGE_SIZE);
+ System.out.println("Will allocate objects of size=" +
+ MemoryUsagePrinter.humanReadableByteCount(HumongousObjectSize, true));
+
+ for (int i = 0; i < PAGES_NUM; i++) {
+ ArrayList stuff = new ArrayList<>();
+ eatList(stuff, 100, HumongousObjectSize);
+ MemoryUsagePrinter.printMemoryUsage("eat #" + i);
+ garbage.add(stuff);
+ }
+ }
+
+ private void free() {
+ // do not free last one list
+ garbage.subList(0, garbage.size() - 1).clear();
+
+ // do not free last one element from last list
+ ArrayList stuff = garbage.get(garbage.size() - 1);
+ stuff.subList(0, stuff.size() - 1).clear();
+ System.gc();
+ }
+
+ private static void eatList(List garbage, int count, int size) {
+ for (int i = 0; i < count; i++) {
+ garbage.add(new byte[size]);
+ }
+ }
+}
+
+/**
+ * Prints memory usage to standard output
+ */
+class MemoryUsagePrinter {
+
+ public static String humanReadableByteCount(long bytes, boolean si) {
+ int unit = si ? 1000 : 1024;
+ if (bytes < unit) {
+ return bytes + " B";
+ }
+ int exp = (int) (Math.log(bytes) / Math.log(unit));
+ String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
+ return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
+ }
+
+ public static void printMemoryUsage(String label) {
+ MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
+ float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
+ System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
+ label,
+ humanReadableByteCount(memusage.getInit(), true),
+ humanReadableByteCount(memusage.getUsed(), true),
+ humanReadableByteCount(memusage.getCommitted(), true),
+ freeratio * 100
+ );
+ }
+}
diff --git a/hotspot/test/gc/parallelScavenge/TestDynShrinkHeap.java b/hotspot/test/gc/parallelScavenge/TestDynShrinkHeap.java
new file mode 100644
index 00000000000..14755075d3b
--- /dev/null
+++ b/hotspot/test/gc/parallelScavenge/TestDynShrinkHeap.java
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test TestDynShrinkHeap
+ * @bug 8016479
+ * @summary Verify that the heap shrinks after full GC according to the current values of the Min/MaxHeapFreeRatio flags
+ * @library /testlibrary
+ * @run main/othervm -XX:+UseAdaptiveSizePolicyWithSystemGC -XX:+UseParallelGC -XX:MinHeapFreeRatio=0 -XX:MaxHeapFreeRatio=100 -verbose:gc TestDynShrinkHeap
+ */
+
+import com.oracle.java.testlibrary.TestDynamicVMOption;
+import java.lang.management.ManagementFactory;
+import java.lang.management.MemoryUsage;
+import java.util.ArrayList;
+import sun.management.ManagementFactoryHelper;
+import static com.oracle.java.testlibrary.Asserts.*;
+
+public class TestDynShrinkHeap {
+
+ public static final String MIN_FREE_RATIO_FLAG_NAME = "MinHeapFreeRatio";
+ public static final String MAX_FREE_RATIO_FLAG_NAME = "MaxHeapFreeRatio";
+
+ private static ArrayList list = new ArrayList<>(0);
+ private static final int M = 1024 * 1024; // to make heap more manageable by test code
+
+ private final TestDynamicVMOption maxRatioOption;
+ private final TestDynamicVMOption minRatioOption;
+
+ public TestDynShrinkHeap() {
+ minRatioOption = new TestDynamicVMOption(MIN_FREE_RATIO_FLAG_NAME);
+ maxRatioOption = new TestDynamicVMOption(MAX_FREE_RATIO_FLAG_NAME);
+ }
+
+ private final void test() {
+ System.gc();
+ MemoryUsagePrinter.printMemoryUsage("init");
+
+ eat();
+ MemoryUsagePrinter.printMemoryUsage("eaten");
+ MemoryUsage muFull = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
+
+ free();
+ MemoryUsagePrinter.printMemoryUsage("free");
+ MemoryUsage muFree = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
+
+ assertLessThan(muFree.getCommitted(), muFull.getCommitted(), String.format(
+ "committed free heap size is not less than committed full heap size, heap hasn't been shrunk?%n"
+ + "%s = %s%n%s = %s",
+ MIN_FREE_RATIO_FLAG_NAME,
+ ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MIN_FREE_RATIO_FLAG_NAME).getValue(),
+ MAX_FREE_RATIO_FLAG_NAME,
+ ManagementFactoryHelper.getDiagnosticMXBean().getVMOption(MAX_FREE_RATIO_FLAG_NAME).getValue()
+ ));
+ }
+
+ private void eat() {
+ for (int i = 0; i < M; i++) {
+ list.add(new byte[1024]);
+ }
+ MemoryUsagePrinter.printMemoryUsage("allocated " + M + " arrays");
+
+ list.subList(0, M / 2).clear();
+ System.gc();
+ MemoryUsagePrinter.printMemoryUsage("array halved");
+ }
+
+ private void free() {
+ maxRatioOption.setIntValue(minRatioOption.getIntValue() + 1);
+ System.gc();
+ MemoryUsagePrinter.printMemoryUsage("under pressure");
+ }
+
+ public static void main(String[] args) {
+ new TestDynShrinkHeap().test();
+ }
+}
+
+/**
+ * Prints memory usage to standard output
+ */
+class MemoryUsagePrinter {
+
+ public static String humanReadableByteCount(long bytes, boolean si) {
+ int unit = si ? 1000 : 1024;
+ if (bytes < unit) {
+ return bytes + " B";
+ }
+ int exp = (int) (Math.log(bytes) / Math.log(unit));
+ String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
+ return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
+ }
+
+ public static void printMemoryUsage(String label) {
+ MemoryUsage memusage = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage();
+ float freeratio = 1f - (float) memusage.getUsed() / memusage.getCommitted();
+ System.out.format("[%-24s] init: %-7s, used: %-7s, comm: %-7s, freeRatio ~= %.1f%%%n",
+ label,
+ humanReadableByteCount(memusage.getInit(), true),
+ humanReadableByteCount(memusage.getUsed(), true),
+ humanReadableByteCount(memusage.getCommitted(), true),
+ freeratio * 100
+ );
+ }
+}
diff --git a/jaxp/.hgtags b/jaxp/.hgtags
index e7dc2ecc96a..4ec338b9d0d 100644
--- a/jaxp/.hgtags
+++ b/jaxp/.hgtags
@@ -250,3 +250,6 @@ fb92ed0399424193f444489ad49a16748816dc12 jdk9-b03
b92a20e303d24c74078888cd7084b14d7626d48f jdk9-b05
46e4951b2a267e98341613a3b796f2c7554eb831 jdk9-b06
389f4094fd603c17e215997b0b40171179629007 jdk9-b07
+3b360a77658e6b3ac150dd7cdbff1a7abe855afc jdk9-b08
+f93a792fe37279d4d37aea86a99f3abbdc6fe79b jdk9-b09
+4ce98701efe3b28f6ce3ab23385445731e968af7 jdk9-b10
diff --git a/jaxp/make/BuildJaxp.gmk b/jaxp/make/BuildJaxp.gmk
index 57c184bc4ee..4efd49f4921 100644
--- a/jaxp/make/BuildJaxp.gmk
+++ b/jaxp/make/BuildJaxp.gmk
@@ -35,15 +35,15 @@ DISABLE_JAXP_WARNINGS := -Xlint:all,-deprecation,-unchecked,-rawtypes,-cast,-ser
# The generate new bytecode uses the new compiler for to generate bytecode
# for the new jdk that is being built. The code compiled by this setup
# cannot necessarily be run with the boot jdk.
-$(eval $(call SetupJavaCompiler,GENERATE_NEWBYTECODE_DEBUG, \
+$(eval $(call SetupJavaCompiler,GENERATE_NEWBYTECODE, \
JVM := $(JAVA), \
JAVAC := $(NEW_JAVAC), \
- FLAGS := -XDignore.symbol.file=true $(DISABLE_JAXP_WARNINGS) -g, \
+ FLAGS := -XDignore.symbol.file=true $(DISABLE_JAXP_WARNINGS), \
SERVER_DIR := $(SJAVAC_SERVER_DIR), \
SERVER_JVM := $(SJAVAC_SERVER_JAVA)))
$(eval $(call SetupJavaCompilation,BUILD_JAXP, \
- SETUP := GENERATE_NEWBYTECODE_DEBUG, \
+ SETUP := GENERATE_NEWBYTECODE, \
SRC := $(JAXP_TOPDIR)/src, \
CLEAN := .properties, \
BIN := $(JAXP_OUTPUTDIR)/classes, \
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/utils/SecuritySupport.java b/jaxp/src/com/sun/org/apache/xalan/internal/utils/SecuritySupport.java
index 0c2d2b1c9ba..e581f9a5b40 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/utils/SecuritySupport.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/utils/SecuritySupport.java
@@ -57,7 +57,7 @@ public final class SecuritySupport {
return securitySupport;
}
- static ClassLoader getContextClassLoader() {
+ public static ClassLoader getContextClassLoader() {
return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
ClassLoader cl = null;
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/ElementSchemePointer.java b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/ElementSchemePointer.java
index 5415c98e6a4..e33612e4a0d 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/ElementSchemePointer.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/ElementSchemePointer.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -19,7 +20,7 @@
*/
package com.sun.org.apache.xerces.internal.xpointer;
-import java.util.Hashtable;
+import java.util.HashMap;
import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
import com.sun.org.apache.xerces.internal.util.SymbolTable;
@@ -38,9 +39,8 @@ import com.sun.org.apache.xerces.internal.xni.parser.XMLErrorHandler;
* @xerces.internal
*
* @version $Id: ElementSchemePointer.java,v 1.4 2009/06/11 23:51:50 joehw Exp $
- *
*/
-class ElementSchemePointer implements XPointerPart {
+final class ElementSchemePointer implements XPointerPart {
// Fields
@@ -346,15 +346,17 @@ class ElementSchemePointer implements XPointerPart {
// Donot check for empty elements if the empty element is
// a child of a found parent element
- //if (!fIsElementFound) {
- if (checkMatch()) {
- fIsElementFound = true;
+ if (checkMatch()) {
+ if (!fIsElementFound) {
fWasOnlyEmptyElementFound = true;
} else {
- fIsElementFound = false;
+ fWasOnlyEmptyElementFound = false;
}
- //}
-
+ fIsElementFound = true;
+ } else {
+ fIsElementFound = false;
+ fWasOnlyEmptyElementFound = false;
+ }
}
}
@@ -526,7 +528,7 @@ class ElementSchemePointer implements XPointerPart {
private SymbolTable fSymbolTable;
- private Hashtable fTokenNames = new Hashtable();
+ private HashMap fTokenNames = new HashMap<>();
/**
* Constructor
@@ -548,16 +550,7 @@ class ElementSchemePointer implements XPointerPart {
* @return String The token string
*/
private String getTokenString(int token) {
- return (String) fTokenNames.get(new Integer(token));
- }
-
- /**
- * Returns the token String
- * @param token The index of the token
- * @return String The token string
- */
- private Integer getToken(int token) {
- return (Integer) fTokenNames.get(new Integer(token));
+ return fTokenNames.get(new Integer(token));
}
/**
@@ -566,12 +559,11 @@ class ElementSchemePointer implements XPointerPart {
* @param token The token string
*/
private void addToken(String tokenStr) {
- Integer tokenInt = (Integer) fTokenNames.get(tokenStr);
- if (tokenInt == null) {
- tokenInt = new Integer(fTokenNames.size());
+ if (!fTokenNames.containsValue(tokenStr)) {
+ Integer tokenInt = new Integer(fTokenNames.size());
fTokenNames.put(tokenInt, tokenStr);
+ addToken(tokenInt.intValue());
}
- addToken(tokenInt.intValue());
}
/**
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/ShortHandPointer.java b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/ShortHandPointer.java
index 1317deb7415..c068917e2d0 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/ShortHandPointer.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/ShortHandPointer.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -17,6 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package com.sun.org.apache.xerces.internal.xpointer;
import com.sun.org.apache.xerces.internal.impl.Constants;
@@ -37,9 +39,8 @@ import com.sun.org.apache.xerces.internal.xs.XSTypeDefinition;
* in document order that has a matching NCName as an identifier.
*
*
- *
*/
-class ShortHandPointer implements XPointerPart {
+final class ShortHandPointer implements XPointerPart {
// The name of the ShortHand pointer
private String fShortHandPointer;
@@ -261,7 +262,7 @@ class ShortHandPointer implements XPointerPart {
* @see com.sun.org.apache.xerces.internal.xpointer.XPointerPart#isChildFragmentResolved()
*/
public boolean isChildFragmentResolved() {
- return fIsFragmentResolved & ( fMatchingChildCount > 0);
+ return fIsFragmentResolved && ( fMatchingChildCount > 0);
}
/**
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerErrorHandler.java b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerErrorHandler.java
index e1a971f98b7..7d02f30e0fa 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerErrorHandler.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerErrorHandler.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -17,6 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package com.sun.org.apache.xerces.internal.xpointer;
import java.io.PrintWriter;
@@ -31,7 +33,7 @@ import com.sun.org.apache.xerces.internal.xni.parser.XMLParseException;
* implementation and reported as resource errors.
*
*/
-class XPointerErrorHandler implements XMLErrorHandler {
+final class XPointerErrorHandler implements XMLErrorHandler {
//
// Data
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerHandler.java b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerHandler.java
index 30b75630b54..5d4c905a3b8 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerHandler.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerHandler.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -17,10 +18,11 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package com.sun.org.apache.xerces.internal.xpointer;
-import java.util.Hashtable;
-import java.util.Vector;
+import java.util.ArrayList;
+import java.util.HashMap;
import com.sun.org.apache.xerces.internal.impl.Constants;
import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
@@ -32,6 +34,7 @@ import com.sun.org.apache.xerces.internal.xinclude.XIncludeNamespaceSupport;
import com.sun.org.apache.xerces.internal.xni.Augmentations;
import com.sun.org.apache.xerces.internal.xni.QName;
import com.sun.org.apache.xerces.internal.xni.XMLAttributes;
+import com.sun.org.apache.xerces.internal.xni.XMLDocumentHandler;
import com.sun.org.apache.xerces.internal.xni.XMLString;
import com.sun.org.apache.xerces.internal.xni.XNIException;
import com.sun.org.apache.xerces.internal.xni.parser.XMLConfigurationException;
@@ -64,8 +67,8 @@ public final class XPointerHandler extends XIncludeHandler implements
XPointerProcessor {
// Fields
- // A Vector of XPointerParts
- protected Vector fXPointerParts = null;
+ // An ArrayList of XPointerParts
+ protected ArrayList fXPointerParts = null;
// The current XPointerPart
protected XPointerPart fXPointerPart = null;
@@ -102,7 +105,7 @@ public final class XPointerHandler extends XIncludeHandler implements
public XPointerHandler() {
super();
- fXPointerParts = new Vector();
+ fXPointerParts = new ArrayList<>();
fSymbolTable = new SymbolTable();
}
@@ -110,13 +113,17 @@ public final class XPointerHandler extends XIncludeHandler implements
XMLErrorHandler errorHandler, XMLErrorReporter errorReporter) {
super();
- fXPointerParts = new Vector();
+ fXPointerParts = new ArrayList<>();
fSymbolTable = symbolTable;
fErrorHandler = errorHandler;
fXPointerErrorReporter = errorReporter;
//fErrorReporter = errorReporter; // The XInclude ErrorReporter
}
+ public void setDocumentHandler(XMLDocumentHandler handler) {
+ fDocumentHandler = handler;
+ }
+
// ************************************************************************
// Implementation of the XPointerProcessor interface.
// ************************************************************************
@@ -300,7 +307,7 @@ public final class XPointerHandler extends XIncludeHandler implements
// in the XPointer expression until a matching element is found.
for (int i = 0; i < fXPointerParts.size(); i++) {
- fXPointerPart = (XPointerPart) fXPointerParts.get(i);
+ fXPointerPart = fXPointerParts.get(i);
if (fXPointerPart.resolveXPointer(element, attributes, augs,
event)) {
@@ -430,11 +437,11 @@ public final class XPointerHandler extends XIncludeHandler implements
}
/**
- * Returns a Vector of XPointerPart objects
+ * Returns an ArrayList of XPointerPart objects
*
- * @return A Vector of XPointerPart objects.
+ * @return An ArrayList of XPointerPart objects.
*/
- public Vector getPointerParts() {
+ public ArrayList getPointerParts() {
return fXPointerParts;
}
@@ -480,7 +487,7 @@ public final class XPointerHandler extends XIncludeHandler implements
private SymbolTable fSymbolTable;
- private Hashtable fTokenNames = new Hashtable();
+ private HashMap fTokenNames = new HashMap<>();
/**
* Constructor
@@ -508,7 +515,7 @@ public final class XPointerHandler extends XIncludeHandler implements
* @return String The token string
*/
private String getTokenString(int token) {
- return (String) fTokenNames.get(new Integer(token));
+ return fTokenNames.get(new Integer(token));
}
/**
@@ -517,12 +524,11 @@ public final class XPointerHandler extends XIncludeHandler implements
* @param token The token string
*/
private void addToken(String tokenStr) {
- Integer tokenInt = (Integer) fTokenNames.get(tokenStr);
- if (tokenInt == null) {
- tokenInt = new Integer(fTokenNames.size());
+ if (!fTokenNames.containsValue(tokenStr)) {
+ Integer tokenInt = new Integer(fTokenNames.size());
fTokenNames.put(tokenInt, tokenStr);
+ addToken(tokenInt.intValue());
}
- addToken(tokenInt.intValue());
}
/**
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerMessageFormatter.java b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerMessageFormatter.java
index 639bdef7784..36ee4811039 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerMessageFormatter.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerMessageFormatter.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -17,6 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package com.sun.org.apache.xerces.internal.xpointer;
import java.util.Locale;
@@ -34,7 +36,7 @@ import com.sun.org.apache.xerces.internal.utils.SecuritySupport;
*
* @version $Id: XPointerMessageFormatter.java,v 1.5 2010-11-01 04:40:26 joehw Exp $
*/
-class XPointerMessageFormatter implements MessageFormatter {
+final class XPointerMessageFormatter implements MessageFormatter {
public static final String XPOINTER_DOMAIN = "http://www.w3.org/TR/XPTR";
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerPart.java b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerPart.java
index 667facef7fd..d5ee0617efe 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerPart.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerPart.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -17,6 +18,7 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
+
package com.sun.org.apache.xerces.internal.xpointer;
import com.sun.org.apache.xerces.internal.xni.Augmentations;
@@ -49,7 +51,7 @@ public interface XPointerPart {
* Provides scheme specific parsing of a XPointer expression i.e.
* the PointerPart or ShortHandPointer.
*
- * @param xpointer A String representing the PointerPart or ShortHandPointer.
+ * @param part A String representing the PointerPart or ShortHandPointer.
* @throws XNIException Thrown if the PointerPart string does not conform to
* the syntax defined by its scheme.
*
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerProcessor.java b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerProcessor.java
index c6e746e365a..8457fd5fd0e 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerProcessor.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/xpointer/XPointerProcessor.java
@@ -3,11 +3,12 @@
* DO NOT REMOVE OR ALTER!
*/
/*
- * Copyright 2005 The Apache Software Foundation.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
@@ -34,7 +35,6 @@ import com.sun.org.apache.xerces.internal.xni.XNIException;
*
* @xerces.internal
*
- *
*/
public interface XPointerProcessor {
@@ -56,7 +56,6 @@ public interface XPointerProcessor {
* @throws XNIException Thrown if the xpointer string does not conform to
* the XPointer Framework syntax or the syntax of the pointer part does
* not conform to its definition for its scheme.
- *
*/
public void parseXPointer(String xpointer) throws XNIException;
@@ -74,7 +73,6 @@ public interface XPointerProcessor {
* 2 - An empty element call
* @return true if the element was resolved by the xpointer
* @throws XNIException Thrown to signal an error
- *
*/
public boolean resolveXPointer(QName element, XMLAttributes attributes,
Augmentations augs, int event) throws XNIException;
@@ -86,7 +84,6 @@ public interface XPointerProcessor {
* @return True if the xpointer expression matches a node/fragment in the resource
* else returns false.
* @throws XNIException Thrown to signal an error
- *
*/
public boolean isFragmentResolved() throws XNIException;
@@ -97,7 +94,6 @@ public interface XPointerProcessor {
* @return True if the xpointer expression matches a fragment in the resource
* else returns false.
* @throws XNIException Thrown to signal an error
- *
*/
public boolean isXPointerResolved() throws XNIException;
diff --git a/jaxp/src/com/sun/org/apache/xml/internal/serializer/CharInfo.java b/jaxp/src/com/sun/org/apache/xml/internal/serializer/CharInfo.java
index ab138efa477..04e77d6bc62 100644
--- a/jaxp/src/com/sun/org/apache/xml/internal/serializer/CharInfo.java
+++ b/jaxp/src/com/sun/org/apache/xml/internal/serializer/CharInfo.java
@@ -22,6 +22,11 @@
*/
package com.sun.org.apache.xml.internal.serializer;
+import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
+import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
+import com.sun.org.apache.xml.internal.serializer.utils.SystemIDResolver;
+import com.sun.org.apache.xml.internal.serializer.utils.Utils;
+import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
@@ -29,19 +34,11 @@ import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.Enumeration;
import java.util.HashMap;
+import java.util.Locale;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
-import java.security.AccessController;
-import java.security.PrivilegedAction;
-
import javax.xml.transform.TransformerException;
-import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
-import com.sun.org.apache.xml.internal.serializer.utils.SystemIDResolver;
-import com.sun.org.apache.xml.internal.serializer.utils.Utils;
-import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException;
-import com.sun.org.apache.xalan.internal.utils.ObjectFactory;
-
/**
* This class provides services that tell if a character should have
* special treatement, such as entity reference substitution or normalization
@@ -176,13 +173,19 @@ final class CharInfo
// file
// 3) try treating the resource a URI
- if (internal) {
- try {
+ try {
+ if (internal) {
// Load entity property files by using PropertyResourceBundle,
// cause of security issure for applets
entities = PropertyResourceBundle.getBundle(entitiesResource);
- } catch (Exception e) {}
- }
+ } else {
+ ClassLoader cl = SecuritySupport.getContextClassLoader();
+ if (cl != null) {
+ entities = PropertyResourceBundle.getBundle(entitiesResource,
+ Locale.getDefault(), cl);
+ }
+ }
+ } catch (Exception e) {}
if (entities != null) {
Enumeration keys = entities.getKeys();
@@ -198,6 +201,7 @@ final class CharInfo
set(S_CARRIAGERETURN);
} else {
InputStream is = null;
+ String err = null;
// Load user specified resource file by using URL loading, it
// requires a valid URI as parameter
@@ -205,18 +209,22 @@ final class CharInfo
if (internal) {
is = CharInfo.class.getResourceAsStream(entitiesResource);
} else {
- ClassLoader cl = ObjectFactory.findClassLoader();
- if (cl == null) {
- is = ClassLoader.getSystemResourceAsStream(entitiesResource);
- } else {
- is = cl.getResourceAsStream(entitiesResource);
+ ClassLoader cl = SecuritySupport.getContextClassLoader();
+ if (cl != null) {
+ try {
+ is = cl.getResourceAsStream(entitiesResource);
+ } catch (Exception e) {
+ err = e.getMessage();
+ }
}
if (is == null) {
try {
URL url = new URL(entitiesResource);
is = url.openStream();
- } catch (Exception e) {}
+ } catch (Exception e) {
+ err = e.getMessage();
+ }
}
}
@@ -224,7 +232,7 @@ final class CharInfo
throw new RuntimeException(
Utils.messages.createMessage(
MsgKey.ER_RESOURCE_COULD_NOT_FIND,
- new Object[] {entitiesResource, entitiesResource}));
+ new Object[] {entitiesResource, err}));
}
// Fix Bugzilla#4000: force reading in UTF-8
@@ -456,64 +464,56 @@ final class CharInfo
return isCleanTextASCII[value];
}
-// In the future one might want to use the array directly and avoid
-// the method call, but I think the JIT alreay inlines this well enough
-// so don't do it (for now) - bjm
-// public final boolean[] getASCIIClean()
-// {
-// return isCleanTextASCII;
-// }
-
-
- private static CharInfo getCharInfoBasedOnPrivilege(
- final String entitiesFileName, final String method,
- final boolean internal){
- return (CharInfo) AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- return new CharInfo(entitiesFileName,
- method, internal);}
- });
- }
/**
- * Factory that reads in a resource file that describes the mapping of
- * characters to entity references.
+ * Read an internal resource file that describes the mapping of
+ * characters to entity references; Construct a CharInfo object.
*
- * Resource files must be encoded in UTF-8 and have a format like:
- *
- * # First char # is a comment
- * Entity numericValue
- * quot 34
- * amp 38
- *
- * (Note: Why don't we just switch to .properties files? Oct-01 -sc)
- *
- * @param entitiesResource Name of entities resource file that should
- * be loaded, which describes that mapping of characters to entity references.
- * @param method the output method type, which should be one of "xml", "html", "text"...
+ * @param entitiesFileName Name of entities resource file that should
+ * be loaded, which describes the mapping of characters to entity references.
+ * @param method the output method type, which should be one of "xml", "html", and "text".
+ * @return an instance of CharInfo
*
* @xsl.usage internal
*/
- static CharInfo getCharInfo(String entitiesFileName, String method)
+ static CharInfo getCharInfoInternal(String entitiesFileName, String method)
{
CharInfo charInfo = (CharInfo) m_getCharInfoCache.get(entitiesFileName);
if (charInfo != null) {
return charInfo;
}
- // try to load it internally - cache
- try {
- charInfo = getCharInfoBasedOnPrivilege(entitiesFileName,
- method, true);
- m_getCharInfoCache.put(entitiesFileName, charInfo);
- return charInfo;
- } catch (Exception e) {}
+ charInfo = new CharInfo(entitiesFileName, method, true);
+ m_getCharInfoCache.put(entitiesFileName, charInfo);
+ return charInfo;
+ }
- // try to load it externally - do not cache
+ /**
+ * Constructs a CharInfo object using the following process to try reading
+ * the entitiesFileName parameter:
+ *
+ * 1) attempt to load it as a ResourceBundle
+ * 2) try using the class loader to find the specified file
+ * 3) try opening it as an URI
+ *
+ * In case of 2 and 3, the resource file must be encoded in UTF-8 and have the
+ * following format:
+ *
+ * # First char # is a comment
+ * Entity numericValue
+ * quot 34
+ * amp 38
+ *
+ *
+ * @param entitiesFileName Name of entities resource file that should
+ * be loaded, which describes the mapping of characters to entity references.
+ * @param method the output method type, which should be one of "xml", "html", and "text".
+ * @return an instance of CharInfo
+ */
+ static CharInfo getCharInfo(String entitiesFileName, String method)
+ {
try {
- return getCharInfoBasedOnPrivilege(entitiesFileName,
- method, false);
+ return new CharInfo(entitiesFileName, method, false);
} catch (Exception e) {}
String absoluteEntitiesFileName;
@@ -530,8 +530,7 @@ final class CharInfo
}
}
- return getCharInfoBasedOnPrivilege(entitiesFileName,
- method, false);
+ return new CharInfo(absoluteEntitiesFileName, method, false);
}
/** Table of user-specified char infos. */
diff --git a/jaxp/src/com/sun/org/apache/xml/internal/serializer/ToHTMLStream.java b/jaxp/src/com/sun/org/apache/xml/internal/serializer/ToHTMLStream.java
index aa48eaed8b4..a68ec6dfa04 100644
--- a/jaxp/src/com/sun/org/apache/xml/internal/serializer/ToHTMLStream.java
+++ b/jaxp/src/com/sun/org/apache/xml/internal/serializer/ToHTMLStream.java
@@ -60,7 +60,7 @@ public final class ToHTMLStream extends ToStream
*/
private static final CharInfo m_htmlcharInfo =
// new CharInfo(CharInfo.HTML_ENTITIES_RESOURCE);
- CharInfo.getCharInfo(CharInfo.HTML_ENTITIES_RESOURCE, Method.HTML);
+ CharInfo.getCharInfoInternal(CharInfo.HTML_ENTITIES_RESOURCE, Method.HTML);
/** A digital search trie for fast, case insensitive lookup of ElemDesc objects. */
static final Trie m_elementFlags = new Trie();
diff --git a/jaxp/src/com/sun/org/apache/xml/internal/serializer/ToXMLStream.java b/jaxp/src/com/sun/org/apache/xml/internal/serializer/ToXMLStream.java
index e64cc3face8..00463bce33f 100644
--- a/jaxp/src/com/sun/org/apache/xml/internal/serializer/ToXMLStream.java
+++ b/jaxp/src/com/sun/org/apache/xml/internal/serializer/ToXMLStream.java
@@ -58,7 +58,7 @@ public final class ToXMLStream extends ToStream
*/
private static CharInfo m_xmlcharInfo =
// new CharInfo(CharInfo.XML_ENTITIES_RESOURCE);
- CharInfo.getCharInfo(CharInfo.XML_ENTITIES_RESOURCE, Method.XML);
+ CharInfo.getCharInfoInternal(CharInfo.XML_ENTITIES_RESOURCE, Method.XML);
/**
* Default constructor.
diff --git a/jaxws/.hgtags b/jaxws/.hgtags
index a7525e9cd6a..17a198b1820 100644
--- a/jaxws/.hgtags
+++ b/jaxws/.hgtags
@@ -253,3 +253,6 @@ da44a8bdf1f3fdd518e7d785d60cc1b15983b176 jdk9-b04
eae966c8133fec0a8bf9e16d1274a4ede3c0fb52 jdk9-b05
cf0a6e41670f990414cd337000ad5f3bd1908073 jdk9-b06
856a9132f506cafe2f251c1a16a0b14e4d16048d jdk9-b07
+2d9f4166e0be68aa43c5f4fd0f8d34768e11f652 jdk9-b08
+c9e8bb8c1144a966ca7b481142c6b5e55d14a29c jdk9-b09
+9af43f4d215f6f19b1767f6ac66da931b8ee9535 jdk9-b10
diff --git a/jaxws/make/BuildJaxws.gmk b/jaxws/make/BuildJaxws.gmk
index 1c159965dd3..5994543f39f 100644
--- a/jaxws/make/BuildJaxws.gmk
+++ b/jaxws/make/BuildJaxws.gmk
@@ -35,21 +35,21 @@ DISABLE_JAXWS_WARNINGS := -Xlint:all,-varargs,-rawtypes,-deprecation,-unchecked,
# The generate new bytecode uses the new compiler for to generate bytecode
# for the new jdk that is being built. The code compiled by this setup
# cannot necessarily be run with the boot jdk.
-$(eval $(call SetupJavaCompiler,GENERATE_NEWBYTECODE_DEBUG, \
+$(eval $(call SetupJavaCompiler,GENERATE_NEWBYTECODE, \
JVM := $(JAVA), \
JAVAC := $(NEW_JAVAC), \
- FLAGS := -XDignore.symbol.file=true $(DISABLE_JAXWS_WARNINGS) -g, \
+ FLAGS := -XDignore.symbol.file=true $(DISABLE_JAXWS_WARNINGS), \
SERVER_DIR := $(SJAVAC_SERVER_DIR), \
SERVER_JVM := $(SJAVAC_SERVER_JAVA)))
$(eval $(call SetupJavaCompilation,BUILD_JAF, \
- SETUP := GENERATE_NEWBYTECODE_DEBUG, \
+ SETUP := GENERATE_NEWBYTECODE, \
SRC := $(JAXWS_TOPDIR)/src/share/jaf_classes, \
CLEAN := .properties, \
BIN := $(JAXWS_OUTPUTDIR)/jaf_classes))
$(eval $(call SetupJavaCompilation,BUILD_JAXWS, \
- SETUP := GENERATE_NEWBYTECODE_DEBUG, \
+ SETUP := GENERATE_NEWBYTECODE, \
SRC := $(JAXWS_TOPDIR)/src/share/jaxws_classes, \
BIN := $(JAXWS_OUTPUTDIR)/jaxws_classes, \
COPY := .xsd, \
diff --git a/jaxws/src/share/jaf_classes/javax/activation/CommandMap.java b/jaxws/src/share/jaf_classes/javax/activation/CommandMap.java
index 55f180b9554..93393377a06 100644
--- a/jaxws/src/share/jaf_classes/javax/activation/CommandMap.java
+++ b/jaxws/src/share/jaf_classes/javax/activation/CommandMap.java
@@ -25,6 +25,9 @@
package javax.activation;
+import java.util.Map;
+import java.util.WeakHashMap;
+
/**
* The CommandMap class provides an interface to a registry of
@@ -38,6 +41,8 @@ package javax.activation;
*/
public abstract class CommandMap {
private static CommandMap defaultCommandMap = null;
+ private static Map map =
+ new WeakHashMap();
/**
* Get the default CommandMap.
@@ -56,11 +61,18 @@ public abstract class CommandMap {
*
* @return the CommandMap
*/
- public static CommandMap getDefaultCommandMap() {
- if (defaultCommandMap == null)
- defaultCommandMap = new MailcapCommandMap();
+ public static synchronized CommandMap getDefaultCommandMap() {
+ if (defaultCommandMap != null)
+ return defaultCommandMap;
- return defaultCommandMap;
+ // fetch per-thread-context-class-loader default
+ ClassLoader tccl = SecuritySupport.getContextClassLoader();
+ CommandMap def = map.get(tccl);
+ if (def == null) {
+ def = new MailcapCommandMap();
+ map.put(tccl, def);
+ }
+ return def;
}
/**
@@ -71,7 +83,7 @@ public abstract class CommandMap {
* @exception SecurityException if the caller doesn't have permission
* to change the default
*/
- public static void setDefaultCommandMap(CommandMap commandMap) {
+ public static synchronized void setDefaultCommandMap(CommandMap commandMap) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
try {
@@ -79,13 +91,16 @@ public abstract class CommandMap {
security.checkSetFactory();
} catch (SecurityException ex) {
// otherwise, we also allow it if this code and the
- // factory come from the same class loader (e.g.,
+ // factory come from the same (non-system) class loader (e.g.,
// the JAF classes were loaded with the applet classes).
- if (CommandMap.class.getClassLoader() !=
+ if (CommandMap.class.getClassLoader() == null ||
+ CommandMap.class.getClassLoader() !=
commandMap.getClass().getClassLoader())
throw ex;
}
}
+ // remove any per-thread-context-class-loader CommandMap
+ map.remove(SecuritySupport.getContextClassLoader());
defaultCommandMap = commandMap;
}
diff --git a/jaxws/src/share/jaf_classes/javax/activation/DataHandler.java b/jaxws/src/share/jaf_classes/javax/activation/DataHandler.java
index 977fb7c3c10..6fef9302a83 100644
--- a/jaxws/src/share/jaf_classes/javax/activation/DataHandler.java
+++ b/jaxws/src/share/jaf_classes/javax/activation/DataHandler.java
@@ -368,7 +368,12 @@ public class DataHandler implements Transferable {
// if it's not set, set it...
if (transferFlavors == emptyFlavors)
transferFlavors = getDataContentHandler().getTransferDataFlavors();
- return transferFlavors;
+
+ if (transferFlavors == emptyFlavors)
+ return transferFlavors;
+ else
+ return transferFlavors.clone();
+
}
/**
diff --git a/jaxws/src/share/jaf_classes/javax/activation/FileTypeMap.java b/jaxws/src/share/jaf_classes/javax/activation/FileTypeMap.java
index a1922d8d070..a7c41185273 100644
--- a/jaxws/src/share/jaf_classes/javax/activation/FileTypeMap.java
+++ b/jaxws/src/share/jaf_classes/javax/activation/FileTypeMap.java
@@ -26,6 +26,8 @@
package javax.activation;
import java.io.File;
+import java.util.Map;
+import java.util.WeakHashMap;
/**
* The FileTypeMap is an abstract class that provides a data typing
@@ -48,6 +50,8 @@ import java.io.File;
public abstract class FileTypeMap {
private static FileTypeMap defaultMap = null;
+ private static Map map =
+ new WeakHashMap();
/**
* The default constructor.
@@ -78,11 +82,11 @@ public abstract class FileTypeMap {
* Sets the default FileTypeMap for the system. This instance
* will be returned to callers of getDefaultFileTypeMap.
*
- * @param map The FileTypeMap.
+ * @param fileTypeMap The FileTypeMap.
* @exception SecurityException if the caller doesn't have permission
* to change the default
*/
- public static void setDefaultFileTypeMap(FileTypeMap map) {
+ public static synchronized void setDefaultFileTypeMap(FileTypeMap fileTypeMap) {
SecurityManager security = System.getSecurityManager();
if (security != null) {
try {
@@ -90,14 +94,17 @@ public abstract class FileTypeMap {
security.checkSetFactory();
} catch (SecurityException ex) {
// otherwise, we also allow it if this code and the
- // factory come from the same class loader (e.g.,
+ // factory come from the same (non-system) class loader (e.g.,
// the JAF classes were loaded with the applet classes).
- if (FileTypeMap.class.getClassLoader() !=
- map.getClass().getClassLoader())
+ if (FileTypeMap.class.getClassLoader() == null ||
+ FileTypeMap.class.getClassLoader() !=
+ fileTypeMap.getClass().getClassLoader())
throw ex;
}
}
- defaultMap = map;
+ // remove any per-thread-context-class-loader FileTypeMap
+ map.remove(SecuritySupport.getContextClassLoader());
+ defaultMap = fileTypeMap;
}
/**
@@ -109,10 +116,17 @@ public abstract class FileTypeMap {
* @return The default FileTypeMap
* @see javax.activation.FileTypeMap#setDefaultFileTypeMap
*/
- public static FileTypeMap getDefaultFileTypeMap() {
- // XXX - probably should be synchronized
- if (defaultMap == null)
- defaultMap = new MimetypesFileTypeMap();
- return defaultMap;
+ public static synchronized FileTypeMap getDefaultFileTypeMap() {
+ if (defaultMap != null)
+ return defaultMap;
+
+ // fetch per-thread-context-class-loader default
+ ClassLoader tccl = SecuritySupport.getContextClassLoader();
+ FileTypeMap def = map.get(tccl);
+ if (def == null) {
+ def = new MimetypesFileTypeMap();
+ map.put(tccl, def);
+ }
+ return def;
}
}
diff --git a/jaxws/src/share/jaf_classes/javax/activation/MailcapCommandMap.java b/jaxws/src/share/jaf_classes/javax/activation/MailcapCommandMap.java
index b24774be77d..91df5fe9afb 100644
--- a/jaxws/src/share/jaf_classes/javax/activation/MailcapCommandMap.java
+++ b/jaxws/src/share/jaf_classes/javax/activation/MailcapCommandMap.java
@@ -120,11 +120,7 @@ import com.sun.activation.registries.LogSupport;
public class MailcapCommandMap extends CommandMap {
/*
* We manage a collection of databases, searched in order.
- * The default database is shared between all instances
- * of this class.
- * XXX - Can we safely share more databases between instances?
*/
- private static MailcapFile defDB = null;
private MailcapFile[] DB;
private static final int PROG = 0; // programmatically added entries
@@ -164,14 +160,10 @@ public class MailcapCommandMap extends CommandMap {
loadAllResources(dbv, "META-INF/mailcap");
LogSupport.log("MailcapCommandMap: load DEF");
- synchronized (MailcapCommandMap.class) {
- // see if another instance has created this yet.
- if (defDB == null)
- defDB = loadResource("/META-INF/mailcap.default");
- }
+ mf = loadResource("/META-INF/mailcap.default");
- if (defDB != null)
- dbv.add(defDB);
+ if (mf != null)
+ dbv.add(mf);
DB = new MailcapFile[dbv.size()];
DB = (MailcapFile[])dbv.toArray(DB);
diff --git a/jaxws/src/share/jaf_classes/javax/activation/MimetypesFileTypeMap.java b/jaxws/src/share/jaf_classes/javax/activation/MimetypesFileTypeMap.java
index 36a19fcae35..fca50572047 100644
--- a/jaxws/src/share/jaf_classes/javax/activation/MimetypesFileTypeMap.java
+++ b/jaxws/src/share/jaf_classes/javax/activation/MimetypesFileTypeMap.java
@@ -69,11 +69,7 @@ import com.sun.activation.registries.LogSupport;
public class MimetypesFileTypeMap extends FileTypeMap {
/*
* We manage a collection of databases, searched in order.
- * The default database is shared between all instances
- * of this class.
- * XXX - Can we safely share more databases between instances?
*/
- private static MimeTypeFile defDB = null;
private MimeTypeFile[] DB;
private static final int PROG = 0; // programmatically added entries
@@ -114,14 +110,10 @@ public class MimetypesFileTypeMap extends FileTypeMap {
loadAllResources(dbv, "META-INF/mime.types");
LogSupport.log("MimetypesFileTypeMap: load DEF");
- synchronized (MimetypesFileTypeMap.class) {
- // see if another instance has created this yet.
- if (defDB == null)
- defDB = loadResource("/META-INF/mimetypes.default");
- }
+ mf = loadResource("/META-INF/mimetypes.default");
- if (defDB != null)
- dbv.addElement(defDB);
+ if (mf != null)
+ dbv.addElement(mf);
DB = new MimeTypeFile[dbv.size()];
dbv.copyInto(DB);
diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..c8c847907cd
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.tools.internal.ws.wsdl.parser;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..c0267b823ea
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/ContextClassloaderLocal.properties
@@ -0,0 +1,26 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/Internalizer.java b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/Internalizer.java
index 449f4dcb6a5..c153cce7f68 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/Internalizer.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/Internalizer.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -60,12 +60,10 @@ import java.util.Set;
*/
public class Internalizer {
- private static final XPathFactory xpf = XmlUtil.newXPathFactory(true);
- private final XPath xpath = xpf.newXPath();
+ private final XPath xpath = xpf.get().newXPath();
private final DOMForest forest;
private final ErrorReceiver errorReceiver;
-
public Internalizer(DOMForest forest, WsimportOptions options, ErrorReceiver errorReceiver) {
this.forest = forest;
this.errorReceiver = errorReceiver;
@@ -77,6 +75,12 @@ public class Internalizer {
}
}
+ private static final ContextClassloaderLocal xpf = new ContextClassloaderLocal() {
+ @Override
+ protected XPathFactory initialValue() throws Exception {
+ return XPathFactory.newInstance();
+ }
+ };
/**
* Validates attributes of a <JAXWS:bindings> element.
*/
diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/JAXWSBindingExtensionHandler.java b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/JAXWSBindingExtensionHandler.java
index 52546947ad7..0f12222220c 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/JAXWSBindingExtensionHandler.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/ws/wsdl/parser/JAXWSBindingExtensionHandler.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -54,8 +54,14 @@ import java.util.Map;
public class JAXWSBindingExtensionHandler extends AbstractExtensionHandler {
// xml security enabled always, xpath used for parsing "part" attribute
- private static final XPathFactory xpf = XmlUtil.newXPathFactory(true);
- private final XPath xpath = xpf.newXPath();
+ private static final ContextClassloaderLocal xpf = new ContextClassloaderLocal() {
+ @Override
+ protected XPathFactory initialValue() throws Exception {
+ return XPathFactory.newInstance();
+ }
+ };
+
+ private final XPath xpath = xpf.get().newXPath();
public JAXWSBindingExtensionHandler(Map extensionHandlerMap) {
super(extensionHandlerMap);
diff --git a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/internalizer/Internalizer.java b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/internalizer/Internalizer.java
index 3fa46d39a00..c360248a139 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/internalizer/Internalizer.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/tools/internal/xjc/reader/internalizer/Internalizer.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -76,8 +76,6 @@ class Internalizer {
private static final String WSDL_NS = "http://schemas.xmlsoap.org/wsdl/";
- private static XPathFactory xpf = null;
-
private final XPath xpath;
/**
@@ -99,12 +97,7 @@ class Internalizer {
this.errorHandler = forest.getErrorHandler();
this.forest = forest;
this.enableSCD = enableSCD;
- synchronized (this) {
- if (xpf == null) {
- xpf = XmlFactory.createXPathFactory(disableSecureProcessing);
- }
- }
- xpath = xpf.newXPath();
+ xpath = XmlFactory.createXPathFactory(disableSecureProcessing).newXPath();
}
/**
@@ -170,7 +163,6 @@ class Internalizer {
if( a.getLocalName().equals("multiple") ) //
continue;
-
// TODO: flag error for this undefined attribute
}
}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/DatatypeConverterImpl.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/DatatypeConverterImpl.java
index 92e4337b012..7f58b05f24f 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/DatatypeConverterImpl.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/DatatypeConverterImpl.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,14 @@ package com.sun.xml.internal.bind;
import java.math.BigDecimal;
import java.math.BigInteger;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.Calendar;
+import java.util.Collections;
import java.util.GregorianCalendar;
+import java.util.Map;
import java.util.TimeZone;
+import java.util.WeakHashMap;
import javax.xml.bind.DatatypeConverter;
import javax.xml.bind.DatatypeConverterInterface;
@@ -356,7 +361,7 @@ public final class DatatypeConverterImpl implements DatatypeConverterInterface {
public static GregorianCalendar _parseDateTime(CharSequence s) {
String val = WhiteSpaceProcessor.trim(s).toString();
- return datatypeFactory.newXMLGregorianCalendar(val).toGregorianCalendar();
+ return getDatatypeFactory().newXMLGregorianCalendar(val).toGregorianCalendar();
}
public static String _printDateTime(Calendar val) {
@@ -722,14 +727,30 @@ public final class DatatypeConverterImpl implements DatatypeConverterInterface {
}
return false;
}
- private static final DatatypeFactory datatypeFactory;
- static {
- try {
- datatypeFactory = DatatypeFactory.newInstance();
- } catch (DatatypeConfigurationException e) {
- throw new Error(e);
+ private static final Map DF_CACHE = Collections.synchronizedMap(new WeakHashMap());
+
+ public static DatatypeFactory getDatatypeFactory() {
+ ClassLoader tccl = AccessController.doPrivileged(new PrivilegedAction() {
+ public ClassLoader run() {
+ return Thread.currentThread().getContextClassLoader();
+ }
+ });
+ DatatypeFactory df = DF_CACHE.get(tccl);
+ if (df == null) {
+ synchronized (DatatypeConverterImpl.class) {
+ df = DF_CACHE.get(tccl);
+ if (df == null) { // to prevent multiple initialization
+ try {
+ df = DatatypeFactory.newInstance();
+ } catch (DatatypeConfigurationException e) {
+ throw new Error(Messages.FAILED_TO_INITIALE_DATATYPE_FACTORY.format(),e);
+ }
+ DF_CACHE.put(tccl, df);
+ }
+ }
}
+ return df;
}
private static final class CalendarFormatter {
@@ -1045,7 +1066,7 @@ public final class DatatypeConverterImpl implements DatatypeConverterInterface {
@Deprecated
public Calendar parseTime(String lexicalXSDTime) {
- return datatypeFactory.newXMLGregorianCalendar(lexicalXSDTime).toGregorianCalendar();
+ return getDatatypeFactory().newXMLGregorianCalendar(lexicalXSDTime).toGregorianCalendar();
}
@Deprecated
@@ -1055,7 +1076,7 @@ public final class DatatypeConverterImpl implements DatatypeConverterInterface {
@Deprecated
public Calendar parseDate(String lexicalXSDDate) {
- return datatypeFactory.newXMLGregorianCalendar(lexicalXSDDate).toGregorianCalendar();
+ return getDatatypeFactory().newXMLGregorianCalendar(lexicalXSDDate).toGregorianCalendar();
}
@Deprecated
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/Messages.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/Messages.java
new file mode 100644
index 00000000000..f424fb71903
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/Messages.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.bind;
+
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+
+/**
+ * Message resources
+ */
+enum Messages {
+ FAILED_TO_INITIALE_DATATYPE_FACTORY, // 0 args
+ ;
+
+ private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName());
+
+ @Override
+ public String toString() {
+ return format();
+ }
+
+ public String format( Object... args ) {
+ return MessageFormat.format( rb.getString(name()), args );
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/Messages.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/Messages.properties
new file mode 100644
index 00000000000..1da585a50de
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/Messages.properties
@@ -0,0 +1,27 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_INITIALE_DATATYPE_FACTORY = \
+ Failed to initialize JAXP 1.3 DatatypeFactory class.
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/impl/Messages.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/impl/Messages.java
index 16190f0b77c..d429eb65310 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/impl/Messages.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/impl/Messages.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -60,7 +60,6 @@ enum Messages {
PROPERTY_ORDER_CONTAINS_UNUSED_ENTRY, // 2 args
INVALID_XML_ENUM_VALUE, // 2 arg
- FAILED_TO_INITIALE_DATATYPE_FACTORY, // 0 args
NO_IMAGE_WRITER, // 1 arg
ILLEGAL_MIME_TYPE, // 2 args
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/impl/RuntimeBuiltinLeafInfoImpl.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/impl/RuntimeBuiltinLeafInfoImpl.java
index e7ff4433460..9447c51048e 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/impl/RuntimeBuiltinLeafInfoImpl.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/model/impl/RuntimeBuiltinLeafInfoImpl.java
@@ -63,9 +63,7 @@ import javax.imageio.ImageWriter;
import javax.imageio.stream.ImageOutputStream;
import javax.xml.bind.ValidationEvent;
import javax.xml.bind.helpers.ValidationEventImpl;
-import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeConstants;
-import javax.xml.datatype.DatatypeFactory;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
@@ -574,7 +572,8 @@ public abstract class RuntimeBuiltinLeafInfoImpl extends BuiltinLeafInfoImpl<
public XMLGregorianCalendar parse(CharSequence lexical) throws SAXException {
try {
- return datatypeFactory.newXMLGregorianCalendar(lexical.toString().trim()); // (.trim() - issue 396)
+ return DatatypeConverterImpl.getDatatypeFactory()
+ .newXMLGregorianCalendar(lexical.toString().trim()); // (.trim() - issue 396)
} catch (Exception e) {
UnmarshallingContext.getInstance().handleError(e);
return null;
@@ -844,7 +843,7 @@ public abstract class RuntimeBuiltinLeafInfoImpl extends BuiltinLeafInfoImpl<
public Duration parse(CharSequence lexical) {
TODO.checkSpec("JSR222 Issue #42");
- return datatypeFactory.newDuration(lexical.toString());
+ return DatatypeConverterImpl.getDatatypeFactory().newDuration(lexical.toString());
}
});
primaryList.add(
@@ -885,21 +884,6 @@ public abstract class RuntimeBuiltinLeafInfoImpl extends BuiltinLeafInfoImpl<
}
}
-
- /**
- * Cached instance of {@link DatatypeFactory} to create
- * {@link XMLGregorianCalendar} and {@link Duration}.
- */
- private static final DatatypeFactory datatypeFactory = init();
-
- private static DatatypeFactory init() {
- try {
- return DatatypeFactory.newInstance();
- } catch (DatatypeConfigurationException e) {
- throw new Error(Messages.FAILED_TO_INITIALE_DATATYPE_FACTORY.format(),e);
- }
- }
-
private static void checkXmlGregorianCalendarFieldRef(QName type,
XMLGregorianCalendar cal)throws javax.xml.bind.MarshalException{
StringBuilder buf = new StringBuilder();
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/JAXBContextImpl.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/JAXBContextImpl.java
index 8454c632780..f7b1db6bee1 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/JAXBContextImpl.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/JAXBContextImpl.java
@@ -128,14 +128,6 @@ public final class JAXBContextImpl extends JAXBRIContext {
*/
private final Map bridges = new LinkedHashMap();
- /**
- * Shared instance of {@link TransformerFactory}.
- * Lock before use, because a {@link TransformerFactory} is not thread-safe
- * whereas {@link JAXBContextImpl} is.
- * Lazily created.
- */
- private volatile static SAXTransformerFactory tf;
-
/**
* Shared instance of {@link DocumentBuilder}.
* Lock before use. Lazily created.
@@ -705,13 +697,7 @@ public final class JAXBContextImpl extends JAXBRIContext {
*/
static Transformer createTransformer(boolean disableSecureProcessing) {
try {
- if (tf==null) {
- synchronized(JAXBContextImpl.class) {
- if (tf==null) {
- tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing);
- }
- }
- }
+ SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing);
return tf.newTransformer();
} catch (TransformerConfigurationException e) {
throw new Error(e); // impossible
@@ -723,13 +709,7 @@ public final class JAXBContextImpl extends JAXBRIContext {
*/
public static TransformerHandler createTransformerHandler(boolean disableSecureProcessing) {
try {
- if (tf==null) {
- synchronized(JAXBContextImpl.class) {
- if (tf==null) {
- tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing);
- }
- }
- }
+ SAXTransformerFactory tf = (SAXTransformerFactory)XmlFactory.createTransformerFactory(disableSecureProcessing);
return tf.newTransformerHandler();
} catch (TransformerConfigurationException e) {
throw new Error(e); // impossible
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/Messages.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/Messages.java
index 3239b418a36..d6b76551dfc 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/Messages.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/Messages.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -58,6 +58,7 @@ enum Messages {
FAILED_TO_GENERATE_SCHEMA, // 0 args
ERROR_PROCESSING_SCHEMA, // 0 args
ILLEGAL_CONTENT, // 2 args
+ FAILED_TO_INITIALE_DATATYPE_FACTORY, // 2 args
;
private static final ResourceBundle rb = ResourceBundle.getBundle(Messages.class.getName());
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/output/XMLStreamWriterOutput.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/output/XMLStreamWriterOutput.java
index 631a86be1cf..c4721fd5ea8 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/output/XMLStreamWriterOutput.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/output/XMLStreamWriterOutput.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -153,7 +153,6 @@ public class XMLStreamWriterOutput extends XmlOutputAbstractImpl {
}
}
-
/**
* Reference to FI's XMLStreamWriter class, if FI can be loaded.
*/
@@ -162,9 +161,8 @@ public class XMLStreamWriterOutput extends XmlOutputAbstractImpl {
private static Class initFIStAXWriterClass() {
try {
- ClassLoader loader = getClassLoader();
- Class llfisw = Class.forName("com.sun.xml.internal.org.jvnet.fastinfoset.stax.LowLevelFastInfosetStreamWriter", true, loader);
- Class sds = loader.loadClass("com.sun.xml.internal.fastinfoset.stax.StAXDocumentSerializer");
+ Class> llfisw = Class.forName("com.sun.xml.internal.org.jvnet.fastinfoset.stax.LowLevelFastInfosetStreamWriter");
+ Class> sds = Class.forName("com.sun.xml.internal.fastinfoset.stax.StAXDocumentSerializer");
// Check if StAXDocumentSerializer implements LowLevelFastInfosetStreamWriter
if (llfisw.isAssignableFrom(sds))
return sds;
@@ -179,8 +177,7 @@ public class XMLStreamWriterOutput extends XmlOutputAbstractImpl {
try {
if (FI_STAX_WRITER_CLASS == null)
return null;
- ClassLoader loader = getClassLoader();
- Class c = Class.forName("com.sun.xml.internal.bind.v2.runtime.output.FastInfosetStreamWriterOutput", true, loader);
+ Class c = Class.forName("com.sun.xml.internal.bind.v2.runtime.output.FastInfosetStreamWriterOutput");
return c.getConstructor(FI_STAX_WRITER_CLASS, JAXBContextImpl.class);
} catch (Throwable e) {
return null;
@@ -195,8 +192,7 @@ public class XMLStreamWriterOutput extends XmlOutputAbstractImpl {
private static Class initStAXExWriterClass() {
try {
- ClassLoader loader = getClassLoader();
- return Class.forName("com.sun.xml.internal.org.jvnet.staxex.XMLStreamWriterEx",true,loader);
+ return Class.forName("com.sun.xml.internal.org.jvnet.staxex.XMLStreamWriterEx");
} catch (Throwable e) {
return null;
}
@@ -204,20 +200,11 @@ public class XMLStreamWriterOutput extends XmlOutputAbstractImpl {
private static Constructor extends XmlOutput> initStAXExOutputClass() {
try {
- ClassLoader loader = getClassLoader();
- Class c = Class.forName("com.sun.xml.internal.bind.v2.runtime.output.StAXExStreamWriterOutput",true, loader);
+ Class c = Class.forName("com.sun.xml.internal.bind.v2.runtime.output.StAXExStreamWriterOutput");
return c.getConstructor(STAXEX_WRITER_CLASS);
} catch (Throwable e) {
return null;
}
}
- private static ClassLoader getClassLoader() {
- ClassLoader cl = SecureLoader.getClassClassLoader(UnmarshallerImpl.class);
- if (cl == null) {
- cl = SecureLoader.getContextClassLoader();
- }
- return cl;
- }
-
}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/reflect/Messages.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/reflect/Messages.properties
index ef094c72f01..8bff1f850bd 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/reflect/Messages.properties
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/reflect/Messages.properties
@@ -1,5 +1,5 @@
#
-# Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -38,3 +38,6 @@ NO_SETTER = \
NO_GETTER = \
The property has a setter "{0}" but no getter. \
For marshaller, please define getters.
+
+INVALID_XML_ENUM_VALUE = \
+ "{0}" is not a valid value for {1}.
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/unmarshaller/StAXStreamConnector.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/unmarshaller/StAXStreamConnector.java
index 1993cd648a4..3b6af4820a9 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/unmarshaller/StAXStreamConnector.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/bind/v2/runtime/unmarshaller/StAXStreamConnector.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -336,9 +336,8 @@ class StAXStreamConnector extends StAXConnector {
private static Class initFIStAXReaderClass() {
try {
- ClassLoader cl = getClassLoader();
- Class fisr = cl.loadClass("com.sun.xml.internal.org.jvnet.fastinfoset.stax.FastInfosetStreamReader");
- Class sdp = cl.loadClass("com.sun.xml.internal.fastinfoset.stax.StAXDocumentParser");
+ Class> fisr = Class.forName("com.sun.xml.internal.org.jvnet.fastinfoset.stax.FastInfosetStreamReader");
+ Class> sdp = Class.forName("com.sun.xml.internal.fastinfoset.stax.StAXDocumentParser");
// Check if StAXDocumentParser implements FastInfosetStreamReader
if (fisr.isAssignableFrom(sdp))
return sdp;
@@ -354,7 +353,7 @@ class StAXStreamConnector extends StAXConnector {
if (FI_STAX_READER_CLASS == null)
return null;
- Class c = getClassLoader().loadClass(
+ Class c = Class.forName(
"com.sun.xml.internal.bind.v2.runtime.unmarshaller.FastInfosetConnector");
return c.getConstructor(FI_STAX_READER_CLASS,XmlVisitor.class);
} catch (Throwable e) {
@@ -370,7 +369,7 @@ class StAXStreamConnector extends StAXConnector {
private static Class initStAXExReader() {
try {
- return getClassLoader().loadClass("com.sun.xml.internal.org.jvnet.staxex.XMLStreamReaderEx");
+ return Class.forName("com.sun.xml.internal.org.jvnet.staxex.XMLStreamReaderEx");
} catch (Throwable e) {
return null;
}
@@ -378,19 +377,11 @@ class StAXStreamConnector extends StAXConnector {
private static Constructor extends StAXConnector> initStAXExConnector() {
try {
- Class c = getClassLoader().loadClass("com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXExConnector");
+ Class c = Class.forName("com.sun.xml.internal.bind.v2.runtime.unmarshaller.StAXExConnector");
return c.getConstructor(STAX_EX_READER_CLASS,XmlVisitor.class);
} catch (Throwable e) {
return null;
}
}
- private static ClassLoader getClassLoader() {
- ClassLoader cl = SecureLoader.getClassClassLoader(UnmarshallerImpl.class);
- if (cl == null) {
- cl = SecureLoader.getContextClassLoader();
- }
- return cl;
- }
-
}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/AttachmentPartImpl.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/AttachmentPartImpl.java
index 76f6802b50d..bc35f38f8da 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/AttachmentPartImpl.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/AttachmentPartImpl.java
@@ -62,61 +62,6 @@ public class AttachmentPartImpl extends AttachmentPart {
Logger.getLogger(LogDomainConstants.SOAP_DOMAIN,
"com.sun.xml.internal.messaging.saaj.soap.LocalStrings");
- static {
- try {
- CommandMap map = CommandMap.getDefaultCommandMap();
- if (map instanceof MailcapCommandMap) {
- MailcapCommandMap mailMap = (MailcapCommandMap) map;
- String hndlrStr = ";;x-java-content-handler=";
- mailMap.addMailcap(
- "text/xml"
- + hndlrStr
- + "com.sun.xml.internal.messaging.saaj.soap.XmlDataContentHandler");
- mailMap.addMailcap(
- "application/xml"
- + hndlrStr
- + "com.sun.xml.internal.messaging.saaj.soap.XmlDataContentHandler");
- mailMap.addMailcap(
- "application/fastinfoset"
- + hndlrStr
- + "com.sun.xml.internal.messaging.saaj.soap.FastInfosetDataContentHandler");
- /* Image DataContentHandler handles all image types
- mailMap.addMailcap(
- "image/jpeg"
- + hndlrStr
- + "com.sun.xml.internal.messaging.saaj.soap.JpegDataContentHandler");
- mailMap.addMailcap(
- "image/gif"
- + hndlrStr
- + "com.sun.xml.internal.messaging.saaj.soap.GifDataContentHandler"); */
- /*mailMap.addMailcap(
- "multipart/*"
- + hndlrStr
- + "com.sun.xml.internal.messaging.saaj.soap.MultipartDataContentHandler");*/
- mailMap.addMailcap(
- "image/*"
- + hndlrStr
- + "com.sun.xml.internal.messaging.saaj.soap.ImageDataContentHandler");
- mailMap.addMailcap(
- "text/plain"
- + hndlrStr
- + "com.sun.xml.internal.messaging.saaj.soap.StringDataContentHandler");
- } else {
- throw new SOAPExceptionImpl("Default CommandMap is not a MailcapCommandMap");
- }
- } catch (Throwable t) {
- log.log(
- Level.SEVERE,
- "SAAJ0508.soap.cannot.register.handlers",
- t);
- if (t instanceof RuntimeException) {
- throw (RuntimeException) t;
- } else {
- throw new RuntimeException(t.getLocalizedMessage());
- }
- }
- };
-
private final MimeHeaders headers;
private MimeBodyPart rawContent = null;
private DataHandler dataHandler = null;
@@ -126,6 +71,12 @@ public class AttachmentPartImpl extends AttachmentPart {
public AttachmentPartImpl() {
headers = new MimeHeaders();
+
+ // initialization from here should cover most of cases;
+ // if not, it would be necessary to call
+ // AttachmentPartImpl.initializeJavaActivationHandlers()
+ // explicitly by programmer
+ initializeJavaActivationHandlers();
}
public AttachmentPartImpl(MIMEPart part) {
@@ -619,4 +570,43 @@ public class AttachmentPartImpl extends AttachmentPart {
return headers;
}
+ public static void initializeJavaActivationHandlers() {
+ // DataHandler.writeTo() may search for DCH. So adding some default ones.
+ try {
+ CommandMap map = CommandMap.getDefaultCommandMap();
+ if (map instanceof MailcapCommandMap) {
+ MailcapCommandMap mailMap = (MailcapCommandMap) map;
+
+ // registering our DCH since javamail's DCH doesn't handle
+ if (!cmdMapInitialized(mailMap)) {
+ mailMap.addMailcap("text/xml;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.XmlDataContentHandler");
+ mailMap.addMailcap("application/xml;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.XmlDataContentHandler");
+ mailMap.addMailcap("application/fastinfoset;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.FastInfosetDataContentHandler");
+ mailMap.addMailcap("multipart/*;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.MultipartDataContentHandler");
+ mailMap.addMailcap("image/*;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.ImageDataContentHandler");
+ mailMap.addMailcap("text/plain;;x-java-content-handler=com.sun.xml.internal.messaging.saaj.soap.StringDataContentHandler");
+ }
+ }
+ } catch (Throwable t) {
+ // ignore the exception.
+ }
+ }
+
+ private static boolean cmdMapInitialized(MailcapCommandMap mailMap) {
+
+ // checking fastinfoset handler, since this one is specific to SAAJ
+ CommandInfo[] commands = mailMap.getAllCommands("application/fastinfoset");
+ if (commands == null || commands.length == 0) {
+ return false;
+ }
+
+ String saajClassName = "com.sun.xml.internal.ws.binding.FastInfosetDataContentHandler";
+ for (CommandInfo command : commands) {
+ String commandClass = command.getCommandClass();
+ if (saajClassName.equals(commandClass)) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..280b0d62e25
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.messaging.saaj.soap;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..c0267b823ea
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/ContextClassloaderLocal.properties
@@ -0,0 +1,26 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/EnvelopeFactory.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/EnvelopeFactory.java
index 907c8ef9d91..58d14861e40 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/EnvelopeFactory.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/messaging/saaj/soap/EnvelopeFactory.java
@@ -25,7 +25,14 @@
package com.sun.xml.internal.messaging.saaj.soap;
-import java.util.logging.Logger;
+import com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl;
+import com.sun.xml.internal.messaging.saaj.util.JAXMStreamSource;
+import com.sun.xml.internal.messaging.saaj.util.LogDomainConstants;
+import com.sun.xml.internal.messaging.saaj.util.ParserPool;
+import com.sun.xml.internal.messaging.saaj.util.RejectDoctypeSaxFilter;
+import com.sun.xml.internal.messaging.saaj.util.transform.EfficientStreamingTransformer;
+import org.xml.sax.InputSource;
+import org.xml.sax.XMLReader;
import javax.xml.parsers.SAXParser;
import javax.xml.soap.SOAPException;
@@ -39,14 +46,11 @@ import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamSource;
-import org.xml.sax.InputSource;
-import org.xml.sax.XMLReader;
-
import com.sun.xml.internal.messaging.saaj.LazyEnvelopeSource;
-import com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl;
-import com.sun.xml.internal.messaging.saaj.util.*;
import com.sun.xml.internal.messaging.saaj.util.transform.EfficientStreamingTransformer;
+import java.util.logging.Logger;
+
/**
* EnvelopeFactory creates SOAP Envelope objects using different
* underlying implementations.
@@ -54,10 +58,16 @@ import com.sun.xml.internal.messaging.saaj.util.transform.EfficientStreamingTran
public class EnvelopeFactory {
protected static final Logger
- log = Logger.getLogger(LogDomainConstants.SOAP_DOMAIN,
- "com.sun.xml.internal.messaging.saaj.soap.LocalStrings");
+ log = Logger.getLogger(LogDomainConstants.SOAP_DOMAIN,
+ "com.sun.xml.internal.messaging.saaj.soap.LocalStrings");
- private static ParserPool parserPool = new ParserPool(5);
+ private static ContextClassloaderLocal parserPool =
+ new ContextClassloaderLocal() {
+ @Override
+ protected ParserPool initialValue() throws Exception {
+ return new ParserPool(5);
+ }
+ };
public static Envelope createEnvelope(Source src, SOAPPartImpl soapPart)
throws SOAPException
@@ -130,15 +140,15 @@ public class EnvelopeFactory {
SAXParser saxParser = null;
if (src instanceof StreamSource) {
try {
- saxParser = parserPool.get();
+ saxParser = parserPool.get().get();
} catch (Exception e) {
log.severe("SAAJ0601.util.newSAXParser.exception");
throw new SOAPExceptionImpl(
- "Couldn't get a SAX parser while constructing a envelope",
- e);
+ "Couldn't get a SAX parser while constructing a envelope",
+ e);
}
InputSource is = SAXSource.sourceToInputSource(src);
- if (is.getEncoding()== null && soapPart.getSourceCharsetEncoding() != null) {
+ if (is.getEncoding() == null && soapPart.getSourceCharsetEncoding() != null) {
is.setEncoding(soapPart.getSourceCharsetEncoding());
}
XMLReader rejectFilter;
@@ -147,15 +157,15 @@ public class EnvelopeFactory {
} catch (Exception ex) {
log.severe("SAAJ0510.soap.cannot.create.envelope");
throw new SOAPExceptionImpl(
- "Unable to create envelope from given source: ",
- ex);
+ "Unable to create envelope from given source: ",
+ ex);
}
src = new SAXSource(rejectFilter, is);
}
try {
Transformer transformer =
- EfficientStreamingTransformer.newTransformer();
+ EfficientStreamingTransformer.newTransformer();
DOMResult result = new DOMResult(soapPart);
transformer.transform(src, result);
@@ -167,11 +177,11 @@ public class EnvelopeFactory {
}
log.severe("SAAJ0511.soap.cannot.create.envelope");
throw new SOAPExceptionImpl(
- "Unable to create envelope from given source: ",
- ex);
+ "Unable to create envelope from given source: ",
+ ex);
} finally {
if (saxParser != null) {
- parserPool.returnParser(saxParser);
+ parserPool.get().returnParser(saxParser);
}
}
}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..fe4a2fe1d5a
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.stream.buffer;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..c0267b823ea
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/ContextClassloaderLocal.properties
@@ -0,0 +1,26 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/XMLStreamBuffer.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/XMLStreamBuffer.java
index c6c68344ce3..85166778d73 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/XMLStreamBuffer.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/stream/buffer/XMLStreamBuffer.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -370,7 +370,12 @@ public abstract class XMLStreamBuffer {
writeTo(handler, errorHandler, isFragment());
}
- private static final TransformerFactory trnsformerFactory = TransformerFactory.newInstance();
+ private static final ContextClassloaderLocal trnsformerFactory = new ContextClassloaderLocal() {
+ @Override
+ protected TransformerFactory initialValue() throws Exception {
+ return TransformerFactory.newInstance();
+ }
+ };
/**
* Writes out the contents of this buffer as DOM node and append that to the given node.
@@ -382,7 +387,7 @@ public abstract class XMLStreamBuffer {
*/
public final Node writeTo(Node n) throws XMLStreamBufferException {
try {
- Transformer t = trnsformerFactory.newTransformer();
+ Transformer t = trnsformerFactory.get().newTransformer();
t.transform(new XMLStreamBufferSource(this), new DOMResult(n));
return n.getLastChild();
} catch (TransformerException e) {
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..d62cb623a86
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.api.streaming;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..c0267b823ea
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/ContextClassloaderLocal.properties
@@ -0,0 +1,26 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamReaderFactory.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamReaderFactory.java
index db6cbc625e7..40a51184c89 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamReaderFactory.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamReaderFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -63,39 +63,43 @@ public abstract class XMLStreamReaderFactory {
private static final Logger LOGGER = Logger.getLogger(XMLStreamReaderFactory.class.getName());
+ private static final String CLASS_NAME_OF_WSTXINPUTFACTORY = "com.ctc.wstx.stax.WstxInputFactory";
+
/**
* Singleton instance.
*/
- private static volatile @NotNull XMLStreamReaderFactory theInstance;
+ private static volatile ContextClassloaderLocal streamReader =
+ new ContextClassloaderLocal() {
- private static final String CLASS_NAME_OF_WSTXINPUTFACTORY = "com.ctc.wstx.stax.WstxInputFactory";
+ @Override
+ protected XMLStreamReaderFactory initialValue() {
- static {
- XMLInputFactory xif = getXMLInputFactory();
- XMLStreamReaderFactory f=null;
+ XMLInputFactory xif = getXMLInputFactory();
+ XMLStreamReaderFactory f=null;
- // this system property can be used to disable the pooling altogether,
- // in case someone hits an issue with pooling in the production system.
- if(!getProperty(XMLStreamReaderFactory.class.getName()+".noPool")) {
- f = Zephyr.newInstance(xif);
- }
+ // this system property can be used to disable the pooling altogether,
+ // in case someone hits an issue with pooling in the production system.
+ if(!getProperty(XMLStreamReaderFactory.class.getName()+".noPool")) {
+ f = Zephyr.newInstance(xif);
+ }
- if(f==null) {
- // is this Woodstox?
- if (xif.getClass().getName().equals(CLASS_NAME_OF_WSTXINPUTFACTORY)) {
- f = new Woodstox(xif);
- }
- }
+ if(f==null) {
+ // is this Woodstox?
+ if (xif.getClass().getName().equals(CLASS_NAME_OF_WSTXINPUTFACTORY)) {
+ f = new Woodstox(xif);
+ }
+ }
- if (f==null) {
- f = new Default();
- }
+ if (f==null) {
+ f = new Default();
+ }
- theInstance = f;
- if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.log(Level.FINE, "XMLStreamReaderFactory instance is = {0}", theInstance);
- }
- }
+ if (LOGGER.isLoggable(Level.FINE)) {
+ LOGGER.log(Level.FINE, "XMLStreamReaderFactory instance is = {0}", f);
+ }
+ return f;
+ }
+ };
private static XMLInputFactory getXMLInputFactory() {
XMLInputFactory xif = null;
@@ -126,11 +130,11 @@ public abstract class XMLStreamReaderFactory {
if(f==null) {
throw new IllegalArgumentException();
}
- theInstance = f;
+ streamReader.set(f);
}
public static XMLStreamReaderFactory get() {
- return theInstance;
+ return streamReader.get();
}
public static XMLStreamReader create(InputSource source, boolean rejectDTDs) {
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamWriterFactory.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamWriterFactory.java
index 51f5da941b9..6cff489ba7b 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamWriterFactory.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/api/streaming/XMLStreamWriterFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -62,52 +62,54 @@ public abstract class XMLStreamWriterFactory {
/**
* Singleton instance.
*/
- private static volatile @NotNull XMLStreamWriterFactory theInstance;
+ private static volatile ContextClassloaderLocal writerFactory =
+ new ContextClassloaderLocal() {
-
- static {
- XMLOutputFactory xof = null;
- if (Boolean.getBoolean(XMLStreamWriterFactory.class.getName()+".woodstox")) {
- try {
- xof = (XMLOutputFactory)Class.forName("com.ctc.wstx.stax.WstxOutputFactory").newInstance();
- } catch (Exception e) {
- // Ignore and fallback to default XMLOutputFactory
- }
- }
- if (xof == null) {
- xof = XMLOutputFactory.newInstance();
- }
-
- XMLStreamWriterFactory f=null;
-
- // this system property can be used to disable the pooling altogether,
- // in case someone hits an issue with pooling in the production system.
- if (!Boolean.getBoolean(XMLStreamWriterFactory.class.getName()+".noPool")) {
- try {
- Class> clazz = xof.createXMLStreamWriter(new StringWriter()).getClass();
- if (clazz.getName().startsWith("com.sun.xml.internal.stream.")) {
- f = new Zephyr(xof,clazz);
+ @Override
+ protected XMLStreamWriterFactory initialValue() {
+ XMLOutputFactory xof = null;
+ if (Boolean.getBoolean(XMLStreamWriterFactory.class.getName()+".woodstox")) {
+ try {
+ xof = (XMLOutputFactory)Class.forName("com.ctc.wstx.stax.WstxOutputFactory").newInstance();
+ } catch (Exception e) {
+ // Ignore and fallback to default XMLOutputFactory
}
- } catch (XMLStreamException ex) {
- Logger.getLogger(XMLStreamWriterFactory.class.getName()).log(Level.INFO, null, ex);
- } catch (NoSuchMethodException ex) {
- Logger.getLogger(XMLStreamWriterFactory.class.getName()).log(Level.INFO, null, ex);
}
- }
+ if (xof == null) {
+ xof = XMLOutputFactory.newInstance();
+ }
- if(f==null) {
- // is this Woodstox?
- if(xof.getClass().getName().equals("com.ctc.wstx.stax.WstxOutputFactory"))
- f = new NoLock(xof);
- }
- if (f == null)
- f = new Default(xof);
+ XMLStreamWriterFactory f=null;
- theInstance = f;
- if (LOGGER.isLoggable(Level.FINE)) {
- LOGGER.log(Level.FINE, "XMLStreamWriterFactory instance is = {0}", f);
+ // this system property can be used to disable the pooling altogether,
+ // in case someone hits an issue with pooling in the production system.
+ if (!Boolean.getBoolean(XMLStreamWriterFactory.class.getName()+".noPool")) {
+ try {
+ Class> clazz = xof.createXMLStreamWriter(new StringWriter()).getClass();
+ if (clazz.getName().startsWith("com.sun.xml.internal.stream.")) {
+ f = new Zephyr(xof,clazz);
+ }
+ } catch (XMLStreamException ex) {
+ Logger.getLogger(XMLStreamWriterFactory.class.getName()).log(Level.INFO, null, ex);
+ } catch (NoSuchMethodException ex) {
+ Logger.getLogger(XMLStreamWriterFactory.class.getName()).log(Level.INFO, null, ex);
+ }
+ }
+
+ if(f==null) {
+ // is this Woodstox?
+ if(xof.getClass().getName().equals("com.ctc.wstx.stax.WstxOutputFactory"))
+ f = new NoLock(xof);
+ }
+ if (f == null)
+ f = new Default(xof);
+
+ if (LOGGER.isLoggable(Level.FINE)) {
+ LOGGER.log(Level.FINE, "XMLStreamWriterFactory instance is = {0}", f);
+ }
+ return f;
}
- }
+ };
/**
* See {@link #create(OutputStream)} for the contract.
@@ -170,7 +172,7 @@ public abstract class XMLStreamWriterFactory {
* Gets the singleton instance.
*/
public static @NotNull XMLStreamWriterFactory get() {
- return theInstance;
+ return writerFactory.get();
}
/**
@@ -183,7 +185,7 @@ public abstract class XMLStreamWriterFactory {
@SuppressWarnings({"null", "ConstantConditions"})
public static void set(@NotNull XMLStreamWriterFactory f) {
if(f==null) throw new IllegalArgumentException();
- theInstance = f;
+ writerFactory.set(f);
}
/**
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/binding/BindingImpl.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/binding/BindingImpl.java
index 7e2c908216d..927fad4d4b0 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/binding/BindingImpl.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/binding/BindingImpl.java
@@ -37,6 +37,9 @@ import com.sun.xml.internal.ws.client.HandlerConfiguration;
import com.sun.xml.internal.ws.developer.MemberSubmissionAddressingFeature;
import com.sun.xml.internal.ws.developer.BindingTypeFeature;
+import javax.activation.CommandInfo;
+import javax.activation.CommandMap;
+import javax.activation.MailcapCommandMap;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebServiceFeature;
@@ -151,12 +154,61 @@ public abstract class BindingImpl implements WSBinding {
return addressingVersion;
}
- public final
@NotNull
- Codec createCodec() {
+ public final Codec createCodec() {
+
+ // initialization from here should cover most of cases;
+ // if not, it would be necessary to call
+ // BindingImpl.initializeJavaActivationHandlers()
+ // explicitly by programmer
+ initializeJavaActivationHandlers();
+
return bindingId.createEncoder(this);
}
+ public static void initializeJavaActivationHandlers() {
+ // DataHandler.writeTo() may search for DCH. So adding some default ones.
+ try {
+ CommandMap map = CommandMap.getDefaultCommandMap();
+ if (map instanceof MailcapCommandMap) {
+ MailcapCommandMap mailMap = (MailcapCommandMap) map;
+
+ // registering our DCH since javamail's DCH doesn't handle
+ if (!cmdMapInitialized(mailMap)) {
+ mailMap.addMailcap("text/xml;;x-java-content-handler=com.sun.xml.internal.ws.encoding.XmlDataContentHandler");
+ mailMap.addMailcap("application/xml;;x-java-content-handler=com.sun.xml.internal.ws.encoding.XmlDataContentHandler");
+ mailMap.addMailcap("image/*;;x-java-content-handler=com.sun.xml.internal.ws.encoding.ImageDataContentHandler");
+ mailMap.addMailcap("text/plain;;x-java-content-handler=com.sun.xml.internal.ws.encoding.StringDataContentHandler");
+ }
+ }
+ } catch (Throwable t) {
+ // ignore the exception.
+ }
+ }
+
+ private static boolean cmdMapInitialized(MailcapCommandMap mailMap) {
+ CommandInfo[] commands = mailMap.getAllCommands("text/xml");
+ if (commands == null || commands.length == 0) {
+ return false;
+ }
+
+ // SAAJ RI implements it's own DataHandlers which can be used for JAX-WS too;
+ // see com.sun.xml.internal.messaging.saaj.soap.AttachmentPartImpl#initializeJavaActivationHandlers
+ // so if found any of SAAJ or our own handler registered, we are ok; anyway using SAAJ directly here
+ // is not good idea since we don't want standalone JAX-WS to depend on specific SAAJ impl.
+ // This is also reason for duplication of Handler's code by JAX-WS
+ String saajClassName = "com.sun.xml.internal.messaging.saaj.soap.XmlDataContentHandler";
+ String jaxwsClassName = "com.sun.xml.internal.ws.encoding.XmlDataContentHandler";
+ for (CommandInfo command : commands) {
+ String commandClass = command.getCommandClass();
+ if (saajClassName.equals(commandClass) ||
+ jaxwsClassName.equals(commandClass)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
public static BindingImpl create(@NotNull BindingID bindingId) {
if (bindingId.equals(BindingID.XML_HTTP))
return new HTTPBindingImpl();
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..63809b00875
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.commons.xmlutil;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..c0267b823ea
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/ContextClassloaderLocal.properties
@@ -0,0 +1,26 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/Converter.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/Converter.java
index 31d1d713443..375844200e2 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/Converter.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/commons/xmlutil/Converter.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -53,7 +53,12 @@ public final class Converter {
// prevents instantiation
}
private static final Logger LOGGER = Logger.getLogger(Converter.class);
- private static final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newInstance();
+ private static final ContextClassloaderLocal xmlOutputFactory = new ContextClassloaderLocal() {
+ @Override
+ protected XMLOutputFactory initialValue() throws Exception {
+ return XMLOutputFactory.newInstance();
+ }
+ };
private static final AtomicBoolean logMissingStaxUtilsWarning = new AtomicBoolean(false);
/**
@@ -110,7 +115,7 @@ public final class Converter {
stringOut = new StringWriter();
XMLStreamWriter writer = null;
try {
- writer = xmlOutputFactory.createXMLStreamWriter(stringOut);
+ writer = xmlOutputFactory.get().createXMLStreamWriter(stringOut);
if (createIndenter) {
writer = createIndenter(writer);
}
@@ -143,7 +148,7 @@ public final class Converter {
try {
if (message != null) {
- XMLStreamWriter xsw = xmlOutputFactory.createXMLStreamWriter(baos, encoding);
+ XMLStreamWriter xsw = xmlOutputFactory.get().createXMLStreamWriter(baos, encoding);
try {
message.writeTo(xsw);
} finally {
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/developer/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/developer/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..e7d0050e775
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/developer/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.developer;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/developer/MemberSubmissionEndpointReference.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/developer/MemberSubmissionEndpointReference.java
index e5a96231ba1..ee70a409528 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/developer/MemberSubmissionEndpointReference.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/developer/MemberSubmissionEndpointReference.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -64,7 +64,12 @@ import java.util.Map;
@XmlType(name = "EndpointReferenceType", namespace = MemberSubmissionEndpointReference.MSNS)
public final class MemberSubmissionEndpointReference extends EndpointReference implements MemberSubmissionAddressingConstants {
- private final static JAXBContext msjc = MemberSubmissionEndpointReference.getMSJaxbContext();
+ private final static ContextClassloaderLocal msjc = new ContextClassloaderLocal() {
+ @Override
+ protected JAXBContext initialValue() throws Exception {
+ return MemberSubmissionEndpointReference.getMSJaxbContext();
+ }
+ };
public MemberSubmissionEndpointReference() {
}
@@ -86,7 +91,7 @@ public final class MemberSubmissionEndpointReference extends EndpointReference i
}
try {
- Unmarshaller unmarshaller = MemberSubmissionEndpointReference.msjc.createUnmarshaller();
+ Unmarshaller unmarshaller = MemberSubmissionEndpointReference.msjc.get().createUnmarshaller();
MemberSubmissionEndpointReference epr = unmarshaller.unmarshal(source,MemberSubmissionEndpointReference.class).getValue();
this.addr = epr.addr;
@@ -106,7 +111,7 @@ public final class MemberSubmissionEndpointReference extends EndpointReference i
@Override
public void writeTo(Result result) {
try {
- Marshaller marshaller = MemberSubmissionEndpointReference.msjc.createMarshaller();
+ Marshaller marshaller = MemberSubmissionEndpointReference.msjc.get().createMarshaller();
//marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
marshaller.marshal(this, result);
} catch (JAXBException e) {
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/encoding/MimeCodec.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/encoding/MimeCodec.java
index fb8e5f2a5a6..fb25118fd2c 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/encoding/MimeCodec.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/encoding/MimeCodec.java
@@ -34,8 +34,6 @@ import com.sun.xml.internal.ws.api.message.Packet;
import com.sun.xml.internal.ws.api.pipe.Codec;
import com.sun.xml.internal.ws.api.pipe.ContentType;
import com.sun.xml.internal.ws.developer.StreamingAttachmentFeature;
-import javax.activation.CommandMap;
-import javax.activation.MailcapCommandMap;
import java.io.IOException;
import java.io.InputStream;
@@ -63,33 +61,6 @@ import java.util.UUID;
*/
abstract class MimeCodec implements Codec {
- static {
- // DataHandler.writeTo() may search for DCH. So adding some default ones.
- try {
- CommandMap map = CommandMap.getDefaultCommandMap();
- if (map instanceof MailcapCommandMap) {
- MailcapCommandMap mailMap = (MailcapCommandMap) map;
- String hndlrStr = ";;x-java-content-handler=";
- // registering our DCH since javamail's DCH doesn't handle
- // Source
- mailMap.addMailcap(
- "text/xml" + hndlrStr + XmlDataContentHandler.class.getName());
- mailMap.addMailcap(
- "application/xml" + hndlrStr + XmlDataContentHandler.class.getName());
- if (map.createDataContentHandler("image/*") == null) {
- mailMap.addMailcap(
- "image/*" + hndlrStr + ImageDataContentHandler.class.getName());
- }
- if (map.createDataContentHandler("text/plain") == null) {
- mailMap.addMailcap(
- "text/plain" + hndlrStr + StringDataContentHandler.class.getName());
- }
- }
- } catch (Throwable t) {
- // ignore the exception.
- }
- }
-
public static final String MULTIPART_RELATED_MIME_TYPE = "multipart/related";
protected Codec mimeRootCodec;
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..f77560163cb
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ContextClassloaderLocal.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.policy.sourcemodel.attach;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return AccessController.doPrivileged(new PrivilegedAction() {
+ public ClassLoader run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..dda20375382
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ContextClassloaderLocal.properties
@@ -0,0 +1,27 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+# Error messages for ContextClassloaderLocal utility class
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ExternalAttachmentsUnmarshaller.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ExternalAttachmentsUnmarshaller.java
index f1664c33dc9..aaed1d8f8bd 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ExternalAttachmentsUnmarshaller.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/policy/sourcemodel/attach/ExternalAttachmentsUnmarshaller.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,7 +83,13 @@ public class ExternalAttachmentsUnmarshaller {
private static final QName POLICY = new QName("http://www.w3.org/ns/ws-policy", "Policy");
private static final QName URI = new QName("http://www.w3.org/ns/ws-policy", "URI");
private static final QName POLICIES = new QName(PolicyConstants.SUN_MANAGEMENT_NAMESPACE, "Policies");
- private static final XMLInputFactory XML_INPUT_FACTORY = XMLInputFactory.newInstance();
+ private static final ContextClassloaderLocal XML_INPUT_FACTORY = new ContextClassloaderLocal() {
+ @Override
+ protected XMLInputFactory initialValue() throws Exception {
+ return XMLInputFactory.newInstance();
+ }
+ };
+
private static final PolicyModelUnmarshaller POLICY_UNMARSHALLER = PolicyModelUnmarshaller.getXmlUnmarshaller();
private final Map map = new HashMap();
@@ -93,7 +99,7 @@ public class ExternalAttachmentsUnmarshaller {
public static Map unmarshal(final Reader source) throws PolicyException {
LOGGER.entering(source);
try {
- XMLEventReader reader = XML_INPUT_FACTORY.createXMLEventReader(source);
+ XMLEventReader reader = XML_INPUT_FACTORY.get().createXMLEventReader(source);
ExternalAttachmentsUnmarshaller instance = new ExternalAttachmentsUnmarshaller();
final Map map = instance.unmarshal(reader, null);
LOGGER.exiting(map);
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..cf0bf26eec3
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.spi;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..c0267b823ea
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ContextClassloaderLocal.properties
@@ -0,0 +1,26 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ProviderImpl.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ProviderImpl.java
index 05b7a2f080a..30f5a7d8042 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ProviderImpl.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/spi/ProviderImpl.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -80,7 +80,12 @@ import java.util.Map;
*/
public class ProviderImpl extends Provider {
- private final static JAXBContext eprjc = getEPRJaxbContext();
+ private final static ContextClassloaderLocal eprjc = new ContextClassloaderLocal() {
+ @Override
+ protected JAXBContext initialValue() throws Exception {
+ return getEPRJaxbContext();
+ }
+ };
/**
* Convenient singleton instance.
@@ -148,7 +153,7 @@ public class ProviderImpl extends Provider {
return AccessController.doPrivileged(new PrivilegedAction() {
public EndpointReference run() {
try {
- Unmarshaller unmarshaller = eprjc.createUnmarshaller();
+ Unmarshaller unmarshaller = eprjc.get().createUnmarshaller();
return (EndpointReference) unmarshaller.unmarshal(eprInfoset);
} catch (JAXBException e) {
throw new WebServiceException("Error creating Marshaller or marshalling.", e);
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..93a44b68050
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.ws.util.xml;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..c0267b823ea
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/ContextClassloaderLocal.properties
@@ -0,0 +1,26 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java
index f6b63d48823..cd87c3b0e2e 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/ws/util/xml/XmlUtil.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -215,20 +215,28 @@ public class XmlUtil {
}
}
- static final TransformerFactory transformerFactory = newTransformerFactory();
+ static final ContextClassloaderLocal transformerFactory = new ContextClassloaderLocal() {
+ @Override
+ protected TransformerFactory initialValue() throws Exception {
+ return TransformerFactory.newInstance();
+ }
+ };
- static final SAXParserFactory saxParserFactory = newSAXParserFactory(true);
-
- static {
- saxParserFactory.setNamespaceAware(true);
- }
+ static final ContextClassloaderLocal saxParserFactory = new ContextClassloaderLocal() {
+ @Override
+ protected SAXParserFactory initialValue() throws Exception {
+ SAXParserFactory factory = SAXParserFactory.newInstance();
+ factory.setNamespaceAware(true);
+ return factory;
+ }
+ };
/**
* Creates a new identity transformer.
*/
public static Transformer newTransformer() {
try {
- return transformerFactory.newTransformer();
+ return transformerFactory.get().newTransformer();
} catch (TransformerConfigurationException tex) {
throw new IllegalStateException("Unable to create a JAXP transformer");
}
@@ -243,9 +251,9 @@ public class XmlUtil {
// work around a bug in JAXP in JDK6u4 and earlier where the namespace processing
// is not turned on by default
StreamSource ssrc = (StreamSource) src;
- TransformerHandler th = ((SAXTransformerFactory) transformerFactory).newTransformerHandler();
+ TransformerHandler th = ((SAXTransformerFactory) transformerFactory.get()).newTransformerHandler();
th.setResult(result);
- XMLReader reader = saxParserFactory.newSAXParser().getXMLReader();
+ XMLReader reader = saxParserFactory.get().newSAXParser().getXMLReader();
reader.setContentHandler(th);
reader.setProperty(LEXICAL_HANDLER_PROPERTY, th);
reader.parse(toInputSource(ssrc));
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/ContextClassloaderLocal.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/ContextClassloaderLocal.java
new file mode 100644
index 00000000000..b8b09bf36c1
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/ContextClassloaderLocal.java
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.xml.internal.xsom.util;
+
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.text.MessageFormat;
+import java.util.ResourceBundle;
+import java.util.WeakHashMap;
+
+/**
+ * Simple utility ensuring that the value is cached only in case it is non-internal implementation
+ */
+abstract class ContextClassloaderLocal {
+
+ private static final String FAILED_TO_CREATE_NEW_INSTANCE = "FAILED_TO_CREATE_NEW_INSTANCE";
+
+ private WeakHashMap CACHE = new WeakHashMap();
+
+ public V get() throws Error {
+ ClassLoader tccl = getContextClassLoader();
+ V instance = CACHE.get(tccl);
+ if (instance == null) {
+ instance = createNewInstance();
+ CACHE.put(tccl, instance);
+ }
+ return instance;
+ }
+
+ public void set(V instance) {
+ CACHE.put(getContextClassLoader(), instance);
+ }
+
+ protected abstract V initialValue() throws Exception;
+
+ private V createNewInstance() {
+ try {
+ return initialValue();
+ } catch (Exception e) {
+ throw new Error(format(FAILED_TO_CREATE_NEW_INSTANCE, getClass().getName()), e);
+ }
+ }
+
+ private static String format(String property, Object... args) {
+ String text = ResourceBundle.getBundle(ContextClassloaderLocal.class.getName()).getString(property);
+ return MessageFormat.format(text, args);
+ }
+
+ private static ClassLoader getContextClassLoader() {
+ return (ClassLoader)
+ AccessController.doPrivileged(new PrivilegedAction() {
+ public Object run() {
+ ClassLoader cl = null;
+ try {
+ cl = Thread.currentThread().getContextClassLoader();
+ } catch (SecurityException ex) {
+ }
+ return cl;
+ }
+ });
+ }
+}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/ContextClassloaderLocal.properties b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/ContextClassloaderLocal.properties
new file mode 100644
index 00000000000..c0267b823ea
--- /dev/null
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/ContextClassloaderLocal.properties
@@ -0,0 +1,26 @@
+#
+# Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+FAILED_TO_CREATE_NEW_INSTANCE=Failed to create new instance of {0}
diff --git a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/DomAnnotationParserFactory.java b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/DomAnnotationParserFactory.java
index 23a78672aaf..ed2a05226e7 100644
--- a/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/DomAnnotationParserFactory.java
+++ b/jaxws/src/share/jaxws_classes/com/sun/xml/internal/xsom/util/DomAnnotationParserFactory.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -63,10 +63,15 @@ public class DomAnnotationParserFactory implements AnnotationParserFactory {
}
public AnnotationParser create(boolean disableSecureProcessing) {
- return new AnnotationParserImpl();
+ return new AnnotationParserImpl(disableSecureProcessing);
}
- private static final SAXTransformerFactory stf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
+ private static final ContextClassloaderLocal stf = new ContextClassloaderLocal() {
+ @Override
+ protected SAXTransformerFactory initialValue() throws Exception {
+ return (SAXTransformerFactory) SAXTransformerFactory.newInstance();
+ }
+ };
private static class AnnotationParserImpl extends AnnotationParser {
@@ -82,8 +87,9 @@ public class DomAnnotationParserFactory implements AnnotationParserFactory {
AnnotationParserImpl(boolean disableSecureProcessing) {
try {
- transformer = stf.newTransformerHandler();
- stf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, disableSecureProcessing);
+ SAXTransformerFactory factory = stf.get();
+ factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, disableSecureProcessing);
+ transformer = factory.newTransformerHandler();
} catch (TransformerConfigurationException e) {
throw new Error(e); // impossible
}
diff --git a/jaxws/src/share/jaxws_classes/javax/xml/ws/wsaddressing/W3CEndpointReference.java b/jaxws/src/share/jaxws_classes/javax/xml/ws/wsaddressing/W3CEndpointReference.java
index 44e103469a5..a1bc3e2b9c2 100644
--- a/jaxws/src/share/jaxws_classes/javax/xml/ws/wsaddressing/W3CEndpointReference.java
+++ b/jaxws/src/share/jaxws_classes/javax/xml/ws/wsaddressing/W3CEndpointReference.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -69,7 +69,7 @@ import java.util.Map;
@XmlType(name="EndpointReferenceType",namespace=W3CEndpointReference.NS)
public final class W3CEndpointReference extends EndpointReference {
- private final static JAXBContext w3cjc = getW3CJaxbContext();
+ private final JAXBContext w3cjc = getW3CJaxbContext();
// should be changed to package private, keeping original modifier to keep backwards compatibility
protected static final String NS = "http://www.w3.org/2005/08/addressing";
diff --git a/jdk/.hgtags b/jdk/.hgtags
index 118a09481e8..ee44f528378 100644
--- a/jdk/.hgtags
+++ b/jdk/.hgtags
@@ -250,3 +250,6 @@ d31cd980e1da31fa496a359caaf1a165aeb5791a jdk8-b120
263198a1d8f1f4cb97d35f40c61704b08ebd3686 jdk9-b05
cac7b28b8b1e0e11d7a8e1ac1fe75a03b3749eab jdk9-b06
f4e624447514f12dd7c51f1e5b0cb97efcd15be2 jdk9-b07
+9e7bd44ea85c72318130379c34b98716b9c7c248 jdk9-b08
+2cef452ba711b17950da275fd15931925799f07c jdk9-b09
+ab06ba2894313a47e4969ca37792ff119c49e711 jdk9-b10
diff --git a/jdk/make/CompileDemos.gmk b/jdk/make/CompileDemos.gmk
index 3b1839102a7..6f80d632c49 100644
--- a/jdk/make/CompileDemos.gmk
+++ b/jdk/make/CompileDemos.gmk
@@ -176,7 +176,6 @@ $(eval $(call SetupDemo,FullThreadDump,management,,FullThreadDump,,,README*))
$(eval $(call SetupDemo,JTop,management,,JTop,,,README*))
$(eval $(call SetupDemo,MemoryMonitor,management,,MemoryMonitor,,,README*))
$(eval $(call SetupDemo,VerboseGC,management,,VerboseGC,,,README*))
-$(eval $(call SetupDemo,zipfs,nio,,,,,README* *.java,,,,Main-Class: \n))
ifndef OPENJDK
$(eval $(call SetupDemo,Laffy,jfc,,,,closed/,*))
diff --git a/jdk/make/CompileJavaClasses.gmk b/jdk/make/CompileJavaClasses.gmk
index ec003f58c20..aed9bec516c 100644
--- a/jdk/make/CompileJavaClasses.gmk
+++ b/jdk/make/CompileJavaClasses.gmk
@@ -326,7 +326,7 @@ JDK_USER_DEFINED_FILTER := $(strip $(subst $(COMMA),$(SPACE), $(JDK_FILTER)))
ifeq ($(ENABLE_SJAVAC),yes)
# With sjavac enabled, excluded sources are not even considered for linking.
# Explicitly add the security sources to sourcepath for linking.
- BUILD_JDK_SOURCEPATH:=$(patsubst %,-i$(SPACE)%.*,$(subst /,.,$(SECURITY_PKGS))) \
+ BUILD_JDK_SOURCEPATH:=$(patsubst %,-i$(SPACE)%/*,$(SECURITY_PKGS)) \
-sourcepath $(JDK_TOPDIR)/src/share/classes
endif
diff --git a/jdk/make/CopyFiles.gmk b/jdk/make/CopyFiles.gmk
index 9fba2dd04cc..5566d4628d4 100644
--- a/jdk/make/CopyFiles.gmk
+++ b/jdk/make/CopyFiles.gmk
@@ -158,15 +158,6 @@ COPY_FILES += $(CURSORS_TARGET_FILES)
##########################################################################################
-CONTENT_TYPES_SRC = $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/lib
-
-$(LIBDIR)/content-types.properties: $(CONTENT_TYPES_SRC)/content-types.properties
- $(call install-file)
-
-COPY_FILES += $(LIBDIR)/content-types.properties
-
-##########################################################################################
-
CALENDARS_SRC := $(JDK_TOPDIR)/src/share/lib
$(LIBDIR)/calendars.properties: $(CALENDARS_SRC)/calendars.properties
@@ -183,9 +174,9 @@ COPY_FILES += $(LIBDIR)/hijrah-config-umalqura.properties
##########################################################################################
-ifeq ($(OPENJDK_TARGET_OS), windows)
+ifneq ($(findstring $(OPENJDK_TARGET_OS), windows aix),)
- TZMAPPINGS_SRC := $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS_API_DIR)/lib
+ TZMAPPINGS_SRC := $(JDK_TOPDIR)/src/$(OPENJDK_TARGET_OS)/lib
$(LIBDIR)/tzmappings: $(TZMAPPINGS_SRC)/tzmappings
$(call install-file)
diff --git a/jdk/make/CopyIntoClasses.gmk b/jdk/make/CopyIntoClasses.gmk
index 6c622e12177..36b0919fa2f 100644
--- a/jdk/make/CopyIntoClasses.gmk
+++ b/jdk/make/CopyIntoClasses.gmk
@@ -26,7 +26,7 @@
# Copy icu and _dict files used by the text break iterator
COPY_PATTERNS := .icu _dict .dat _options .js aliasmap .spp .wav .css \
- .png .gif .xml .dtd .txt oqlhelp.html
+ .png .gif .xml .dtd .txt oqlhelp.html content-types.properties
# These directories should not be copied at all
EXCLUDES += \
diff --git a/jdk/make/CreateJars.gmk b/jdk/make/CreateJars.gmk
index 91145fdb4b7..eebdcf666f0 100644
--- a/jdk/make/CreateJars.gmk
+++ b/jdk/make/CreateJars.gmk
@@ -160,11 +160,13 @@ RT_JAR_EXCLUDES += \
javax/swing/JWindowBeanInfo.class \
javax/swing/SwingBeanInfoBase.class \
javax/swing/text/JTextComponentBeanInfo.class \
+ jdk/nio/zipfs \
META-INF/services/com.sun.jdi.connect.Connector \
META-INF/services/com.sun.jdi.connect.spi.TransportService \
META-INF/services/com.sun.tools.attach.spi.AttachProvider \
META-INF/services/com.sun.tools.xjc.Plugin \
META-INF/services/sun.net.spi.nameservice.NameServiceDescriptor \
+ META-INF/services/java.nio.file.spi.FileSystemProvider \
org/relaxng/datatype \
sun/awt/HKSCS.class \
sun/awt/motif/X11GB2312.class \
@@ -356,6 +358,16 @@ $(eval $(call SetupArchive,BUILD_CHARSETS_JAR, , \
##########################################################################################
+$(eval $(call SetupArchive,BUILD_ZIPFS_JAR, , \
+ SRCS := $(JDK_OUTPUTDIR)/classes, \
+ INCLUDES := jdk/nio/zipfs, \
+ EXTRA_FILES := META-INF/services/java.nio.file.spi.FileSystemProvider, \
+ JAR := $(IMAGES_OUTPUTDIR)/lib/ext/zipfs.jar, \
+ SKIP_METAINF := true, \
+ CHECK_COMPRESS_JAR := true))
+
+##########################################################################################
+
ifndef OPENJDK
ifeq ($(ENABLE_JFR), true)
$(eval $(call SetupArchive,BUILD_JFR_JAR, , \
@@ -660,11 +672,6 @@ $(IMAGES_OUTPUTDIR)/lib/management-agent.jar: $(JDK_TOPDIR)/src/share/classes/su
##########################################################################################
-$(IMAGES_OUTPUTDIR)/lib/ext/zipfs.jar: $(JDK_OUTPUTDIR)/demo/nio/zipfs/zipfs.jar
- $(install-file)
-
-##########################################################################################
-
# This file is imported from hotspot in Import.gmk. Copying it into images/lib so that
# all jars can be found in one place when creating images in Images.gmk. It needs to be
# done here so that clean targets can be simple and accurate.
diff --git a/jdk/make/data/jdwp/jdwp.spec b/jdk/make/data/jdwp/jdwp.spec
index 7ddbaf4912b..0df8837c2cb 100644
--- a/jdk/make/data/jdwp/jdwp.spec
+++ b/jdk/make/data/jdwp/jdwp.spec
@@ -1079,7 +1079,7 @@ JDWP "Java(tm) Debug Wire Protocol"
(Command InvokeMethod=3
"Invokes a static method. "
"The method must be member of the class type "
- "or one of its superclasses, superinterfaces, or implemented interfaces. "
+ "or one of its superclasses. "
"Access control is not enforced; for example, private "
"methods can be invoked."
"
"
diff --git a/jdk/make/mapfiles/libnet/mapfile-vers b/jdk/make/mapfiles/libnet/mapfile-vers
index 879fff4a850..ab621a923a8 100644
--- a/jdk/make/mapfiles/libnet/mapfile-vers
+++ b/jdk/make/mapfiles/libnet/mapfile-vers
@@ -94,6 +94,10 @@ SUNWprivate_1.1 {
Java_sun_net_sdp_SdpSupport_create0;
Java_sun_net_spi_DefaultProxySelector_init;
Java_sun_net_spi_DefaultProxySelector_getSystemProxy;
+ Java_sun_net_ExtendedOptionsImpl_init;
+ Java_sun_net_ExtendedOptionsImpl_setFlowOption;
+ Java_sun_net_ExtendedOptionsImpl_getFlowOption;
+ Java_sun_net_ExtendedOptionsImpl_flowSupported;
NET_AllocSockaddr;
NET_SockaddrToInetAddress;
NET_SockaddrEqualsInetAddress;
diff --git a/jdk/make/profile-includes.txt b/jdk/make/profile-includes.txt
index f8fbef0c69a..f2ae4c1b31c 100644
--- a/jdk/make/profile-includes.txt
+++ b/jdk/make/profile-includes.txt
@@ -56,7 +56,6 @@ PROFILE_1_JRE_LIB_FILES := \
$(OPENJDK_TARGET_CPU_LEGACY_LIB)/server/Xusage.txt \
calendars.properties \
classlist \
- content-types.properties \
currency.data \
ext/localedata.jar \
ext/meta-index \
diff --git a/jdk/src/aix/lib/tzmappings b/jdk/src/aix/lib/tzmappings
new file mode 100644
index 00000000000..079d2c937ba
--- /dev/null
+++ b/jdk/src/aix/lib/tzmappings
@@ -0,0 +1,586 @@
+#
+#
+# Copyright (c) 1994, 2014, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation. Oracle designates this
+# particular file as subject to the "Classpath" exception as provided
+# by Oracle in the LICENSE file that accompanied this code.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#
+
+#
+# Portions Copyright (c) 2014 IBM Corporation
+#
+
+# This table describes mappings between AIX time zone IDs and Java time zone
+# IDs. Fields are separated by a single TAB ('\t'). Lines must be in the ascending
+# order in ASCII. (non-ASCII characters can't be used.)
+# NOTE
+# This table format is not a public interface of any Java
+# platforms. No applications should depend on this file in any form.
+# This file has been generated using programs. Do not edit this file manually.
+#
+# Solaris Java
+
+ACST-9:30ACDT Australia/Adelaide
+AST4 America/Curacao
+AST4ADT America/Halifax
+AST9 Pacific/Gambier
+AST9ADT America/Anchorage
+AZOREST1 Atlantic/Cape_Verde
+AZOREST1AZOREDT Atlantic/Azores
+Africa/Abidjan Africa/Abidjan
+Africa/Accra Africa/Accra
+Africa/Addis_Ababa Africa/Addis_Ababa
+Africa/Algiers Africa/Algiers
+Africa/Asmera Africa/Asmera
+Africa/Bamako GMT
+Africa/Bangui Africa/Bangui
+Africa/Banjul Africa/Banjul
+Africa/Bissau Africa/Bissau
+Africa/Blantyre Africa/Blantyre
+Africa/Brazzaville Africa/Luanda
+Africa/Bujumbura Africa/Bujumbura
+Africa/Cairo Africa/Cairo
+Africa/Casablanca Africa/Casablanca
+Africa/Ceuta Europe/Paris
+Africa/Conakry Africa/Conakry
+Africa/Dakar Africa/Dakar
+Africa/Dar_es_Salaam Africa/Dar_es_Salaam
+Africa/Djibouti Africa/Djibouti
+Africa/Douala Africa/Douala
+Africa/El_Aaiun Africa/Casablanca
+Africa/Freetown Africa/Freetown
+Africa/Gaborone Africa/Gaborone
+Africa/Harare Africa/Harare
+Africa/Johannesburg Africa/Johannesburg
+Africa/Kampala Africa/Kampala
+Africa/Khartoum Africa/Khartoum
+Africa/Kigali Africa/Kigali
+Africa/Kinshasa Africa/Kinshasa
+Africa/Lagos Africa/Lagos
+Africa/Libreville Africa/Libreville
+Africa/Lome Africa/Lome
+Africa/Luanda Africa/Luanda
+Africa/Lubumbashi Africa/Lubumbashi
+Africa/Lusaka Africa/Lusaka
+Africa/Malabo Africa/Malabo
+Africa/Maputo Africa/Maputo
+Africa/Maseru Africa/Maseru
+Africa/Mbabane Africa/Mbabane
+Africa/Mogadishu Africa/Mogadishu
+Africa/Monrovia Africa/Monrovia
+Africa/Nairobi Africa/Nairobi
+Africa/Ndjamena Africa/Ndjamena
+Africa/Niamey Africa/Niamey
+Africa/Nouakchott Africa/Nouakchott
+Africa/Ouagadougou Africa/Ouagadougou
+Africa/Porto-Novo Africa/Porto-Novo
+Africa/Sao_Tome Africa/Sao_Tome
+Africa/Timbuktu Africa/Timbuktu
+Africa/Tripoli Africa/Tripoli
+Africa/Tunis Africa/Tunis
+Africa/Windhoek Africa/Windhoek
+America/Adak America/Adak
+America/Anchorage America/Anchorage
+America/Anguilla America/Anguilla
+America/Antigua America/Antigua
+America/Araguaina America/Sao_Paulo
+America/Argentina/Buenos_Aires America/Argentina/Buenos_Aires
+America/Argentina/Catamarca America/Argentina/Catamarca
+America/Argentina/ComodRivadavia America/Argentina/Catamarca
+America/Argentina/Cordoba America/Argentina/Cordoba
+America/Argentina/Jujuy America/Argentina/Jujuy
+America/Argentina/La_Rioja America/Argentina/La_Rioja
+America/Argentina/Mendoza America/Argentina/Mendoza
+America/Argentina/Rio_Gallegos America/Argentina/Rio_Gallegos
+America/Argentina/Salta America/Argentina/Salta
+America/Argentina/San_Juan America/Argentina/San_Juan
+America/Argentina/San_Luis America/Argentina/San_Luis
+America/Argentina/Tucuman America/Argentina/Tucuman
+America/Argentina/Ushuaia America/Argentina/Ushuaia
+America/Aruba America/Aruba
+America/Asuncion America/Asuncion
+America/Atka America/Adak
+America/Barbados America/Barbados
+America/Belize America/Belize
+America/Bogota America/Bogota
+America/Boise America/Denver
+America/Buenos_Aires America/Argentina/Buenos_Aires
+America/Cancun America/Chicago
+America/Caracas America/Caracas
+America/Catamarca America/Argentina/Catamarca
+America/Cayenne America/Cayenne
+America/Cayman America/Cayman
+America/Chicago America/Chicago
+America/Chihuahua America/Denver
+America/Coral_Harbour America/Atikokan
+America/Cordoba America/Argentina/Cordoba
+America/Costa_Rica America/Costa_Rica
+America/Cuiaba America/Cuiaba
+America/Curacao America/Curacao
+America/Dawson America/Los_Angeles
+America/Dawson_Creek America/Dawson_Creek
+America/Denver America/Denver
+America/Detroit America/New_York
+America/Dominica America/Dominica
+America/Edmonton America/Edmonton
+America/El_Salvador America/El_Salvador
+America/Ensenada America/Los_Angeles
+America/Fort_Wayne America/Indiana/Indianapolis
+America/Fortaleza America/Fortaleza
+America/Glace_Bay America/Halifax
+America/Godthab America/Godthab
+America/Goose_Bay America/Thule
+America/Grand_Turk America/Grand_Turk
+America/Grenada America/Grenada
+America/Guadeloupe America/Guadeloupe
+America/Guatemala America/Guatemala
+America/Guayaquil America/Guayaquil
+America/Guyana America/Guyana
+America/Halifax America/Halifax
+America/Havana America/Havana
+America/Indiana/Indianapolis America/Indianapolis
+America/Indianapolis America/Indiana/Indianapolis
+America/Inuvik America/Denver
+America/Iqaluit America/New_York
+America/Jamaica America/Jamaica
+America/Jujuy America/Argentina/Jujuy
+America/Juneau America/Anchorage
+America/Knox_IN America/Indiana/Knox
+America/La_Paz America/La_Paz
+America/Lima America/Lima
+America/Los_Angeles America/Los_Angeles
+America/Louisville America/Kentucky/Louisville
+America/Managua America/Managua
+America/Manaus America/Manaus
+America/Marigot America/Guadeloupe
+America/Martinique America/Martinique
+America/Mazatlan America/Mazatlan
+America/Mendoza America/Argentina/Mendoza
+America/Menominee America/Winnipeg
+America/Mexico_City America/Mexico_City
+America/Miquelon America/Miquelon
+America/Moncton America/Moncton
+America/Montevideo America/Montevideo
+America/Montreal America/Montreal
+America/Montserrat America/Montserrat
+America/Nassau America/Nassau
+America/New_York America/New_York
+America/Nipigon America/New_York
+America/Nome America/Anchorage
+America/Noronha America/Noronha
+America/Panama America/Panama
+America/Pangnirtung America/Thule
+America/Paramaribo America/Paramaribo
+America/Phoenix America/Phoenix
+America/Port-au-Prince America/Port-au-Prince
+America/Port_of_Spain America/Port_of_Spain
+America/Porto_Acre America/Rio_Branco
+America/Puerto_Rico America/Puerto_Rico
+America/Rainy_River America/Chicago
+America/Rankin_Inlet America/Chicago
+America/Regina America/Regina
+America/Rio_Branco America/Rio_Branco
+America/Rosario America/Argentina/Cordoba
+America/Santiago America/Santiago
+America/Santo_Domingo America/Santo_Domingo
+America/Sao_Paulo America/Sao_Paulo
+America/Scoresbysund America/Scoresbysund
+America/Shiprock America/Denver
+America/St_Barthelemy America/Guadeloupe
+America/St_Johns America/St_Johns
+America/St_Kitts America/St_Kitts
+America/St_Lucia America/St_Lucia
+America/St_Thomas America/St_Thomas
+America/St_Vincent America/St_Vincent
+America/Tegucigalpa America/Tegucigalpa
+America/Thule America/Thule
+America/Thunder_Bay America/New_York
+America/Tijuana America/Tijuana
+America/Toronto America/Toronto
+America/Tortola America/Tortola
+America/Vancouver America/Vancouver
+America/Virgin America/St_Thomas
+America/Whitehorse America/Los_Angeles
+America/Winnipeg America/Winnipeg
+America/Yakutat America/Anchorage
+America/Yellowknife America/Denver
+Antarctica/Casey Antarctica/Casey
+Antarctica/DumontDUrville Antarctica/DumontDUrville
+Antarctica/Mawson Antarctica/Mawson
+Antarctica/McMurdo Antarctica/McMurdo
+Antarctica/Palmer Antarctica/Palmer
+Antarctica/South_Pole Antarctica/McMurdo
+Arctic/Longyearbyen Europe/Oslo
+Asia/Aden Asia/Aden
+Asia/Almaty Asia/Almaty
+Asia/Amman Asia/Amman
+Asia/Anadyr Asia/Anadyr
+Asia/Aqtau Asia/Aqtau
+Asia/Aqtobe Asia/Aqtobe
+Asia/Ashkhabad Asia/Ashkhabad
+Asia/Baghdad Asia/Baghdad
+Asia/Bahrain Asia/Bahrain
+Asia/Baku Asia/Baku
+Asia/Bangkok Asia/Bangkok
+Asia/Beirut Asia/Beirut
+Asia/Bishkek Asia/Bishkek
+Asia/Brunei Asia/Brunei
+Asia/Calcutta Asia/Calcutta
+Asia/Chungking Asia/Shanghai
+Asia/Colombo Asia/Colombo
+Asia/Dacca Asia/Dacca
+Asia/Damascus Asia/Damascus
+Asia/Dhaka Asia/Dhaka
+Asia/Dubai Asia/Dubai
+Asia/Dushanbe Asia/Dushanbe
+Asia/Gaza Asia/Amman
+Asia/Harbin Asia/Shanghai
+Asia/Hong_Kong Asia/Hong_Kong
+Asia/Irkutsk Asia/Irkutsk
+Asia/Istanbul Europe/Istanbul
+Asia/Jakarta Asia/Jakarta
+Asia/Jayapura Asia/Jayapura
+Asia/Jerusalem Asia/Jerusalem
+Asia/Kabul Asia/Kabul
+Asia/Kamchatka Asia/Kamchatka
+Asia/Karachi Asia/Karachi
+Asia/Kashgar Asia/Shanghai
+Asia/Katmandu Asia/Katmandu
+Asia/Kolkata Asia/Kolkata
+Asia/Krasnoyarsk Asia/Krasnoyarsk
+Asia/Kuala_Lumpur Asia/Kuala_Lumpur
+Asia/Kuwait Asia/Kuwait
+Asia/Macao Asia/Macao
+Asia/Magadan Asia/Magadan
+Asia/Manila Asia/Manila
+Asia/Muscat Asia/Muscat
+Asia/Nicosia Asia/Nicosia
+Asia/Novosibirsk Asia/Novosibirsk
+Asia/Omsk Asia/Novosibirsk
+Asia/Phnom_Penh Asia/Phnom_Penh
+Asia/Pyongyang Asia/Pyongyang
+Asia/Qatar Asia/Qatar
+Asia/Rangoon Asia/Rangoon
+Asia/Riyadh Asia/Riyadh
+Asia/Saigon Asia/Ho_Chi_Minh
+Asia/Seoul Asia/Seoul
+Asia/Shanghai Asia/Shanghai
+Asia/Singapore Asia/Singapore
+Asia/Taipei Asia/Taipei
+Asia/Tashkent Asia/Tashkent
+Asia/Tbilisi Asia/Tbilisi
+Asia/Tehran Asia/Tehran
+Asia/Tel_Aviv Asia/Jerusalem
+Asia/Thimbu Asia/Thimbu
+Asia/Tokyo Asia/Tokyo
+Asia/Ujung_Pandang Asia/Ujung_Pandang
+Asia/Ulan_Bator Asia/Ulaanbaatar
+Asia/Urumqi Asia/Shanghai
+Asia/Vientiane Asia/Vientiane
+Asia/Vladivostok Asia/Vladivostok
+Asia/Yakutsk Asia/Yakutsk
+Asia/Yekaterinburg Asia/Yekaterinburg
+Asia/Yerevan Asia/Yerevan
+Atlantic/Azores Atlantic/Azores
+Atlantic/Bermuda Atlantic/Bermuda
+Atlantic/Canary Atlantic/Canary
+Atlantic/Cape_Verde Atlantic/Cape_Verde
+Atlantic/Faeroe Atlantic/Faeroe
+Atlantic/Jan_Mayen Atlantic/Jan_Mayen
+Atlantic/Madeira Europe/London
+Atlantic/Reykjavik Atlantic/Reykjavik
+Atlantic/South_Georgia Atlantic/South_Georgia
+Atlantic/St_Helena Atlantic/St_Helena
+Atlantic/Stanley Atlantic/Stanley
+Australia/ACT Australia/Sydney
+Australia/Adelaide Australia/Adelaide
+Australia/Brisbane Australia/Brisbane
+Australia/Broken_Hill Australia/Broken_Hill
+Australia/Canberra Australia/Sydney
+Australia/Darwin Australia/Darwin
+Australia/Hobart Australia/Hobart
+Australia/LHI Australia/Lord_Howe
+Australia/Lord_Howe Australia/Lord_Howe
+Australia/Melbourne Australia/Sydney
+Australia/NSW Australia/Sydney
+Australia/North Australia/Darwin
+Australia/Perth Australia/Perth
+Australia/Queensland Australia/Brisbane
+Australia/South Australia/Adelaide
+Australia/Sydney Australia/Sydney
+Australia/Tasmania Australia/Hobart
+Australia/Victoria Australia/Melbourne
+Australia/West Australia/Perth
+Australia/Yancowinna Australia/Broken_Hill
+BRT3BRST America/Sao_Paulo
+BST11 Pacific/Apia
+BST11BDT Pacific/Apia
+Brazil/Acre America/Rio_Branco
+Brazil/DeNoronha America/Noronha
+Brazil/East America/Sao_Paulo
+Brazil/West America/Manaus
+CET Europe/Paris
+CET-1CEST Europe/Paris
+CET-1CEST-2 Europe/Berlin
+CET-1CET-2 Europe/Paris
+CST6 America/Costa_Rica
+CST6CDT America/Chicago
+CUT0 UTC
+CUT0GDT Europe/London
+Canada/Atlantic America/Halifax
+Canada/Central America/Winnipeg
+Canada/East-Saskatchewan America/Regina
+Canada/Eastern America/Montreal
+Canada/Mountain America/Edmonton
+Canada/Newfoundland America/St_Johns
+Canada/Pacific America/Vancouver
+Canada/Saskatchewan America/Regina
+Canada/Yukon America/Whitehorse
+Chile/Continental America/Santiago
+Chile/EasterIsland Pacific/Easter
+Cuba America/Havana
+EET Europe/Istanbul
+EET-10 Australia/Brisbane
+EET-10EETDT Australia/Sydney
+EST America/Indianapolis
+EST5 America/Indianapolis
+EST5EDT America/New_York
+Egypt Africa/Cairo
+Eire Europe/Dublin
+Etc/GMT GMT
+Etc/GMT0 GMT
+Etc/Greenwich GMT
+Etc/UCT UTC
+Etc/UTC UTC
+Etc/Universal UTC
+Etc/Zulu UTC
+Europe/Amsterdam Europe/Amsterdam
+Europe/Andorra Europe/Andorra
+Europe/Athens Europe/Athens
+Europe/Belfast Europe/London
+Europe/Belgrade Europe/Belgrade
+Europe/Berlin Europe/Berlin
+Europe/Bratislava Europe/Prague
+Europe/Brussels Europe/Brussels
+Europe/Bucharest Europe/Bucharest
+Europe/Budapest Europe/Budapest
+Europe/Chisinau Europe/Chisinau
+Europe/Copenhagen Europe/Copenhagen
+Europe/Dublin Europe/Dublin
+Europe/Gibraltar Europe/Gibraltar
+Europe/Guernsey Europe/London
+Europe/Helsinki Europe/Helsinki
+Europe/Isle_of_Man Europe/London
+Europe/Istanbul Europe/Istanbul
+Europe/Jersey Europe/London
+Europe/Kaliningrad Europe/Kaliningrad
+Europe/Kiev Europe/Kiev
+Europe/Lisbon Europe/Lisbon
+Europe/Ljubljana Europe/Belgrade
+Europe/London Europe/London
+Europe/Luxembourg Europe/Luxembourg
+Europe/Madrid Europe/Madrid
+Europe/Malta Europe/Malta
+Europe/Mariehamn Europe/Helsinki
+Europe/Minsk Europe/Minsk
+Europe/Monaco Europe/Monaco
+Europe/Moscow Europe/Moscow
+Europe/Nicosia Asia/Nicosia
+Europe/Oslo Europe/Oslo
+Europe/Paris Europe/Paris
+Europe/Podgorica Europe/Belgrade
+Europe/Prague Europe/Prague
+Europe/Riga Europe/Riga
+Europe/Rome Europe/Rome
+Europe/Samara Europe/Samara
+Europe/San_Marino Europe/Rome
+Europe/Sarajevo Europe/Belgrade
+Europe/Simferopol Europe/Simferopol
+Europe/Skopje Europe/Belgrade
+Europe/Sofia Europe/Sofia
+Europe/Stockholm Europe/Stockholm
+Europe/Tallinn Europe/Tallinn
+Europe/Tirane Europe/Tirane
+Europe/Vaduz Europe/Vaduz
+Europe/Vatican Europe/Rome
+Europe/Vienna Europe/Vienna
+Europe/Vilnius Europe/Vilnius
+Europe/Warsaw Europe/Warsaw
+Europe/Zagreb Europe/Belgrade
+Europe/Zurich Europe/Zurich
+FALKST2 Atlantic/South_Georgia
+FALKST2FALKDT Atlantic/South_Georgia
+Factory GMT
+GB Europe/London
+GB-Eire Europe/London
+GMT GMT
+GMT0 GMT
+GMT0BST Europe/London
+GMT0BST-1 Europe/London
+GMT0WET Europe/Lisbon
+GRNLNDST3 America/Buenos_Aires
+GRNLNDST3GRNLNDDT America/Godthab
+Greenwich GMT
+HST Pacific/Honolulu
+HST10 Pacific/Honolulu
+HST10HDT America/Adak
+Hongkong Asia/Hong_Kong
+Iceland Atlantic/Reykjavik
+Indian/Antananarivo Indian/Antananarivo
+Indian/Chagos Indian/Chagos
+Indian/Christmas Indian/Christmas
+Indian/Cocos Indian/Cocos
+Indian/Comoro Indian/Comoro
+Indian/Kerguelen Indian/Kerguelen
+Indian/Mahe Indian/Mahe
+Indian/Maldives Indian/Maldives
+Indian/Mauritius Indian/Mauritius
+Indian/Mayotte Indian/Mayotte
+Indian/Reunion Indian/Reunion
+Iran Asia/Tehran
+Israel Asia/Jerusalem
+JST-9 Asia/Tokyo
+JST-9JSTDT Asia/Tokyo
+Jamaica America/Jamaica
+Japan Asia/Tokyo
+KORST-9 Asia/Seoul
+KORST-9KORDT Asia/Seoul
+Kwajalein Pacific/Kwajalein
+Libya Africa/Tripoli
+MEST-2 Europe/Istanbul
+MEST-2MEDT Europe/Istanbul
+MEST-3 Asia/Riyadh
+MEST-3MEDT Europe/Moscow
+MET Europe/Paris
+MET-11 Pacific/Guadalcanal
+MET-11METDT Asia/Magadan
+MET-1MEST Europe/Paris
+MET-1MST-2 Europe/Berlin
+MEZ-1MESZ Europe/Berlin
+MEZ-1MESZ-2 Europe/Berlin
+MSK-3MSD Europe/Moscow
+MST America/Phoenix
+MST7 America/Phoenix
+MST7MDT America/Denver
+Mexico/BajaNorte America/Tijuana
+Mexico/BajaSur America/Mazatlan
+Mexico/General America/Mexico_City
+Mideast/Riyadh87 Asia/Riyadh87
+Mideast/Riyadh88 Asia/Riyadh88
+Mideast/Riyadh89 Asia/Riyadh89
+NFT-1 Africa/Algiers
+NFT-1DFT Europe/Paris
+NFT-1DST Europe/Paris
+NZ Pacific/Auckland
+NZ-CHAT Pacific/Chatham
+NZST-12 Pacific/Fiji
+NZST-12NZDT Pacific/Auckland
+Navajo America/Denver
+PAKST-5 Asia/Karachi
+PAKST-5PAKDT Asia/Yekaterinburg
+PRC Asia/Shanghai
+PST8 Pacific/Pitcairn
+PST8PDT America/Los_Angeles
+PST8PDT7 America/Tijuana
+Pacific/Apia Pacific/Apia
+Pacific/Auckland Pacific/Auckland
+Pacific/Chatham Pacific/Chatham
+Pacific/Easter Pacific/Easter
+Pacific/Efate Pacific/Efate
+Pacific/Enderbury Pacific/Enderbury
+Pacific/Fakaofo Pacific/Fakaofo
+Pacific/Fiji Pacific/Fiji
+Pacific/Funafuti Pacific/Funafuti
+Pacific/Galapagos Pacific/Galapagos
+Pacific/Gambier Pacific/Gambier
+Pacific/Guadalcanal Pacific/Guadalcanal
+Pacific/Guam Pacific/Guam
+Pacific/Honolulu Pacific/Honolulu
+Pacific/Kiritimati Pacific/Kiritimati
+Pacific/Kosrae Pacific/Kosrae
+Pacific/Majuro Pacific/Majuro
+Pacific/Marquesas Pacific/Marquesas
+Pacific/Nauru Pacific/Nauru
+Pacific/Niue Pacific/Niue
+Pacific/Norfolk Pacific/Norfolk
+Pacific/Noumea Pacific/Noumea
+Pacific/Pago_Pago Pacific/Pago_Pago
+Pacific/Palau Pacific/Palau
+Pacific/Pitcairn Pacific/Pitcairn
+Pacific/Ponape Pacific/Ponape
+Pacific/Port_Moresby Pacific/Port_Moresby
+Pacific/Rarotonga Pacific/Rarotonga
+Pacific/Saipan Pacific/Saipan
+Pacific/Samoa Pacific/Pago_Pago
+Pacific/Tahiti Pacific/Tahiti
+Pacific/Tarawa Pacific/Tarawa
+Pacific/Tongatapu Pacific/Tongatapu
+Pacific/Truk Pacific/Truk
+Pacific/Wake Pacific/Wake
+Pacific/Wallis Pacific/Wallis
+Poland Europe/Warsaw
+Portugal Europe/Lisbon
+ROC Asia/Taipei
+ROK Asia/Seoul
+SAUST-3 Asia/Riyadh
+SAUST-3SAUDT Europe/Moscow
+Singapore Asia/Singapore
+SystemV/AST4ADT America/Thule
+SystemV/CST6CDT America/Chicago
+SystemV/EST5EDT America/New_York
+SystemV/MST7MDT America/Denver
+SystemV/PST8PDT America/Los_Angeles
+SystemV/YST9YDT America/Anchorage
+TAIST-8 Asia/Taipei
+TAIST-8TAIDT Asia/Irkutsk
+TASHST-6 Asia/Dacca
+TASHST-6TASHDT Asia/Novosibirsk
+THAIST-7 Asia/Bangkok
+THAIST-7THAIDT Asia/Krasnoyarsk
+Turkey Europe/Istanbul
+UCT UTC
+US/Alaska America/Anchorage
+US/Aleutian America/Adak
+US/Arizona America/Phoenix
+US/Central America/Chicago
+US/East-Indiana America/Indiana/Indianapolis
+US/Eastern America/New_York
+US/Hawaii Pacific/Honolulu
+US/Indiana-Starke America/Indiana/Knox
+US/Michigan America/New_York
+US/Mountain America/Denver
+US/Pacific America/Los_Angeles
+US/Pacific-New America/Los_Angeles
+US/Samoa Pacific/Pago_Pago
+USAST-2 Africa/Johannesburg
+USAST-2USADT Europe/Istanbul
+UTC UTC
+UYT3UYST America/Montevideo
+Universal UTC
+W-SU Europe/Moscow
+WAUST-8 Australia/Perth
+WAUST-8WAUDT Australia/Perth
+WET WET
+WET-2 Africa/Johannesburg
+WET-2WET Europe/Helsinki
+WST-4 Asia/Dubai
+WST-4WDT Europe/Samara
+Zulu UTC
diff --git a/jdk/src/macosx/classes/sun/font/CFontManager.java b/jdk/src/macosx/classes/sun/font/CFontManager.java
index a5f36154d64..ad2bfab62ba 100644
--- a/jdk/src/macosx/classes/sun/font/CFontManager.java
+++ b/jdk/src/macosx/classes/sun/font/CFontManager.java
@@ -27,6 +27,8 @@ package sun.font;
import java.awt.*;
import java.io.File;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
@@ -38,6 +40,7 @@ import javax.swing.plaf.FontUIResource;
import sun.awt.FontConfiguration;
import sun.awt.HeadlessToolkit;
+import sun.misc.ThreadGroupUtils;
import sun.lwawt.macosx.*;
public class CFontManager extends SunFontManager {
@@ -215,24 +218,19 @@ public class CFontManager extends SunFontManager {
});
}
};
- java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction
@@ -2448,7 +2447,7 @@ public final class Files {
}
/**
- * Used by isReadbale, isWritable, isExecutable to test access to a file.
+ * Used by isReadable, isWritable, isExecutable to test access to a file.
*/
private static boolean isAccessible(Path path, AccessMode... modes) {
try {
diff --git a/jdk/src/share/classes/java/nio/file/spi/FileSystemProvider.java b/jdk/src/share/classes/java/nio/file/spi/FileSystemProvider.java
index bed84168cef..def1cca7a57 100644
--- a/jdk/src/share/classes/java/nio/file/spi/FileSystemProvider.java
+++ b/jdk/src/share/classes/java/nio/file/spi/FileSystemProvider.java
@@ -81,7 +81,7 @@ public abstract class FileSystemProvider {
// installed providers
private static volatile List installedProviders;
- // used to avoid recursive loading of instaled providers
+ // used to avoid recursive loading of installed providers
private static boolean loadingProviders = false;
private static Void checkPermission() {
diff --git a/jdk/src/share/classes/java/security/Provider.java b/jdk/src/share/classes/java/security/Provider.java
index 05f670c29bd..e8c7a081b5a 100644
--- a/jdk/src/share/classes/java/security/Provider.java
+++ b/jdk/src/share/classes/java/security/Provider.java
@@ -1332,7 +1332,7 @@ public abstract class Provider extends Properties {
addEngine("SSLContext", false, null);
addEngine("TrustManagerFactory", false, null);
// JGSS
- addEngine("GssApiMechanism", true, "sun.security.jgss.GSSCaller");
+ addEngine("GssApiMechanism", false, null);
// SASL
addEngine("SaslClientFactory", false, null);
addEngine("SaslServerFactory", false, null);
diff --git a/jdk/src/share/classes/java/time/temporal/IsoFields.java b/jdk/src/share/classes/java/time/temporal/IsoFields.java
index 8d9cc84f3c4..70c3ffb39b7 100644
--- a/jdk/src/share/classes/java/time/temporal/IsoFields.java
+++ b/jdk/src/share/classes/java/time/temporal/IsoFields.java
@@ -535,11 +535,17 @@ public final class IsoFields {
if (isSupportedBy(temporal) == false) {
throw new UnsupportedTemporalTypeException("Unsupported field: WeekBasedYear");
}
- int newVal = range().checkValidIntValue(newValue, WEEK_BASED_YEAR); // strict check
+ int newWby = range().checkValidIntValue(newValue, WEEK_BASED_YEAR); // strict check
LocalDate date = LocalDate.from(temporal);
+ int dow = date.get(DAY_OF_WEEK);
int week = getWeek(date);
- date = date.withDayOfYear(180).withYear(newVal).with(WEEK_OF_WEEK_BASED_YEAR, week);
- return (R) date.with(date);
+ if (week == 53 && getWeekRange(newWby) == 52) {
+ week = 52;
+ }
+ LocalDate resolved = LocalDate.of(newWby, 1, 4); // 4th is guaranteed to be in week one
+ int days = (dow - resolved.get(DAY_OF_WEEK)) + ((week - 1) * 7);
+ resolved = resolved.plusDays(days);
+ return (R) temporal.with(resolved);
}
@Override
public String toString() {
@@ -577,12 +583,16 @@ public final class IsoFields {
private static ValueRange getWeekRange(LocalDate date) {
int wby = getWeekBasedYear(date);
- date = date.withDayOfYear(1).withYear(wby);
+ return ValueRange.of(1, getWeekRange(wby));
+ }
+
+ private static int getWeekRange(int wby) {
+ LocalDate date = LocalDate.of(wby, 1, 1);
// 53 weeks if standard year starts on Thursday, or Wed in a leap year
if (date.getDayOfWeek() == THURSDAY || (date.getDayOfWeek() == WEDNESDAY && date.isLeapYear())) {
- return ValueRange.of(1, 53);
+ return 53;
}
- return ValueRange.of(1, 52);
+ return 52;
}
private static int getWeek(LocalDate date) {
diff --git a/jdk/src/share/classes/java/time/temporal/WeekFields.java b/jdk/src/share/classes/java/time/temporal/WeekFields.java
index 3aa362cea60..faee176d3e7 100644
--- a/jdk/src/share/classes/java/time/temporal/WeekFields.java
+++ b/jdk/src/share/classes/java/time/temporal/WeekFields.java
@@ -700,7 +700,7 @@ public final class WeekFields implements Serializable {
* @see WeekFields#weekOfWeekBasedYear()
*/
static ComputedDayOfField ofWeekOfWeekBasedYearField(WeekFields weekDef) {
- return new ComputedDayOfField("WeekOfWeekBasedYear", weekDef, WEEKS, IsoFields.WEEK_BASED_YEARS, WEEK_OF_YEAR_RANGE);
+ return new ComputedDayOfField("WeekOfWeekBasedYear", weekDef, WEEKS, IsoFields.WEEK_BASED_YEARS, WEEK_OF_WEEK_BASED_YEAR_RANGE);
}
/**
@@ -753,6 +753,7 @@ public final class WeekFields implements Serializable {
private static final ValueRange DAY_OF_WEEK_RANGE = ValueRange.of(1, 7);
private static final ValueRange WEEK_OF_MONTH_RANGE = ValueRange.of(0, 1, 4, 6);
private static final ValueRange WEEK_OF_YEAR_RANGE = ValueRange.of(0, 1, 52, 54);
+ private static final ValueRange WEEK_OF_WEEK_BASED_YEAR_RANGE = ValueRange.of(1, 52, 53);
@Override
public long getFrom(TemporalAccessor temporal) {
diff --git a/jdk/src/share/classes/java/util/Locale.java b/jdk/src/share/classes/java/util/Locale.java
index 2b16d993434..fddf8de5fbd 100644
--- a/jdk/src/share/classes/java/util/Locale.java
+++ b/jdk/src/share/classes/java/util/Locale.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -3040,6 +3040,7 @@ public final class Locale implements Cloneable, Serializable {
* 2616
* @param map a map containing information to customize language ranges
* @return a Language Priority List with customization. The list is
+ * modifiable.
* @throws NullPointerException if {@code ranges} is null
* @throws IllegalArgumentException if a language range or a weight
* found in the given {@code ranges} is ill-formed
diff --git a/jdk/src/share/classes/java/util/Random.java b/jdk/src/share/classes/java/util/Random.java
index 069242c6e30..1061b59361e 100644
--- a/jdk/src/share/classes/java/util/Random.java
+++ b/jdk/src/share/classes/java/util/Random.java
@@ -874,7 +874,7 @@ class Random implements java.io.Serializable {
* (inclusive) and one (exclusive).
*
*
A pseudorandom {@code double} value is generated as if it's the result
- * of calling the method {@link #nextDouble()}}.
+ * of calling the method {@link #nextDouble()}.
*
* @param streamSize the number of values to generate
* @return a stream of {@code double} values
@@ -897,7 +897,7 @@ class Random implements java.io.Serializable {
* (exclusive).
*
*
A pseudorandom {@code double} value is generated as if it's the result
- * of calling the method {@link #nextDouble()}}.
+ * of calling the method {@link #nextDouble()}.
*
* @implNote This method is implemented to be equivalent to {@code
* doubles(Long.MAX_VALUE)}.
diff --git a/jdk/src/share/classes/java/util/ServiceLoader.java b/jdk/src/share/classes/java/util/ServiceLoader.java
index 8c887ebeb07..49b1b58d477 100644
--- a/jdk/src/share/classes/java/util/ServiceLoader.java
+++ b/jdk/src/share/classes/java/util/ServiceLoader.java
@@ -382,7 +382,7 @@ public final class ServiceLoader
return p;
} catch (Throwable x) {
fail(service,
- "Provider " + cn + " could not be instantiated: " + x,
+ "Provider " + cn + " could not be instantiated",
x);
}
throw new Error(); // This cannot happen
diff --git a/jdk/src/share/classes/java/util/jar/JarVerifier.java b/jdk/src/share/classes/java/util/jar/JarVerifier.java
index 3c9a1eb2c03..0c24af26f28 100644
--- a/jdk/src/share/classes/java/util/jar/JarVerifier.java
+++ b/jdk/src/share/classes/java/util/jar/JarVerifier.java
@@ -676,6 +676,8 @@ class JarVerifier {
} else {
matchUnsigned = true;
}
+ } else {
+ matchUnsigned = true;
}
}
@@ -778,23 +780,7 @@ class JarVerifier {
// true if file is part of the signature mechanism itself
static boolean isSigningRelated(String name) {
- name = name.toUpperCase(Locale.ENGLISH);
- if (!name.startsWith("META-INF/")) {
- return false;
- }
- name = name.substring(9);
- if (name.indexOf('/') != -1) {
- return false;
- }
- if (name.endsWith(".DSA")
- || name.endsWith(".RSA")
- || name.endsWith(".SF")
- || name.endsWith(".EC")
- || name.startsWith("SIG-")
- || name.equals("MANIFEST.MF")) {
- return true;
- }
- return false;
+ return SignatureFileVerifier.isSigningRelated(name);
}
private Enumeration unsignedEntryNames(JarFile jar) {
diff --git a/jdk/src/share/classes/java/util/logging/LogManager.java b/jdk/src/share/classes/java/util/logging/LogManager.java
index 993c7d513d8..669045d60eb 100644
--- a/jdk/src/share/classes/java/util/logging/LogManager.java
+++ b/jdk/src/share/classes/java/util/logging/LogManager.java
@@ -464,7 +464,7 @@ public class LogManager {
Logger result = getLogger(name);
if (result == null) {
// only allocate the new logger once
- Logger newLogger = new Logger(name, resourceBundleName, caller, this);
+ Logger newLogger = new Logger(name, resourceBundleName, caller, this, false);
do {
if (addLogger(newLogger)) {
// We successfully added the new Logger that we
@@ -511,13 +511,13 @@ public class LogManager {
} while (logger == null);
// LogManager will set the sysLogger's handlers via LogManager.addLogger method.
- if (logger != sysLogger && sysLogger.getHandlers().length == 0) {
+ if (logger != sysLogger && sysLogger.accessCheckedHandlers().length == 0) {
// if logger already exists but handlers not set
final Logger l = logger;
AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Void run() {
- for (Handler hdl : l.getHandlers()) {
+ for (Handler hdl : l.accessCheckedHandlers()) {
sysLogger.addHandler(hdl);
}
return null;
@@ -835,7 +835,7 @@ public class LogManager {
Logger result = findLogger(name);
if (result == null) {
// only allocate the new system logger once
- Logger newLogger = new Logger(name, resourceBundleName, null, getOwner());
+ Logger newLogger = new Logger(name, resourceBundleName, null, getOwner(), true);
do {
if (addLocalLogger(newLogger)) {
// We successfully added the new Logger that we
@@ -1527,7 +1527,7 @@ public class LogManager {
// We do not call the protected Logger two args constructor here,
// to avoid calling LogManager.getLogManager() from within the
// RootLogger constructor.
- super("", null, null, LogManager.this);
+ super("", null, null, LogManager.this, true);
}
@Override
@@ -1550,9 +1550,9 @@ public class LogManager {
}
@Override
- public Handler[] getHandlers() {
+ Handler[] accessCheckedHandlers() {
initializeGlobalHandlers();
- return super.getHandlers();
+ return super.accessCheckedHandlers();
}
}
diff --git a/jdk/src/share/classes/java/util/logging/Logger.java b/jdk/src/share/classes/java/util/logging/Logger.java
index 662c7185991..d3050007806 100644
--- a/jdk/src/share/classes/java/util/logging/Logger.java
+++ b/jdk/src/share/classes/java/util/logging/Logger.java
@@ -277,6 +277,7 @@ public class Logger {
private volatile Level levelObject;
private volatile int levelValue; // current effective level value
private WeakReference callersClassLoaderRef;
+ private final boolean isSystemLogger;
/**
* GLOBAL_LOGGER_NAME is a name for the global logger.
@@ -370,11 +371,12 @@ public class Logger {
* no corresponding resource can be found.
*/
protected Logger(String name, String resourceBundleName) {
- this(name, resourceBundleName, null, LogManager.getLogManager());
+ this(name, resourceBundleName, null, LogManager.getLogManager(), false);
}
- Logger(String name, String resourceBundleName, Class> caller, LogManager manager) {
+ Logger(String name, String resourceBundleName, Class> caller, LogManager manager, boolean isSystemLogger) {
this.manager = manager;
+ this.isSystemLogger = isSystemLogger;
setupResourceInfo(resourceBundleName, caller);
this.name = name;
levelValue = Level.INFO.intValue();
@@ -401,6 +403,7 @@ public class Logger {
private Logger(String name) {
// The manager field is not initialized here.
this.name = name;
+ this.isSystemLogger = true;
levelValue = Level.INFO.intValue();
}
@@ -635,7 +638,7 @@ public class Logger {
// cleanup some Loggers that have been GC'ed
manager.drainLoggerRefQueueBounded();
Logger result = new Logger(null, resourceBundleName,
- Reflection.getCallerClass(), manager);
+ Reflection.getCallerClass(), manager, false);
result.anonymous = true;
Logger root = manager.getLogger("");
result.doSetParent(root);
@@ -727,15 +730,23 @@ public class Logger {
Logger logger = this;
while (logger != null) {
- for (Handler handler : logger.getHandlers()) {
+ final Handler[] loggerHandlers = isSystemLogger
+ ? logger.accessCheckedHandlers()
+ : logger.getHandlers();
+
+ for (Handler handler : loggerHandlers) {
handler.publish(record);
}
- if (!logger.getUseParentHandlers()) {
+ final boolean useParentHdls = isSystemLogger
+ ? logger.useParentHandlers
+ : logger.getUseParentHandlers();
+
+ if (!useParentHdls) {
break;
}
- logger = logger.getParent();
+ logger = isSystemLogger ? logger.parent : logger.getParent();
}
}
@@ -1762,6 +1773,12 @@ public class Logger {
* @return an array of all registered Handlers
*/
public Handler[] getHandlers() {
+ return accessCheckedHandlers();
+ }
+
+ // This method should ideally be marked final - but unfortunately
+ // it needs to be overridden by LogManager.RootLogger
+ Handler[] accessCheckedHandlers() {
return handlers.toArray(emptyHandlers);
}
@@ -2149,12 +2166,14 @@ public class Logger {
if (trb.userBundle != null) {
return trb;
}
- final String rbName = target.getResourceBundleName();
+ final String rbName = isSystemLogger
+ ? trb.resourceBundleName
+ : target.getResourceBundleName();
if (rbName != null) {
return LoggerBundle.get(rbName,
findResourceBundle(rbName, true));
}
- target = target.getParent();
+ target = isSystemLogger ? target.parent : target.getParent();
}
return NO_RESOURCE_BUNDLE;
}
diff --git a/jdk/src/share/classes/java/util/logging/Logging.java b/jdk/src/share/classes/java/util/logging/Logging.java
index 740a533063d..88624fc83e2 100644
--- a/jdk/src/share/classes/java/util/logging/Logging.java
+++ b/jdk/src/share/classes/java/util/logging/Logging.java
@@ -87,7 +87,7 @@ class Logging implements LoggingMXBean {
Logger logger = logManager.getLogger(loggerName);
if (logger == null) {
throw new IllegalArgumentException("Logger " + loggerName +
- "does not exist");
+ " does not exist");
}
Level level = null;
diff --git a/jdk/src/share/classes/javax/naming/NameImpl.java b/jdk/src/share/classes/javax/naming/NameImpl.java
index f9643054dfe..65a67677677 100644
--- a/jdk/src/share/classes/javax/naming/NameImpl.java
+++ b/jdk/src/share/classes/javax/naming/NameImpl.java
@@ -232,7 +232,7 @@ class NameImpl {
syntaxDirection = FLAT;
} else {
throw new IllegalArgumentException(syntaxDirectionStr +
- "is not a valid value for the jndi.syntax.direction property");
+ " is not a valid value for the jndi.syntax.direction property");
}
if (syntaxDirection != FLAT) {
diff --git a/jdk/src/share/classes/javax/script/ScriptEngineManager.java b/jdk/src/share/classes/javax/script/ScriptEngineManager.java
index 83cb9f0137c..b2af53e5bc3 100644
--- a/jdk/src/share/classes/javax/script/ScriptEngineManager.java
+++ b/jdk/src/share/classes/javax/script/ScriptEngineManager.java
@@ -81,23 +81,28 @@ public class ScriptEngineManager {
nameAssociations = new HashMap();
extensionAssociations = new HashMap();
mimeTypeAssociations = new HashMap();
- AccessController.doPrivileged(new PrivilegedAction() {
- public Object run() {
- initEngines(loader);
- return null;
- }
- });
+ initEngines(loader);
+ }
+
+ private ServiceLoader getServiceLoader(final ClassLoader loader) {
+ if (loader != null) {
+ return ServiceLoader.load(ScriptEngineFactory.class, loader);
+ } else {
+ return ServiceLoader.loadInstalled(ScriptEngineFactory.class);
+ }
}
private void initEngines(final ClassLoader loader) {
Iterator itr = null;
try {
- ServiceLoader sl;
- if (loader != null) {
- sl = ServiceLoader.load(ScriptEngineFactory.class, loader);
- } else {
- sl = ServiceLoader.loadInstalled(ScriptEngineFactory.class);
- }
+ ServiceLoader sl = AccessController.doPrivileged(
+ new PrivilegedAction>() {
+ @Override
+ public ServiceLoader run() {
+ return getServiceLoader(loader);
+ }
+ });
+
itr = sl.iterator();
} catch (ServiceConfigurationError err) {
System.err.println("Can't find ScriptEngineFactory providers: " +
diff --git a/jdk/src/share/classes/javax/security/auth/Subject.java b/jdk/src/share/classes/javax/security/auth/Subject.java
index 23197b79935..2c9e8b8083f 100644
--- a/jdk/src/share/classes/javax/security/auth/Subject.java
+++ b/jdk/src/share/classes/javax/security/auth/Subject.java
@@ -959,14 +959,30 @@ public final class Subject implements java.io.Serializable {
/**
* Reads this object from a stream (i.e., deserializes it)
*/
+ @SuppressWarnings("unchecked")
private void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException {
- s.defaultReadObject();
+ ObjectInputStream.GetField gf = s.readFields();
+
+ readOnly = gf.get("readOnly", false);
+
+ Set inputPrincs = (Set)gf.get("principals", null);
// Rewrap the principals into a SecureSet
- principals = Collections.synchronizedSet(new SecureSet
- (this, PRINCIPAL_SET, principals));
+ if (inputPrincs == null) {
+ throw new NullPointerException
+ (ResourcesMgr.getString("invalid.null.input.s."));
+ }
+ try {
+ principals = Collections.synchronizedSet(new SecureSet
+ (this, PRINCIPAL_SET, inputPrincs));
+ } catch (NullPointerException npe) {
+ // Sometimes people deserialize the principals set only.
+ // Subject is not accessible, so just don't fail.
+ principals = Collections.synchronizedSet
+ (new SecureSet(this, PRINCIPAL_SET));
+ }
// The Credential {@code Set} is not serialized, but we do not
// want the default deserialization routine to set it to null.
diff --git a/jdk/src/share/classes/javax/sql/rowset/RowSetProvider.java b/jdk/src/share/classes/javax/sql/rowset/RowSetProvider.java
index 654bb88ea24..e8c10c0a1a2 100644
--- a/jdk/src/share/classes/javax/sql/rowset/RowSetProvider.java
+++ b/jdk/src/share/classes/javax/sql/rowset/RowSetProvider.java
@@ -28,8 +28,11 @@ package javax.sql.rowset;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.sql.SQLException;
+import java.util.PropertyPermission;
import java.util.ServiceConfigurationError;
import java.util.ServiceLoader;
+import javax.sql.rowset.spi.SyncFactoryException;
+import sun.reflect.misc.ReflectUtil;
/**
* A factory API that enables applications to obtain a
@@ -129,15 +132,11 @@ public class RowSetProvider {
factoryClassName = getSystemProperty(ROWSET_FACTORY_NAME);
if (factoryClassName != null) {
trace("Found system property, value=" + factoryClassName);
- factory = (RowSetFactory) getFactoryClass(factoryClassName, null, true).newInstance();
+ factory = (RowSetFactory) ReflectUtil.newInstance(getFactoryClass(factoryClassName, null, true));
}
- } catch (ClassNotFoundException e) {
- throw new SQLException(
- "RowSetFactory: " + factoryClassName + " not found", e);
- } catch (Exception e) {
- throw new SQLException(
- "RowSetFactory: " + factoryClassName + " could not be instantiated: " + e,
- e);
+ } catch (Exception e) {
+ throw new SQLException( "RowSetFactory: " + factoryClassName +
+ " could not be instantiated: ", e);
}
// Check to see if we found the RowSetFactory via a System property
@@ -182,6 +181,16 @@ public class RowSetProvider {
throws SQLException {
trace("***In newInstance()");
+
+ if(factoryClassName == null) {
+ throw new SQLException("Error: factoryClassName cannot be null");
+ }
+ try {
+ ReflectUtil.checkPackageAccess(factoryClassName);
+ } catch (java.security.AccessControlException e) {
+ throw new SQLException("Access Exception",e);
+ }
+
try {
Class> providerClass = getFactoryClass(factoryClassName, cl, false);
RowSetFactory instance = (RowSetFactory) providerClass.newInstance();
@@ -291,8 +300,9 @@ public class RowSetProvider {
public String run() {
return System.getProperty(propName);
}
- });
+ }, null, new PropertyPermission(propName, "read"));
} catch (SecurityException se) {
+ trace("error getting " + propName + ": "+ se);
if (debug) {
se.printStackTrace();
}
diff --git a/jdk/src/share/classes/javax/sql/rowset/serial/SQLInputImpl.java b/jdk/src/share/classes/javax/sql/rowset/serial/SQLInputImpl.java
index 95a9938a007..27a7d200341 100644
--- a/jdk/src/share/classes/javax/sql/rowset/serial/SQLInputImpl.java
+++ b/jdk/src/share/classes/javax/sql/rowset/serial/SQLInputImpl.java
@@ -27,6 +27,7 @@ package javax.sql.rowset.serial;
import java.sql.*;
import java.util.Arrays;
import java.util.Map;
+import sun.reflect.misc.ReflectUtil;
/**
* An input stream used for custom mapping user-defined types (UDTs).
@@ -476,13 +477,9 @@ public class SQLInputImpl implements SQLInput {
// create new instance of the class
SQLData obj = null;
try {
- obj = (SQLData)c.newInstance();
- } catch (java.lang.InstantiationException ex) {
- throw new SQLException("Unable to instantiate: " +
- ex.getMessage());
- } catch (java.lang.IllegalAccessException ex) {
- throw new SQLException("Unable to instantiate: " +
- ex.getMessage());
+ obj = (SQLData)ReflectUtil.newInstance(c);
+ } catch (Exception ex) {
+ throw new SQLException("Unable to Instantiate: ", ex);
}
// get the attributes from the struct
Object attribs[] = s.getAttributes(map);
diff --git a/jdk/src/share/classes/javax/sql/rowset/spi/SyncFactory.java b/jdk/src/share/classes/javax/sql/rowset/spi/SyncFactory.java
index f1a5eedf1f9..a4b757941da 100644
--- a/jdk/src/share/classes/javax/sql/rowset/spi/SyncFactory.java
+++ b/jdk/src/share/classes/javax/sql/rowset/spi/SyncFactory.java
@@ -37,8 +37,11 @@ import java.io.IOException;
import java.io.FileNotFoundException;
import java.security.AccessController;
import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
import javax.naming.*;
+import sun.reflect.misc.ReflectUtil;
/**
* The Service Provider Interface (SPI) mechanism that generates SyncProvider
@@ -329,7 +332,7 @@ public class SyncFactory {
// Local implementation class names and keys from Properties
// file, translate names into Class objects using Class.forName
// and store mappings
- Properties properties = new Properties();
+ final Properties properties = new Properties();
if (implementations == null) {
implementations = new Hashtable<>();
@@ -356,10 +359,11 @@ public class SyncFactory {
public String run() {
return System.getProperty("rowset.properties");
}
- }, null, new PropertyPermission("rowset.properties","read"));
+ }, null, new PropertyPermission("rowset.properties", "read"));
} catch (Exception ex) {
+ System.out.println("errorget rowset.properties: " + ex);
strRowsetProperties = null;
- }
+ };
if (strRowsetProperties != null) {
// Load user's implementation of SyncProvider
@@ -380,14 +384,27 @@ public class SyncFactory {
ClassLoader cl = Thread.currentThread().getContextClassLoader();
- try (InputStream stream =
- (cl == null) ? ClassLoader.getSystemResourceAsStream(ROWSET_PROPERTIES)
- : cl.getResourceAsStream(ROWSET_PROPERTIES)) {
- if (stream == null) {
- throw new SyncFactoryException(
- "Resource " + ROWSET_PROPERTIES + " not found");
+ try {
+ AccessController.doPrivileged((PrivilegedExceptionAction) () -> {
+ try (InputStream stream = (cl == null) ?
+ ClassLoader.getSystemResourceAsStream(ROWSET_PROPERTIES)
+ : cl.getResourceAsStream(ROWSET_PROPERTIES)) {
+ if (stream == null) {
+ throw new SyncFactoryException("Resource " + ROWSET_PROPERTIES + " not found");
+ }
+ properties.load(stream);
+ }
+ return null;
+ });
+ } catch (PrivilegedActionException ex) {
+ Throwable e = ex.getException();
+ if (e instanceof SyncFactoryException) {
+ throw (SyncFactoryException) e;
+ } else {
+ SyncFactoryException sfe = new SyncFactoryException();
+ sfe.initCause(ex.getException());
+ throw sfe;
}
- properties.load(stream);
}
parseProperties(properties);
@@ -411,7 +428,7 @@ public class SyncFactory {
public String run() {
return System.getProperty(ROWSET_SYNC_PROVIDER);
}
- }, null, new PropertyPermission(ROWSET_SYNC_PROVIDER,"read"));
+ }, null, new PropertyPermission(ROWSET_SYNC_PROVIDER, "read"));
} catch (Exception ex) {
providerImpls = null;
}
@@ -547,6 +564,14 @@ public class SyncFactory {
return new com.sun.rowset.providers.RIOptimisticProvider();
}
+ try {
+ ReflectUtil.checkPackageAccess(providerID);
+ } catch (java.security.AccessControlException e) {
+ SyncFactoryException sfe = new SyncFactoryException();
+ sfe.initCause(e);
+ throw sfe;
+ }
+
// Attempt to invoke classname from registered SyncProvider list
Class> c = null;
try {
@@ -555,7 +580,7 @@ public class SyncFactory {
/**
* The SyncProvider implementation of the user will be in
* the classpath. We need to find the ClassLoader which loads
- * this SyncFactory and try to laod the SyncProvider class from
+ * this SyncFactory and try to load the SyncProvider class from
* there.
**/
c = Class.forName(providerID, true, cl);
diff --git a/jdk/src/share/classes/jdk/net/ExtendedSocketOptions.java b/jdk/src/share/classes/jdk/net/ExtendedSocketOptions.java
new file mode 100644
index 00000000000..8be1fe6a5dc
--- /dev/null
+++ b/jdk/src/share/classes/jdk/net/ExtendedSocketOptions.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.net;
+
+import java.net.SocketOption;
+
+/**
+ * Defines extended socket options, beyond those defined in
+ * {@link java.net.StandardSocketOptions}. These options may be platform
+ * specific.
+ *
+ * @since 1.9
+ */
+@jdk.Exported
+public final class ExtendedSocketOptions {
+
+ private static class ExtSocketOption implements SocketOption {
+ private final String name;
+ private final Class type;
+ ExtSocketOption(String name, Class type) {
+ this.name = name;
+ this.type = type;
+ }
+ @Override public String name() { return name; }
+ @Override public Class type() { return type; }
+ @Override public String toString() { return name; }
+ }
+
+ private ExtendedSocketOptions() {}
+
+ /**
+ * Service level properties. When a security manager is installed,
+ * setting or getting this option requires a {@link NetworkPermission}
+ * {@code ("setOption.SO_FLOW_SLA")} or {@code "getOption.SO_FLOW_SLA"}
+ * respectively.
+ */
+ public static final SocketOption SO_FLOW_SLA = new
+ ExtSocketOption("SO_FLOW_SLA", SocketFlow.class);
+}
diff --git a/jdk/src/share/classes/jdk/net/NetworkPermission.java b/jdk/src/share/classes/jdk/net/NetworkPermission.java
new file mode 100644
index 00000000000..0e853f0d527
--- /dev/null
+++ b/jdk/src/share/classes/jdk/net/NetworkPermission.java
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.net;
+
+import java.security.BasicPermission;
+
+/**
+ * Represents permission to access the extended networking capabilities
+ * defined in the jdk.net package. These permissions contain a target
+ * name, but no actions list. Callers either possess the permission or not.
+ *
+ * The following targets are defined:
+ *
+ *
+ *
+ *
Permission Target Name
+ *
What the Permission Allows
+ *
Risks of Allowing this Permission
+ *
+ *
+ *
setOption.SO_FLOW_SLA
+ *
set the {@link ExtendedSocketOptions#SO_FLOW_SLA SO_FLOW_SLA} option
+ * on any socket that supports it
+ *
allows caller to set a higher priority or bandwidth allocation
+ * to sockets it creates, than they might otherwise be allowed.
+ *
+ *
+ *
getOption.SO_FLOW_SLA
+ *
retrieve the {@link ExtendedSocketOptions#SO_FLOW_SLA SO_FLOW_SLA}
+ * setting from any socket that supports the option
+ *
allows caller access to SLA information that it might not
+ * otherwise have
+ *
+ *
+ * @see jdk.net.ExtendedSocketOptions
+ *
+ * @since 1.9
+ */
+
+@jdk.Exported
+public final class NetworkPermission extends BasicPermission {
+
+ private static final long serialVersionUID = -2012939586906722291L;
+
+ /**
+ * Creates a NetworkPermission with the given target name.
+ *
+ * @param name the permission target name
+ * @throws NullPointerException if {@code name} is {@code null}.
+ * @throws IllegalArgumentException if {@code name} is empty.
+ */
+ public NetworkPermission(String name)
+ {
+ super(name);
+ }
+
+ /**
+ * Creates a NetworkPermission with the given target name.
+ *
+ * @param name the permission target name
+ * @param actions should be {@code null}. Is ignored if not.
+ * @throws NullPointerException if {@code name} is {@code null}.
+ * @throws IllegalArgumentException if {@code name} is empty.
+ */
+ public NetworkPermission(String name, String actions)
+ {
+ super(name, actions);
+ }
+}
diff --git a/jdk/src/share/classes/jdk/net/SocketFlow.java b/jdk/src/share/classes/jdk/net/SocketFlow.java
new file mode 100644
index 00000000000..a102a3f35a0
--- /dev/null
+++ b/jdk/src/share/classes/jdk/net/SocketFlow.java
@@ -0,0 +1,169 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.net;
+
+import java.lang.annotation.Native;
+
+/**
+ * Represents the service level properties for the platform specific socket
+ * option {@link ExtendedSocketOptions#SO_FLOW_SLA}.
+ *
+ * The priority and bandwidth parameters must be set before
+ * setting the socket option.
+ *
+ * When the {@code SO_FLOW_SLA} option is set then it may not take effect
+ * immediately. If the value of the socket option is obtained with
+ * {@code getOption()} then the status may be returned as {@code INPROGRESS}
+ * until it takes effect. The priority and bandwidth values are only valid when
+ * the status is returned as OK.
+ *
+ * When a security manager is installed, a {@link NetworkPermission}
+ * is required to set or get this option.
+ *
+ * @since 1.9
+ */
+@jdk.Exported
+public class SocketFlow {
+
+ private static final int UNSET = -1;
+ @Native public static final int NORMAL_PRIORITY = 1;
+ @Native public static final int HIGH_PRIORITY = 2;
+
+ private int priority = NORMAL_PRIORITY;
+
+ private long bandwidth = UNSET;
+
+ private Status status = Status.NO_STATUS;
+
+ private SocketFlow() {}
+
+ /**
+ * Enumeration of the return values from the SO_FLOW_SLA
+ * socket option. Both setting and getting the option return
+ * one of these statuses, which reflect the state of socket's
+ * flow.
+ *
+ * @since 1.9
+ */
+ @jdk.Exported
+ public enum Status {
+ /**
+ * Set or get socket option has not been called yet. Status
+ * values can only be retrieved after calling set or get.
+ */
+ NO_STATUS,
+ /**
+ * Flow successfully created.
+ */
+ OK,
+ /**
+ * Caller has no permission to create flow.
+ */
+ NO_PERMISSION,
+ /**
+ * Flow can not be created because socket is not connected.
+ */
+ NOT_CONNECTED,
+ /**
+ * Flow creation not supported for this socket.
+ */
+ NOT_SUPPORTED,
+ /**
+ * A flow already exists with identical attributes.
+ */
+ ALREADY_CREATED,
+ /**
+ * A flow is being created.
+ */
+ IN_PROGRESS,
+ /**
+ * Some other unspecified error.
+ */
+ OTHER
+ }
+
+ /**
+ * Creates a new SocketFlow that can be used to set the SO_FLOW_SLA
+ * socket option and create a socket flow.
+ */
+ public static SocketFlow create() {
+ return new SocketFlow();
+ }
+
+ /**
+ * Sets this SocketFlow's priority. Must be either NORMAL_PRIORITY
+ * HIGH_PRIORITY. If not set, a flow's priority is normal.
+ *
+ * @throws IllegalArgumentException if priority is not NORMAL_PRIORITY or
+ * HIGH_PRIORITY.
+ */
+ public SocketFlow priority(int priority) {
+ if (priority != NORMAL_PRIORITY && priority != HIGH_PRIORITY) {
+ throw new IllegalArgumentException("invalid priority");
+ }
+ this.priority = priority;
+ return this;
+ }
+
+ /**
+ * Sets this SocketFlow's bandwidth. Must be greater than or equal to zero.
+ * A value of zero drops all packets for the socket.
+ *
+ * @throws IllegalArgumentException if bandwidth is less than zero.
+ */
+ public SocketFlow bandwidth(long bandwidth) {
+ if (bandwidth < 0) {
+ throw new IllegalArgumentException("invalid bandwidth");
+ } else {
+ this.bandwidth = bandwidth;
+ }
+ return this;
+ }
+
+ /**
+ * Returns this SocketFlow's priority.
+ */
+ public int priority() {
+ return priority;
+ }
+
+ /**
+ * Returns this SocketFlow's bandwidth.
+ *
+ * @return this SocketFlow's bandwidth, or {@code -1} if status is not OK.
+ */
+ public long bandwidth() {
+ return bandwidth;
+ }
+
+ /**
+ * Returns the Status value of this SocketFlow. NO_STATUS is returned
+ * if the object was not used in a call to set or get the option.
+ */
+ public Status status() {
+ return status;
+ }
+}
diff --git a/jdk/src/share/classes/jdk/net/Sockets.java b/jdk/src/share/classes/jdk/net/Sockets.java
new file mode 100644
index 00000000000..9f7d94a0323
--- /dev/null
+++ b/jdk/src/share/classes/jdk/net/Sockets.java
@@ -0,0 +1,311 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.net;
+
+import java.net.*;
+import java.io.IOException;
+import java.io.FileDescriptor;
+import java.security.PrivilegedAction;
+import java.security.AccessController;
+import java.lang.reflect.Field;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.HashMap;
+import java.util.Collections;
+import sun.net.ExtendedOptionsImpl;
+
+/**
+ * Defines static methods to set and get socket options defined by the
+ * {@link java.net.SocketOption} interface. All of the standard options defined
+ * by {@link java.net.Socket}, {@link java.net.ServerSocket}, and
+ * {@link java.net.DatagramSocket} can be set this way, as well as additional
+ * or platform specific options supported by each socket type.
+ *
+ * The {@link #supportedOptions(Class)} method can be called to determine
+ * the complete set of options available (per socket type) on the
+ * current system.
+ *
+ * When a security manager is installed, some non-standard socket options
+ * may require a security permission before being set or get.
+ * The details are specified in {@link ExtendedSocketOptions}. No permission
+ * is required for {@link java.net.StandardSocketOption}s.
+ *
+ * @see java.nio.channels.NetworkChannel
+ */
+@jdk.Exported
+public class Sockets {
+
+ private final static HashMap,Set>>
+ options = new HashMap<>();
+
+ static {
+ initOptionSets();
+ }
+
+ private Sockets() {}
+
+ /**
+ * Sets the value of a socket option on a {@link java.net.Socket}
+ *
+ * @param s the socket
+ * @param name The socket option
+ * @param value The value of the socket option. May be null for some
+ * options.
+ *
+ * @throws UnsupportedOperationException if the socket does not support
+ * the option.
+ *
+ * @throws IllegalArgumentException if the value is not valid for
+ * the option.
+ *
+ * @throws IOException if an I/O error occurs, or socket is closed.
+ *
+ * @throws SecurityException if a security manager is set and the
+ * caller does not have any required permission.
+ *
+ * @throws NullPointerException if name is null
+ *
+ * @see java.net.StandardSocketOptions
+ */
+ public static void setOption(Socket s, SocketOption name, T value) throws IOException
+ {
+ s.setOption(name, value);
+ }
+
+ /**
+ * Returns the value of a socket option from a {@link java.net.Socket}
+ *
+ * @param s the socket
+ * @param name The socket option
+ *
+ * @return The value of the socket option.
+ *
+ * @throws UnsupportedOperationException if the socket does not support
+ * the option.
+ *
+ * @throws IOException if an I/O error occurs
+ *
+ * @throws SecurityException if a security manager is set and the
+ * caller does not have any required permission.
+ *
+ * @throws NullPointerException if name is null
+ *
+ * @see java.net.StandardSocketOptions
+ */
+ public static T getOption(Socket s, SocketOption name) throws IOException
+ {
+ return s.getOption(name);
+ }
+
+ /**
+ * Sets the value of a socket option on a {@link java.net.ServerSocket}
+ *
+ * @param s the socket
+ * @param name The socket option
+ * @param value The value of the socket option.
+ *
+ * @throws UnsupportedOperationException if the socket does not support
+ * the option.
+ *
+ * @throws IllegalArgumentException if the value is not valid for
+ * the option.
+ *
+ * @throws IOException if an I/O error occurs
+ *
+ * @throws NullPointerException if name is null
+ *
+ * @throws SecurityException if a security manager is set and the
+ * caller does not have any required permission.
+ *
+ * @see java.net.StandardSocketOptions
+ */
+ public static void setOption(ServerSocket s, SocketOption name, T value) throws IOException
+ {
+ s.setOption(name, value);
+ }
+
+ /**
+ * Returns the value of a socket option from a {@link java.net.ServerSocket}
+ *
+ * @param s the socket
+ * @param name The socket option
+ *
+ * @return The value of the socket option.
+ *
+ * @throws UnsupportedOperationException if the socket does not support
+ * the option.
+ *
+ * @throws IOException if an I/O error occurs
+ *
+ * @throws NullPointerException if name is null
+ *
+ * @throws SecurityException if a security manager is set and the
+ * caller does not have any required permission.
+ *
+ * @see java.net.StandardSocketOptions
+ */
+ public static T getOption(ServerSocket s, SocketOption name) throws IOException
+ {
+ return s.getOption(name);
+ }
+
+ /**
+ * Sets the value of a socket option on a {@link java.net.DatagramSocket}
+ * or {@link java.net.MulticastSocket}
+ *
+ * @param s the socket
+ * @param name The socket option
+ * @param value The value of the socket option.
+ *
+ * @throws UnsupportedOperationException if the socket does not support
+ * the option.
+ *
+ * @throws IllegalArgumentException if the value is not valid for
+ * the option.
+ *
+ * @throws IOException if an I/O error occurs
+ *
+ * @throws NullPointerException if name is null
+ *
+ * @throws SecurityException if a security manager is set and the
+ * caller does not have any required permission.
+ *
+ * @see java.net.StandardSocketOptions
+ */
+ public static void setOption(DatagramSocket s, SocketOption name, T value) throws IOException
+ {
+ s.setOption(name, value);
+ }
+
+ /**
+ * Returns the value of a socket option from a
+ * {@link java.net.DatagramSocket} or {@link java.net.MulticastSocket}
+ *
+ * @param s the socket
+ * @param name The socket option
+ *
+ * @return The value of the socket option.
+ *
+ * @throws UnsupportedOperationException if the socket does not support
+ * the option.
+ *
+ * @throws IOException if an I/O error occurs
+ *
+ * @throws NullPointerException if name is null
+ *
+ * @throws SecurityException if a security manager is set and the
+ * caller does not have any required permission.
+ *
+ * @see java.net.StandardSocketOptions
+ */
+ public static T getOption(DatagramSocket s, SocketOption name) throws IOException
+ {
+ return s.getOption(name);
+ }
+
+ /**
+ * Returns a set of {@link java.net.SocketOption}s supported by the
+ * given socket type. This set may include standard options and also
+ * non standard extended options.
+ *
+ * @param socketType the type of java.net socket
+ *
+ * @throws IllegalArgumentException if socketType is not a valid
+ * socket type from the java.net package.
+ */
+ public static Set> supportedOptions(Class> socketType) {
+ Set> set = options.get(socketType);
+ if (set == null) {
+ throw new IllegalArgumentException("unknown socket type");
+ }
+ return set;
+ }
+
+ private static void checkValueType(Object value, Class> type) {
+ if (!type.isAssignableFrom(value.getClass())) {
+ String s = "Found: " + value.getClass().toString() + " Expected: "
+ + type.toString();
+ throw new IllegalArgumentException(s);
+ }
+ }
+
+ private static void initOptionSets() {
+ boolean flowsupported = ExtendedOptionsImpl.flowSupported();
+
+ // Socket
+
+ Set> set = new HashSet<>();
+ set.add(StandardSocketOptions.SO_KEEPALIVE);
+ set.add(StandardSocketOptions.SO_SNDBUF);
+ set.add(StandardSocketOptions.SO_RCVBUF);
+ set.add(StandardSocketOptions.SO_REUSEADDR);
+ set.add(StandardSocketOptions.SO_LINGER);
+ set.add(StandardSocketOptions.IP_TOS);
+ set.add(StandardSocketOptions.TCP_NODELAY);
+ if (flowsupported) {
+ set.add(ExtendedSocketOptions.SO_FLOW_SLA);
+ }
+ set = Collections.unmodifiableSet(set);
+ options.put(Socket.class, set);
+
+ // ServerSocket
+
+ set = new HashSet<>();
+ set.add(StandardSocketOptions.SO_RCVBUF);
+ set.add(StandardSocketOptions.SO_REUSEADDR);
+ set = Collections.unmodifiableSet(set);
+ options.put(ServerSocket.class, set);
+
+ // DatagramSocket
+
+ set = new HashSet<>();
+ set.add(StandardSocketOptions.SO_SNDBUF);
+ set.add(StandardSocketOptions.SO_RCVBUF);
+ set.add(StandardSocketOptions.SO_REUSEADDR);
+ set.add(StandardSocketOptions.IP_TOS);
+ if (flowsupported) {
+ set.add(ExtendedSocketOptions.SO_FLOW_SLA);
+ }
+ set = Collections.unmodifiableSet(set);
+ options.put(DatagramSocket.class, set);
+
+ // MulticastSocket
+
+ set = new HashSet<>();
+ set.add(StandardSocketOptions.SO_SNDBUF);
+ set.add(StandardSocketOptions.SO_RCVBUF);
+ set.add(StandardSocketOptions.SO_REUSEADDR);
+ set.add(StandardSocketOptions.IP_TOS);
+ set.add(StandardSocketOptions.IP_MULTICAST_IF);
+ set.add(StandardSocketOptions.IP_MULTICAST_TTL);
+ set.add(StandardSocketOptions.IP_MULTICAST_LOOP);
+ if (flowsupported) {
+ set.add(ExtendedSocketOptions.SO_FLOW_SLA);
+ }
+ set = Collections.unmodifiableSet(set);
+ options.put(MulticastSocket.class, set);
+ }
+}
diff --git a/jdk/src/share/classes/jdk/net/package-info.java b/jdk/src/share/classes/jdk/net/package-info.java
new file mode 100644
index 00000000000..236d640dbfa
--- /dev/null
+++ b/jdk/src/share/classes/jdk/net/package-info.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * Platform specific socket options for the {@code java.net} and {@code java.nio.channels}
+ * socket classes.
+ *
+ * @since 1.9
+ */
+
+@jdk.Exported
+package jdk.net;
diff --git a/jdk/src/share/classes/jdk/nio/zipfs/JarFileSystemProvider.java b/jdk/src/share/classes/jdk/nio/zipfs/JarFileSystemProvider.java
new file mode 100644
index 00000000000..e6495b157da
--- /dev/null
+++ b/jdk/src/share/classes/jdk/nio/zipfs/JarFileSystemProvider.java
@@ -0,0 +1,83 @@
+/*
+ * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.nio.zipfs;
+
+import java.nio.file.*;
+import java.nio.file.spi.*;
+import java.nio.file.attribute.*;
+import java.nio.file.spi.FileSystemProvider;
+
+import java.net.URI;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.nio.channels.FileChannel;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Set;
+
+class JarFileSystemProvider extends ZipFileSystemProvider
+{
+
+ @Override
+ public String getScheme() {
+ return "jar";
+ }
+
+ @Override
+ protected Path uriToPath(URI uri) {
+ String scheme = uri.getScheme();
+ if ((scheme == null) || !scheme.equalsIgnoreCase(getScheme())) {
+ throw new IllegalArgumentException("URI scheme is not '" + getScheme() + "'");
+ }
+ try {
+ String uristr = uri.toString();
+ int end = uristr.indexOf("!/");
+ uristr = uristr.substring(4, (end == -1) ? uristr.length() : end);
+ uri = new URI(uristr);
+ return Paths.get(new URI("file", uri.getHost(), uri.getPath(), null))
+ .toAbsolutePath();
+ } catch (URISyntaxException e) {
+ throw new AssertionError(e); //never thrown
+ }
+ }
+
+ @Override
+ public Path getPath(URI uri) {
+ FileSystem fs = getFileSystem(uri);
+ String path = uri.getFragment();
+ if (path == null) {
+ String uristr = uri.toString();
+ int off = uristr.indexOf("!/");
+ if (off != -1)
+ path = uristr.substring(off + 2);
+ }
+ if (path != null)
+ return fs.getPath(path);
+ throw new IllegalArgumentException("URI: "
+ + uri
+ + " does not contain path fragment ex. jar:///c:/foo.zip!/BAR");
+ }
+}
diff --git a/jdk/src/share/classes/jdk/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider b/jdk/src/share/classes/jdk/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider
new file mode 100644
index 00000000000..22b5cb22325
--- /dev/null
+++ b/jdk/src/share/classes/jdk/nio/zipfs/META-INF/services/java.nio.file.spi.FileSystemProvider
@@ -0,0 +1,2 @@
+jdk.nio.zipfs.ZipFileSystemProvider
+
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipCoder.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipCoder.java
similarity index 66%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipCoder.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipCoder.java
index 362b3bd66e1..08f97cc61b1 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipCoder.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipCoder.java
@@ -1,44 +1,29 @@
/*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipConstants.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipConstants.java
similarity index 84%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipConstants.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipConstants.java
index 61551a4d447..0a080a261ed 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipConstants.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipConstants.java
@@ -1,45 +1,29 @@
/*
- * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
-
+package jdk.nio.zipfs;
/**
*
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipDirectoryStream.java
similarity index 51%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipDirectoryStream.java
index 7ee803cc35d..68cfd334c3e 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipDirectoryStream.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipDirectoryStream.java
@@ -1,44 +1,29 @@
/*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.nio.file.DirectoryStream;
import java.nio.file.ClosedDirectoryStreamException;
@@ -53,7 +38,7 @@ import java.io.IOException;
* @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal
*/
-public class ZipDirectoryStream implements DirectoryStream {
+class ZipDirectoryStream implements DirectoryStream {
private final ZipFileSystem zipfs;
private final byte[] path;
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributeView.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileAttributeView.java
similarity index 68%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributeView.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipFileAttributeView.java
index 2498acd8e58..ef446d96cd4 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributeView.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileAttributeView.java
@@ -1,45 +1,29 @@
/*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.nio.file.attribute.*;
import java.io.IOException;
@@ -50,7 +34,7 @@ import java.util.Map;
* @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal
*/
-public class ZipFileAttributeView implements BasicFileAttributeView
+class ZipFileAttributeView implements BasicFileAttributeView
{
private static enum AttrID {
size,
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributes.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileAttributes.java
similarity index 59%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributes.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipFileAttributes.java
index 1eb8b0614f7..12d70ec82ca 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileAttributes.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileAttributes.java
@@ -1,59 +1,42 @@
/*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Arrays;
import java.util.Formatter;
-import static com.sun.nio.zipfs.ZipUtils.*;
+import static jdk.nio.zipfs.ZipUtils.*;
/**
*
* @author Xueming Shen, Rajendra Gutupalli,Jaya Hangal
*/
-public class ZipFileAttributes implements BasicFileAttributes
-
+class ZipFileAttributes implements BasicFileAttributes
{
private final ZipFileSystem.Entry e;
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileStore.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileStore.java
similarity index 61%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileStore.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipFileStore.java
index c4bfa2c0e8d..9f789709a02 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileStore.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileStore.java
@@ -1,44 +1,29 @@
/*
- * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.io.IOException;
import java.nio.file.Files;
@@ -56,7 +41,7 @@ import java.util.Formatter;
* @author Xueming Shen, Rajendra Gutupalli, Jaya Hangal
*/
-public class ZipFileStore extends FileStore {
+class ZipFileStore extends FileStore {
private final ZipFileSystem zfs;
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileSystem.java
similarity index 97%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipFileSystem.java
index 9101f56532e..34e0bc0435c 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystem.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileSystem.java
@@ -1,44 +1,29 @@
/*
- * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
@@ -54,6 +39,8 @@ import java.nio.channels.*;
import java.nio.file.*;
import java.nio.file.attribute.*;
import java.nio.file.spi.*;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
@@ -66,8 +53,8 @@ import java.util.zip.DeflaterOutputStream;
import java.util.zip.ZipException;
import java.util.zip.ZipError;
import static java.lang.Boolean.*;
-import static com.sun.nio.zipfs.ZipConstants.*;
-import static com.sun.nio.zipfs.ZipUtils.*;
+import static jdk.nio.zipfs.ZipConstants.*;
+import static jdk.nio.zipfs.ZipUtils.*;
import static java.nio.file.StandardOpenOption.*;
import static java.nio.file.StandardCopyOption.*;
@@ -77,7 +64,7 @@ import static java.nio.file.StandardCopyOption.*;
* @author Xueming Shen
*/
-public class ZipFileSystem extends FileSystem {
+class ZipFileSystem extends FileSystem {
private final ZipFileSystemProvider provider;
private final ZipPath defaultdir;
@@ -91,8 +78,9 @@ public class ZipFileSystem extends FileSystem {
private final boolean useTempFile; // use a temp file for newOS, default
// is to use BAOS for better performance
private final boolean createNew; // create a new zip if not exists
- private static final boolean isWindows =
- System.getProperty("os.name").startsWith("Windows");
+ private static final boolean isWindows = AccessController.doPrivileged(
+ (PrivilegedAction) () -> System.getProperty("os.name")
+ .startsWith("Windows"));
ZipFileSystem(ZipFileSystemProvider provider,
Path zfpath,
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java
similarity index 82%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java
index 8d4343a4718..bd3bd411820 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipFileSystemProvider.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipFileSystemProvider.java
@@ -1,44 +1,29 @@
/*
- * Copyright (c) 2009, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.io.*;
import java.nio.channels.*;
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipInfo.java
similarity index 79%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipInfo.java
index 7cef6ce54ed..05b08a3d443 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipInfo.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipInfo.java
@@ -1,50 +1,35 @@
/*
- * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.nio.file.Paths;
import java.util.Collections;
import java.util.Map;
-import static com.sun.nio.zipfs.ZipConstants.*;
-import static com.sun.nio.zipfs.ZipUtils.*;
+import static jdk.nio.zipfs.ZipConstants.*;
+import static jdk.nio.zipfs.ZipUtils.*;
/**
* Print all loc and cen headers of the ZIP file
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipPath.java
similarity index 93%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipPath.java
index 3527e5de25b..6001d0654ed 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipPath.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipPath.java
@@ -1,44 +1,29 @@
/*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.io.*;
import java.net.URI;
@@ -56,7 +41,7 @@ import static java.nio.file.StandardCopyOption.*;
* @author Xueming Shen, Rajendra Gutupalli,Jaya Hangal
*/
-public class ZipPath implements Path {
+class ZipPath implements Path {
private final ZipFileSystem zfs;
private final byte[] path;
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipUtils.java b/jdk/src/share/classes/jdk/nio/zipfs/ZipUtils.java
similarity index 83%
rename from jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipUtils.java
rename to jdk/src/share/classes/jdk/nio/zipfs/ZipUtils.java
index 3d576ae77c2..0e3584e89c9 100644
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/ZipUtils.java
+++ b/jdk/src/share/classes/jdk/nio/zipfs/ZipUtils.java
@@ -1,44 +1,29 @@
/*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
-package com.sun.nio.zipfs;
+package jdk.nio.zipfs;
import java.io.IOException;
import java.io.OutputStream;
diff --git a/jdk/src/share/classes/sun/awt/AWTAutoShutdown.java b/jdk/src/share/classes/sun/awt/AWTAutoShutdown.java
index 310e88b3237..f03cd50988d 100644
--- a/jdk/src/share/classes/sun/awt/AWTAutoShutdown.java
+++ b/jdk/src/share/classes/sun/awt/AWTAutoShutdown.java
@@ -27,13 +27,15 @@ package sun.awt;
import java.awt.AWTEvent;
-import java.util.Collections;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.HashSet;
import java.util.IdentityHashMap;
import java.util.Map;
import java.util.Set;
import sun.util.logging.PlatformLogger;
+import sun.misc.ThreadGroupUtils;
/**
* This class is to let AWT shutdown automatically when a user is done
@@ -215,7 +217,10 @@ public final class AWTAutoShutdown implements Runnable {
synchronized (activationLock) {
synchronized (mainLock) {
if (!isReadyToShutdown() && blockerThread == null) {
- activateBlockerThread();
+ AccessController.doPrivileged((PrivilegedAction) () -> {
+ activateBlockerThread();
+ return null;
+ });
} else {
mainLock.notifyAll();
timeoutPassed = false;
@@ -331,9 +336,12 @@ public final class AWTAutoShutdown implements Runnable {
/**
* Creates and starts a new blocker thread. Doesn't return until
* the new blocker thread starts.
+ *
+ * Must be called with {@link sun.security.util.SecurityConstants#MODIFY_THREADGROUP_PERMISSION}
*/
private void activateBlockerThread() {
- Thread thread = new Thread(this, "AWT-Shutdown");
+ Thread thread = new Thread(ThreadGroupUtils.getRootThreadGroup(), this, "AWT-Shutdown");
+ thread.setContextClassLoader(null);
thread.setDaemon(false);
blockerThread = thread;
thread.start();
diff --git a/jdk/src/share/classes/sun/awt/SunToolkit.java b/jdk/src/share/classes/sun/awt/SunToolkit.java
index a5f09e15008..1cb15b78a01 100644
--- a/jdk/src/share/classes/sun/awt/SunToolkit.java
+++ b/jdk/src/share/classes/sun/awt/SunToolkit.java
@@ -40,6 +40,7 @@ import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
+import java.security.PrivilegedAction;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
diff --git a/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java b/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java
index c0bb3c62f6d..6c3a4d18c06 100644
--- a/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java
+++ b/jdk/src/share/classes/sun/awt/datatransfer/ClipboardTransferable.java
@@ -85,7 +85,7 @@ public class ClipboardTransferable implements Transferable {
// read it.
Map cached_data = new HashMap<>(formats.length, 1.0f);
DataTransferer.getInstance()
- .getFlavorsForFormats(formats, SunClipboard.flavorMap)
+ .getFlavorsForFormats(formats, SunClipboard.getDefaultFlavorTable())
.entrySet()
.forEach(entry -> fetchOneFlavor(clipboard, entry.getKey(), entry.getValue(), cached_data));
flavors = DataTransferer.setToSortedDataFlavorArray(flavorsToData.keySet());
diff --git a/jdk/src/share/classes/sun/awt/datatransfer/SunClipboard.java b/jdk/src/share/classes/sun/awt/datatransfer/SunClipboard.java
index 13d4a4c8828..1c3aaf4c334 100644
--- a/jdk/src/share/classes/sun/awt/datatransfer/SunClipboard.java
+++ b/jdk/src/share/classes/sun/awt/datatransfer/SunClipboard.java
@@ -64,9 +64,6 @@ import sun.awt.EventListenerAggregate;
public abstract class SunClipboard extends Clipboard
implements PropertyChangeListener {
- public static final FlavorTable flavorMap =
- (FlavorTable)SystemFlavorMap.getDefaultFlavorMap();
-
private AppContext contentsContext = null;
private final Object CLIPBOARD_FLAVOR_LISTENER_KEY;
@@ -172,7 +169,7 @@ public abstract class SunClipboard extends Clipboard
long[] formats = getClipboardFormatsOpenClose();
return DataTransferer.getInstance().
- getFlavorsForFormatsAsArray(formats, flavorMap);
+ getFlavorsForFormatsAsArray(formats, getDefaultFlavorTable());
}
/**
@@ -218,7 +215,7 @@ public abstract class SunClipboard extends Clipboard
long[] formats = getClipboardFormats();
Long lFormat = DataTransferer.getInstance().
- getFlavorsForFormats(formats, flavorMap).get(flavor);
+ getFlavorsForFormats(formats, getDefaultFlavorTable()).get(flavor);
if (lFormat == null) {
throw new UnsupportedFlavorException(flavor);
@@ -349,7 +346,7 @@ public abstract class SunClipboard extends Clipboard
private static Set formatArrayAsDataFlavorSet(long[] formats) {
return (formats == null) ? null :
DataTransferer.getInstance().
- getFlavorsForFormatsAsSet(formats, flavorMap);
+ getFlavorsForFormatsAsSet(formats, getDefaultFlavorTable());
}
@@ -469,4 +466,7 @@ public abstract class SunClipboard extends Clipboard
}
}
+ public static FlavorTable getDefaultFlavorTable() {
+ return (FlavorTable) SystemFlavorMap.getDefaultFlavorMap();
+ }
}
diff --git a/jdk/src/share/classes/sun/font/CreatedFontTracker.java b/jdk/src/share/classes/sun/font/CreatedFontTracker.java
index 71efa7ba446..02b264db785 100644
--- a/jdk/src/share/classes/sun/font/CreatedFontTracker.java
+++ b/jdk/src/share/classes/sun/font/CreatedFontTracker.java
@@ -27,12 +27,15 @@ package sun.font;
import java.io.File;
import java.io.OutputStream;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import sun.awt.AppContext;
+import sun.misc.ThreadGroupUtils;
public class CreatedFontTracker {
@@ -112,28 +115,18 @@ public class CreatedFontTracker {
static void init() {
if (t == null) {
// Add a shutdown hook to remove the temp file.
- java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction() {
- public Object run() {
- /* The thread must be a member of a thread group
- * which will not get GCed before VM exit.
- * Make its parent the top-level thread group.
- */
- ThreadGroup tg =
- Thread.currentThread().getThreadGroup();
- for (ThreadGroup tgn = tg;
- tgn != null;
- tg = tgn, tgn = tg.getParent());
- t = new Thread(tg, new Runnable() {
- public void run() {
- runHooks();
- }
- });
- t.setContextClassLoader(null);
- Runtime.getRuntime().addShutdownHook(t);
- return null;
- }
- });
+ AccessController.doPrivileged(
+ (PrivilegedAction) () -> {
+ /* The thread must be a member of a thread group
+ * which will not get GCed before VM exit.
+ * Make its parent the top-level thread group.
+ */
+ ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
+ t = new Thread(rootTG, TempFileDeletionHook::runHooks);
+ t.setContextClassLoader(null);
+ Runtime.getRuntime().addShutdownHook(t);
+ return null;
+ });
}
}
diff --git a/jdk/src/share/classes/sun/font/SunFontManager.java b/jdk/src/share/classes/sun/font/SunFontManager.java
index 9ac30ef4e9f..8487b9632a1 100644
--- a/jdk/src/share/classes/sun/font/SunFontManager.java
+++ b/jdk/src/share/classes/sun/font/SunFontManager.java
@@ -52,6 +52,7 @@ import javax.swing.plaf.FontUIResource;
import sun.awt.AppContext;
import sun.awt.FontConfiguration;
import sun.awt.SunToolkit;
+import sun.misc.ThreadGroupUtils;
import sun.java2d.FontSupport;
import sun.util.logging.PlatformLogger;
@@ -2527,24 +2528,18 @@ public abstract class SunFontManager implements FontSupport, FontManagerForSGE {
});
}
};
- java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction() {
- public Object run() {
- /* The thread must be a member of a thread group
- * which will not get GCed before VM exit.
- * Make its parent the top-level thread group.
- */
- ThreadGroup tg =
- Thread.currentThread().getThreadGroup();
- for (ThreadGroup tgn = tg;
- tgn != null;
- tg = tgn, tgn = tg.getParent());
- fileCloser = new Thread(tg, fileCloserRunnable);
- fileCloser.setContextClassLoader(null);
- Runtime.getRuntime().addShutdownHook(fileCloser);
- return null;
- }
- });
+ AccessController.doPrivileged(
+ (PrivilegedAction) () -> {
+ /* The thread must be a member of a thread group
+ * which will not get GCed before VM exit.
+ * Make its parent the top-level thread group.
+ */
+ ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
+ fileCloser = new Thread(rootTG, fileCloserRunnable);
+ fileCloser.setContextClassLoader(null);
+ Runtime.getRuntime().addShutdownHook(fileCloser);
+ return null;
+ });
}
}
}
diff --git a/jdk/src/share/classes/sun/java2d/Disposer.java b/jdk/src/share/classes/sun/java2d/Disposer.java
index 61877c3436d..1acf1447cdc 100644
--- a/jdk/src/share/classes/sun/java2d/Disposer.java
+++ b/jdk/src/share/classes/sun/java2d/Disposer.java
@@ -25,10 +25,14 @@
package sun.java2d;
+import sun.misc.ThreadGroupUtils;
+
import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.PhantomReference;
import java.lang.ref.WeakReference;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Hashtable;
@@ -77,27 +81,21 @@ public class Disposer implements Runnable {
}
}
disposerInstance = new Disposer();
- java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction() {
- public Object run() {
- /* The thread must be a member of a thread group
- * which will not get GCed before VM exit.
- * Make its parent the top-level thread group.
- */
- ThreadGroup tg = Thread.currentThread().getThreadGroup();
- for (ThreadGroup tgn = tg;
- tgn != null;
- tg = tgn, tgn = tg.getParent());
- Thread t =
- new Thread(tg, disposerInstance, "Java2D Disposer");
- t.setContextClassLoader(null);
- t.setDaemon(true);
- t.setPriority(Thread.MAX_PRIORITY);
- t.start();
- return null;
- }
- }
- );
+ AccessController.doPrivileged(
+ (PrivilegedAction) () -> {
+ /* The thread must be a member of a thread group
+ * which will not get GCed before VM exit.
+ * Make its parent the top-level thread group.
+ */
+ ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
+ Thread t = new Thread(rootTG, disposerInstance, "Java2D Disposer");
+ t.setContextClassLoader(null);
+ t.setDaemon(true);
+ t.setPriority(Thread.MAX_PRIORITY);
+ t.start();
+ return null;
+ }
+ );
}
/**
diff --git a/jdk/src/share/classes/sun/java2d/opengl/OGLRenderQueue.java b/jdk/src/share/classes/sun/java2d/opengl/OGLRenderQueue.java
index 43a47a8e26d..a73a883d16f 100644
--- a/jdk/src/share/classes/sun/java2d/opengl/OGLRenderQueue.java
+++ b/jdk/src/share/classes/sun/java2d/opengl/OGLRenderQueue.java
@@ -25,6 +25,7 @@
package sun.java2d.opengl;
+import sun.misc.ThreadGroupUtils;
import sun.java2d.pipe.RenderBuffer;
import sun.java2d.pipe.RenderQueue;
import static sun.java2d.pipe.BufferedOpCodes.*;
@@ -47,14 +48,8 @@ public class OGLRenderQueue extends RenderQueue {
* The thread must be a member of a thread group
* which will not get GCed before VM exit.
*/
- flusher = AccessController.doPrivileged(new PrivilegedAction() {
- public QueueFlusher run() {
- ThreadGroup rootThreadGroup = Thread.currentThread().getThreadGroup();
- while (rootThreadGroup.getParent() != null) {
- rootThreadGroup = rootThreadGroup.getParent();
- }
- return new QueueFlusher(rootThreadGroup);
- }
+ flusher = AccessController.doPrivileged((PrivilegedAction) () -> {
+ return new QueueFlusher(ThreadGroupUtils.getRootThreadGroup());
});
}
diff --git a/jdk/src/share/classes/sun/misc/InnocuousThread.java b/jdk/src/share/classes/sun/misc/InnocuousThread.java
new file mode 100644
index 00000000000..db431029484
--- /dev/null
+++ b/jdk/src/share/classes/sun/misc/InnocuousThread.java
@@ -0,0 +1,121 @@
+/*
+ * 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. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.misc;
+
+import java.security.AccessControlContext;
+import java.security.ProtectionDomain;
+
+/**
+ * A thread that has no permissions, is not a member of any user-defined
+ * ThreadGroup and supports the ability to erase ThreadLocals.
+ *
+ * @implNote Based on the implementation of InnocuousForkJoinWorkerThread.
+ */
+public final class InnocuousThread extends Thread {
+ private static final Unsafe UNSAFE;
+ private static final ThreadGroup THREADGROUP;
+ private static final AccessControlContext ACC;
+ private static final long THREADLOCALS;
+ private static final long INHERITABLETHREADLOCALS;
+ private static final long INHERITEDACCESSCONTROLCONTEXT;
+
+ public InnocuousThread(Runnable target) {
+ super(THREADGROUP, target, "anInnocuousThread");
+ UNSAFE.putOrderedObject(this, INHERITEDACCESSCONTROLCONTEXT, ACC);
+ eraseThreadLocals();
+ }
+
+ @Override
+ public ClassLoader getContextClassLoader() {
+ // always report system class loader
+ return ClassLoader.getSystemClassLoader();
+ }
+
+ @Override
+ public void setUncaughtExceptionHandler(UncaughtExceptionHandler x) {
+ // silently fail
+ }
+
+ @Override
+ public void setContextClassLoader(ClassLoader cl) {
+ throw new SecurityException("setContextClassLoader");
+ }
+
+ // ensure run method is run only once
+ private volatile boolean hasRun;
+
+ @Override
+ public void run() {
+ if (Thread.currentThread() == this && !hasRun) {
+ hasRun = true;
+ super.run();
+ }
+ }
+
+ /**
+ * Drops all thread locals (and inherited thread locals).
+ */
+ public void eraseThreadLocals() {
+ UNSAFE.putObject(this, THREADLOCALS, null);
+ UNSAFE.putObject(this, INHERITABLETHREADLOCALS, null);
+ }
+
+ // Use Unsafe to access Thread group and ThreadGroup parent fields
+ static {
+ try {
+ ACC = new AccessControlContext(new ProtectionDomain[] {
+ new ProtectionDomain(null, null)
+ });
+
+ // Find and use topmost ThreadGroup as parent of new group
+ UNSAFE = Unsafe.getUnsafe();
+ Class> tk = Thread.class;
+ Class> gk = ThreadGroup.class;
+
+ THREADLOCALS = UNSAFE.objectFieldOffset
+ (tk.getDeclaredField("threadLocals"));
+ INHERITABLETHREADLOCALS = UNSAFE.objectFieldOffset
+ (tk.getDeclaredField("inheritableThreadLocals"));
+ INHERITEDACCESSCONTROLCONTEXT = UNSAFE.objectFieldOffset
+ (tk.getDeclaredField("inheritedAccessControlContext"));
+
+ long tg = UNSAFE.objectFieldOffset(tk.getDeclaredField("group"));
+ long gp = UNSAFE.objectFieldOffset(gk.getDeclaredField("parent"));
+ ThreadGroup group = (ThreadGroup)
+ UNSAFE.getObject(Thread.currentThread(), tg);
+
+ while (group != null) {
+ ThreadGroup parent = (ThreadGroup)UNSAFE.getObject(group, gp);
+ if (parent == null)
+ break;
+ group = parent;
+ }
+ THREADGROUP = new ThreadGroup(group, "InnocuousThreadGroup");
+ } catch (Exception e) {
+ throw new Error(e);
+ }
+ }
+}
diff --git a/jdk/src/share/classes/sun/misc/JavaNetHttpCookieAccess.java b/jdk/src/share/classes/sun/misc/JavaNetHttpCookieAccess.java
index 8149a222bdb..61f856f3f9e 100644
--- a/jdk/src/share/classes/sun/misc/JavaNetHttpCookieAccess.java
+++ b/jdk/src/share/classes/sun/misc/JavaNetHttpCookieAccess.java
@@ -36,7 +36,7 @@ public interface JavaNetHttpCookieAccess {
public List parse(String header);
/*
- * Returns the original header this cookie was consructed from, if it was
+ * Returns the original header this cookie was constructed from, if it was
* constructed by parsing a header, otherwise null.
*/
public String header(HttpCookie cookie);
diff --git a/jdk/src/share/classes/sun/misc/ThreadGroupUtils.java b/jdk/src/share/classes/sun/misc/ThreadGroupUtils.java
new file mode 100644
index 00000000000..066a8002f72
--- /dev/null
+++ b/jdk/src/share/classes/sun/misc/ThreadGroupUtils.java
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.misc;
+
+/**
+ * A utility class needed to access the root {@code ThreadGroup}
+ *
+ * The class should not depend on any others, because it' called from JNI_OnLoad of the AWT
+ * native library. Triggering class loading could could lead to a deadlock.
+ */
+public final class ThreadGroupUtils {
+
+ private ThreadGroupUtils() {
+ // Avoid instantiation
+ }
+
+ /**
+ * Returns a root thread group.
+ * Should be called with {@link sun.security.util.SecurityConstants#MODIFY_THREADGROUP_PERMISSION}
+ *
+ * @return a root {@code ThreadGroup}
+ */
+ public static ThreadGroup getRootThreadGroup() {
+ ThreadGroup currentTG = Thread.currentThread().getThreadGroup();
+ ThreadGroup parentTG = currentTG.getParent();
+ while (parentTG != null) {
+ currentTG = parentTG;
+ parentTG = currentTG.getParent();
+ }
+ return currentTG;
+ }
+}
diff --git a/jdk/src/share/classes/sun/net/ExtendedOptionsImpl.java b/jdk/src/share/classes/sun/net/ExtendedOptionsImpl.java
new file mode 100644
index 00000000000..8fbcdd7b49d
--- /dev/null
+++ b/jdk/src/share/classes/sun/net/ExtendedOptionsImpl.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.net;
+
+import java.net.*;
+import jdk.net.*;
+import java.io.IOException;
+import java.io.FileDescriptor;
+import java.security.PrivilegedAction;
+import java.security.AccessController;
+import java.lang.reflect.Field;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.HashMap;
+import java.util.Collections;
+
+/**
+ * Contains the native implementation for extended socket options
+ * together with some other static utilities
+ */
+public class ExtendedOptionsImpl {
+
+ static {
+ AccessController.doPrivileged((PrivilegedAction)() -> {
+ System.loadLibrary("net");
+ return null;
+ });
+ init();
+ }
+
+ private ExtendedOptionsImpl() {}
+
+ public static void checkSetOptionPermission(SocketOption> option) {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm == null) {
+ return;
+ }
+ String check = "setOption." + option.name();
+ sm.checkPermission(new NetworkPermission(check));
+ }
+
+ public static void checkGetOptionPermission(SocketOption> option) {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm == null) {
+ return;
+ }
+ String check = "getOption." + option.name();
+ sm.checkPermission(new NetworkPermission(check));
+ }
+
+ public static void checkValueType(Object value, Class> type) {
+ if (!type.isAssignableFrom(value.getClass())) {
+ String s = "Found: " + value.getClass().toString() + " Expected: "
+ + type.toString();
+ throw new IllegalArgumentException(s);
+ }
+ }
+
+ private static native void init();
+
+ /*
+ * Extension native implementations
+ *
+ * SO_FLOW_SLA
+ */
+ public static native void setFlowOption(FileDescriptor fd, SocketFlow f);
+ public static native void getFlowOption(FileDescriptor fd, SocketFlow f);
+ public static native boolean flowSupported();
+}
diff --git a/jdk/src/share/classes/sun/net/InetAddressCachePolicy.java b/jdk/src/share/classes/sun/net/InetAddressCachePolicy.java
index 8437a1d5234..31578b50d78 100644
--- a/jdk/src/share/classes/sun/net/InetAddressCachePolicy.java
+++ b/jdk/src/share/classes/sun/net/InetAddressCachePolicy.java
@@ -84,19 +84,31 @@ public final class InetAddressCachePolicy {
* Initialize
*/
static {
- Integer tmp = null;
- try {
- tmp = new Integer(
- java.security.AccessController.doPrivileged (
- new PrivilegedAction() {
- public String run() {
- return Security.getProperty(cachePolicyProp);
- }
- }));
- } catch (NumberFormatException e) {
- // ignore
- }
+ Integer tmp = java.security.AccessController.doPrivileged(
+ new PrivilegedAction() {
+ public Integer run() {
+ try {
+ String tmpString = Security.getProperty(cachePolicyProp);
+ if (tmpString != null) {
+ return Integer.valueOf(tmpString);
+ }
+ } catch (NumberFormatException ignored) {
+ // Ignore
+ }
+
+ try {
+ String tmpString = System.getProperty(cachePolicyPropFallback);
+ if (tmpString != null) {
+ return Integer.decode(tmpString);
+ }
+ } catch (NumberFormatException ignored) {
+ // Ignore
+ }
+ return null;
+ }
+ });
+
if (tmp != null) {
cachePolicy = tmp.intValue();
if (cachePolicy < 0) {
@@ -104,35 +116,36 @@ public final class InetAddressCachePolicy {
}
propertySet = true;
} else {
- tmp = java.security.AccessController.doPrivileged
- (new sun.security.action.GetIntegerAction(cachePolicyPropFallback));
- if (tmp != null) {
- cachePolicy = tmp.intValue();
- if (cachePolicy < 0) {
- cachePolicy = FOREVER;
- }
- propertySet = true;
- } else {
- /* No properties defined for positive caching. If there is no
- * security manager then use the default positive cache value.
- */
- if (System.getSecurityManager() == null) {
- cachePolicy = DEFAULT_POSITIVE;
- }
+ /* No properties defined for positive caching. If there is no
+ * security manager then use the default positive cache value.
+ */
+ if (System.getSecurityManager() == null) {
+ cachePolicy = DEFAULT_POSITIVE;
}
}
+ tmp = java.security.AccessController.doPrivileged (
+ new PrivilegedAction() {
+ public Integer run() {
+ try {
+ String tmpString = Security.getProperty(negativeCachePolicyProp);
+ if (tmpString != null) {
+ return Integer.valueOf(tmpString);
+ }
+ } catch (NumberFormatException ignored) {
+ // Ignore
+ }
- try {
- tmp = new Integer(
- java.security.AccessController.doPrivileged (
- new PrivilegedAction() {
- public String run() {
- return Security.getProperty(negativeCachePolicyProp);
- }
- }));
- } catch (NumberFormatException e) {
- // ignore
- }
+ try {
+ String tmpString = System.getProperty(negativeCachePolicyPropFallback);
+ if (tmpString != null) {
+ return Integer.decode(tmpString);
+ }
+ } catch (NumberFormatException ignored) {
+ // Ignore
+ }
+ return null;
+ }
+ });
if (tmp != null) {
negativeCachePolicy = tmp.intValue();
@@ -140,16 +153,6 @@ public final class InetAddressCachePolicy {
negativeCachePolicy = FOREVER;
}
propertyNegativeSet = true;
- } else {
- tmp = java.security.AccessController.doPrivileged
- (new sun.security.action.GetIntegerAction(negativeCachePolicyPropFallback));
- if (tmp != null) {
- negativeCachePolicy = tmp.intValue();
- if (negativeCachePolicy < 0) {
- negativeCachePolicy = FOREVER;
- }
- propertyNegativeSet = true;
- }
}
}
diff --git a/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java b/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
index 0f4bf3fdfcf..9c3fb964f0a 100644
--- a/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
+++ b/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
@@ -32,6 +32,7 @@ import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
+import java.util.Base64;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
@@ -42,8 +43,6 @@ import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
-import sun.misc.BASE64Decoder;
-import sun.misc.BASE64Encoder;
import sun.net.ftp.*;
import sun.util.logging.PlatformLogger;
@@ -1899,22 +1898,16 @@ public class FtpClient extends sun.net.ftp.FtpClient {
}
private boolean sendSecurityData(byte[] buf) throws IOException {
- BASE64Encoder encoder = new BASE64Encoder();
- String s = encoder.encode(buf);
+ String s = Base64.getMimeEncoder().encodeToString(buf);
return issueCommand("ADAT " + s);
}
private byte[] getSecurityData() {
String s = getLastResponseString();
if (s.substring(4, 9).equalsIgnoreCase("ADAT=")) {
- BASE64Decoder decoder = new BASE64Decoder();
- try {
- // Need to get rid of the leading '315 ADAT='
- // and the trailing newline
- return decoder.decodeBuffer(s.substring(9, s.length() - 1));
- } catch (IOException e) {
- //
- }
+ // Need to get rid of the leading '315 ADAT='
+ // and the trailing newline
+ return Base64.getMimeDecoder().decode(s.substring(9, s.length() - 1));
}
return null;
}
diff --git a/jdk/src/share/classes/sun/net/util/IPAddressUtil.java b/jdk/src/share/classes/sun/net/util/IPAddressUtil.java
index 4cef8ab04dc..4dafa8a1d0b 100644
--- a/jdk/src/share/classes/sun/net/util/IPAddressUtil.java
+++ b/jdk/src/share/classes/sun/net/util/IPAddressUtil.java
@@ -37,90 +37,73 @@ public class IPAddressUtil {
* @param src a String representing an IPv4 address in standard format
* @return a byte array representing the IPv4 numeric address
*/
+ @SuppressWarnings("fallthrough")
public static byte[] textToNumericFormatV4(String src)
{
- if (src.length() == 0) {
+ byte[] res = new byte[INADDR4SZ];
+
+ long tmpValue = 0;
+ int currByte = 0;
+
+ int len = src.length();
+ if (len == 0 || len > 15) {
return null;
}
-
- byte[] res = new byte[INADDR4SZ];
- String[] s = src.split("\\.", -1);
- long val;
- try {
- switch(s.length) {
- case 1:
- /*
- * When only one part is given, the value is stored directly in
- * the network address without any byte rearrangement.
- */
-
- val = Long.parseLong(s[0]);
- if (val < 0 || val > 0xffffffffL)
+ /*
+ * When only one part is given, the value is stored directly in
+ * the network address without any byte rearrangement.
+ *
+ * When a two part address is supplied, the last part is
+ * interpreted as a 24-bit quantity and placed in the right
+ * most three bytes of the network address. This makes the
+ * two part address format convenient for specifying Class A
+ * network addresses as net.host.
+ *
+ * When a three part address is specified, the last part is
+ * interpreted as a 16-bit quantity and placed in the right
+ * most two bytes of the network address. This makes the
+ * three part address format convenient for specifying
+ * Class B net- work addresses as 128.net.host.
+ *
+ * When four parts are specified, each is interpreted as a
+ * byte of data and assigned, from left to right, to the
+ * four bytes of an IPv4 address.
+ *
+ * We determine and parse the leading parts, if any, as single
+ * byte values in one pass directly into the resulting byte[],
+ * then the remainder is treated as a 8-to-32-bit entity and
+ * translated into the remaining bytes in the array.
+ */
+ for (int i = 0; i < len; i++) {
+ char c = src.charAt(i);
+ if (c == '.') {
+ if (tmpValue < 0 || tmpValue > 0xff || currByte == 3) {
return null;
- res[0] = (byte) ((val >> 24) & 0xff);
- res[1] = (byte) (((val & 0xffffff) >> 16) & 0xff);
- res[2] = (byte) (((val & 0xffff) >> 8) & 0xff);
- res[3] = (byte) (val & 0xff);
- break;
- case 2:
- /*
- * When a two part address is supplied, the last part is
- * interpreted as a 24-bit quantity and placed in the right
- * most three bytes of the network address. This makes the
- * two part address format convenient for specifying Class A
- * network addresses as net.host.
- */
-
- val = Integer.parseInt(s[0]);
- if (val < 0 || val > 0xff)
- return null;
- res[0] = (byte) (val & 0xff);
- val = Integer.parseInt(s[1]);
- if (val < 0 || val > 0xffffff)
- return null;
- res[1] = (byte) ((val >> 16) & 0xff);
- res[2] = (byte) (((val & 0xffff) >> 8) &0xff);
- res[3] = (byte) (val & 0xff);
- break;
- case 3:
- /*
- * When a three part address is specified, the last part is
- * interpreted as a 16-bit quantity and placed in the right
- * most two bytes of the network address. This makes the
- * three part address format convenient for specifying
- * Class B net- work addresses as 128.net.host.
- */
- for (int i = 0; i < 2; i++) {
- val = Integer.parseInt(s[i]);
- if (val < 0 || val > 0xff)
- return null;
- res[i] = (byte) (val & 0xff);
}
- val = Integer.parseInt(s[2]);
- if (val < 0 || val > 0xffff)
+ res[currByte++] = (byte) (tmpValue & 0xff);
+ tmpValue = 0;
+ } else {
+ int digit = Character.digit(c, 10);
+ if (digit < 0) {
return null;
- res[2] = (byte) ((val >> 8) & 0xff);
- res[3] = (byte) (val & 0xff);
- break;
- case 4:
- /*
- * When four parts are specified, each is interpreted as a
- * byte of data and assigned, from left to right, to the
- * four bytes of an IPv4 address.
- */
- for (int i = 0; i < 4; i++) {
- val = Integer.parseInt(s[i]);
- if (val < 0 || val > 0xff)
- return null;
- res[i] = (byte) (val & 0xff);
}
- break;
- default:
- return null;
+ tmpValue *= 10;
+ tmpValue += digit;
}
- } catch(NumberFormatException e) {
+ }
+ if (tmpValue < 0 || tmpValue >= (1L << ((4 - currByte) * 8))) {
return null;
}
+ switch (currByte) {
+ case 0:
+ res[0] = (byte) ((tmpValue >> 24) & 0xff);
+ case 1:
+ res[1] = (byte) ((tmpValue >> 16) & 0xff);
+ case 2:
+ res[2] = (byte) ((tmpValue >> 8) & 0xff);
+ case 3:
+ res[3] = (byte) ((tmpValue >> 0) & 0xff);
+ }
return res;
}
diff --git a/jdk/src/share/classes/sun/net/www/MimeTable.java b/jdk/src/share/classes/sun/net/www/MimeTable.java
index cab244c7615..84d4ef9f7dc 100644
--- a/jdk/src/share/classes/sun/net/www/MimeTable.java
+++ b/jdk/src/share/classes/sun/net/www/MimeTable.java
@@ -225,39 +225,28 @@ public class MimeTable implements FileNameMap {
public synchronized void load() {
Properties entries = new Properties();
File file = null;
- try {
- InputStream is;
- // First try to load the user-specific table, if it exists
- String userTablePath =
- System.getProperty("content.types.user.table");
- if (userTablePath != null) {
- file = new File(userTablePath);
- if (!file.exists()) {
- // No user-table, try to load the default built-in table.
- file = new File(System.getProperty("java.home") +
- File.separator +
- "lib" +
- File.separator +
- "content-types.properties");
- }
- }
- else {
- // No user table, try to load the default built-in table.
- file = new File(System.getProperty("java.home") +
- File.separator +
- "lib" +
- File.separator +
- "content-types.properties");
- }
+ InputStream in;
- is = new BufferedInputStream(new FileInputStream(file));
- entries.load(is);
- is.close();
+ // First try to load the user-specific table, if it exists
+ String userTablePath = System.getProperty("content.types.user.table");
+ if (userTablePath != null && (file = new File(userTablePath)).exists()) {
+ try {
+ in = new FileInputStream(file);
+ } catch (FileNotFoundException e) {
+ System.err.println("Warning: " + file.getPath()
+ + " mime table not found.");
+ return;
+ }
+ } else {
+ in = MimeTable.class.getResourceAsStream("content-types.properties");
+ if (in == null)
+ throw new InternalError("default mime table not found");
}
- catch (IOException e) {
- System.err.println("Warning: default mime table not found: " +
- file.getPath());
- return;
+
+ try (BufferedInputStream bin = new BufferedInputStream(in)) {
+ entries.load(bin);
+ } catch (IOException e) {
+ System.err.println("Warning: " + e.getMessage());
}
parse(entries);
}
@@ -380,18 +369,6 @@ public class MimeTable implements FileNameMap {
return MimeEntry.UNKNOWN;
}
- public synchronized boolean save(String filename) {
- if (filename == null) {
- filename = System.getProperty("user.home" +
- File.separator +
- "lib" +
- File.separator +
- "content-types.properties");
- }
-
- return saveAsProperties(new File(filename));
- }
-
public Properties getAsProperties() {
Properties properties = new Properties();
Enumeration e = elements();
diff --git a/jdk/src/share/classes/sun/net/www/http/HttpClient.java b/jdk/src/share/classes/sun/net/www/http/HttpClient.java
index 44a52530752..3013da01df3 100644
--- a/jdk/src/share/classes/sun/net/www/http/HttpClient.java
+++ b/jdk/src/share/classes/sun/net/www/http/HttpClient.java
@@ -665,7 +665,9 @@ public class HttpClient extends NetworkClient {
// try once more
openServer();
if (needsTunneling()) {
+ MessageHeader origRequests = requests;
httpuc.doTunneling();
+ requests = origRequests;
}
afterConnect();
writeRequests(requests, poster);
@@ -776,7 +778,9 @@ public class HttpClient extends NetworkClient {
cachedHttpClient = false;
openServer();
if (needsTunneling()) {
+ MessageHeader origRequests = requests;
httpuc.doTunneling();
+ requests = origRequests;
}
afterConnect();
writeRequests(requests, poster);
diff --git a/jdk/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java b/jdk/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java
index d28bf90b83f..9899d759b71 100644
--- a/jdk/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java
+++ b/jdk/src/share/classes/sun/nio/ch/AsynchronousSocketChannelImpl.java
@@ -39,6 +39,7 @@ import java.util.Collections;
import java.util.concurrent.*;
import java.util.concurrent.locks.*;
import sun.net.NetHooks;
+import sun.net.ExtendedOptionsImpl;
/**
* Base implementation of AsynchronousSocketChannel
@@ -508,6 +509,9 @@ abstract class AsynchronousSocketChannelImpl
set.add(StandardSocketOptions.SO_KEEPALIVE);
set.add(StandardSocketOptions.SO_REUSEADDR);
set.add(StandardSocketOptions.TCP_NODELAY);
+ if (ExtendedOptionsImpl.flowSupported()) {
+ set.add(jdk.net.ExtendedSocketOptions.SO_FLOW_SLA);
+ }
return Collections.unmodifiableSet(set);
}
}
diff --git a/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java b/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java
index c151afe570b..fe32f63880b 100644
--- a/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java
+++ b/jdk/src/share/classes/sun/nio/ch/DatagramChannelImpl.java
@@ -33,6 +33,7 @@ import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.util.*;
import sun.net.ResourceManager;
+import sun.net.ExtendedOptionsImpl;
/**
* An implementation of DatagramChannels.
@@ -317,6 +318,9 @@ class DatagramChannelImpl
set.add(StandardSocketOptions.IP_MULTICAST_IF);
set.add(StandardSocketOptions.IP_MULTICAST_TTL);
set.add(StandardSocketOptions.IP_MULTICAST_LOOP);
+ if (ExtendedOptionsImpl.flowSupported()) {
+ set.add(jdk.net.ExtendedSocketOptions.SO_FLOW_SLA);
+ }
return Collections.unmodifiableSet(set);
}
}
diff --git a/jdk/src/share/classes/sun/nio/ch/Invoker.java b/jdk/src/share/classes/sun/nio/ch/Invoker.java
index e55db542593..22908f0f143 100644
--- a/jdk/src/share/classes/sun/nio/ch/Invoker.java
+++ b/jdk/src/share/classes/sun/nio/ch/Invoker.java
@@ -130,6 +130,18 @@ class Invoker {
// clear interrupt
Thread.interrupted();
+
+ // clear thread locals when in default thread pool
+ if (System.getSecurityManager() != null) {
+ Thread me = Thread.currentThread();
+ if (me instanceof sun.misc.InnocuousThread) {
+ GroupAndInvokeCount thisGroupAndInvokeCount = myGroupAndInvokeCount.get();
+ ((sun.misc.InnocuousThread)me).eraseThreadLocals();
+ if (thisGroupAndInvokeCount != null) {
+ myGroupAndInvokeCount.set(thisGroupAndInvokeCount);
+ }
+ }
+ }
}
/**
diff --git a/jdk/src/share/classes/sun/nio/ch/Net.java b/jdk/src/share/classes/sun/nio/ch/Net.java
index 79ebb2f36a5..753e5417310 100644
--- a/jdk/src/share/classes/sun/nio/ch/Net.java
+++ b/jdk/src/share/classes/sun/nio/ch/Net.java
@@ -27,11 +27,13 @@ package sun.nio.ch;
import java.io.*;
import java.net.*;
+import jdk.net.*;
import java.nio.channels.*;
import java.util.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
+import sun.net.ExtendedOptionsImpl;
public class Net {
@@ -297,6 +299,16 @@ public class Net {
// only simple values supported by this method
Class> type = name.type();
+
+ if (type == SocketFlow.class) {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ sm.checkPermission(new NetworkPermission("setOption.SO_FLOW_SLA"));
+ }
+ ExtendedOptionsImpl.setFlowOption(fd, (SocketFlow)value);
+ return;
+ }
+
if (type != Integer.class && type != Boolean.class)
throw new AssertionError("Should not reach here");
@@ -349,6 +361,16 @@ public class Net {
{
Class> type = name.type();
+ if (type == SocketFlow.class) {
+ SecurityManager sm = System.getSecurityManager();
+ if (sm != null) {
+ sm.checkPermission(new NetworkPermission("getOption.SO_FLOW_SLA"));
+ }
+ SocketFlow flow = SocketFlow.create();
+ ExtendedOptionsImpl.getFlowOption(fd, flow);
+ return flow;
+ }
+
// only simple values supported by this method
if (type != Integer.class && type != Boolean.class)
throw new AssertionError("Should not reach here");
diff --git a/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java b/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java
index a977ced312b..1e36aed74d0 100644
--- a/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java
+++ b/jdk/src/share/classes/sun/nio/ch/SocketChannelImpl.java
@@ -33,6 +33,7 @@ import java.nio.channels.*;
import java.nio.channels.spi.*;
import java.util.*;
import sun.net.NetHooks;
+import sun.net.ExtendedOptionsImpl;
/**
@@ -237,6 +238,9 @@ class SocketChannelImpl
// additional options required by socket adaptor
set.add(StandardSocketOptions.IP_TOS);
set.add(ExtendedSocketOption.SO_OOBINLINE);
+ if (ExtendedOptionsImpl.flowSupported()) {
+ set.add(jdk.net.ExtendedSocketOptions.SO_FLOW_SLA);
+ }
return Collections.unmodifiableSet(set);
}
}
diff --git a/jdk/src/share/classes/sun/nio/ch/ThreadPool.java b/jdk/src/share/classes/sun/nio/ch/ThreadPool.java
index 0761cb3b4ba..0624e8a6788 100644
--- a/jdk/src/share/classes/sun/nio/ch/ThreadPool.java
+++ b/jdk/src/share/classes/sun/nio/ch/ThreadPool.java
@@ -27,6 +27,7 @@ package sun.nio.ch;
import java.util.concurrent.*;
import java.security.AccessController;
+import java.security.PrivilegedAction;
import sun.security.action.GetPropertyAction;
import sun.security.action.GetIntegerAction;
@@ -39,14 +40,6 @@ public class ThreadPool {
"java.nio.channels.DefaultThreadPool.threadFactory";
private static final String DEFAULT_THREAD_POOL_INITIAL_SIZE =
"java.nio.channels.DefaultThreadPool.initialSize";
- private static final ThreadFactory defaultThreadFactory = new ThreadFactory() {
- @Override
- public Thread newThread(Runnable r) {
- Thread t = new Thread(r);
- t.setDaemon(true);
- return t;
- }
- };
private final ExecutorService executor;
@@ -79,7 +72,22 @@ public class ThreadPool {
}
static ThreadFactory defaultThreadFactory() {
- return defaultThreadFactory;
+ if (System.getSecurityManager() == null) {
+ return (Runnable r) -> {
+ Thread t = new Thread(r);
+ t.setDaemon(true);
+ return t;
+ };
+ } else {
+ return (Runnable r) -> {
+ PrivilegedAction action = () -> {
+ Thread t = new sun.misc.InnocuousThread(r);
+ t.setDaemon(true);
+ return t;
+ };
+ return AccessController.doPrivileged(action);
+ };
+ }
}
private static class DefaultThreadPoolHolder {
@@ -100,7 +108,7 @@ public class ThreadPool {
// default to thread factory that creates daemon threads
ThreadFactory threadFactory = getDefaultThreadPoolThreadFactory();
if (threadFactory == null)
- threadFactory = defaultThreadFactory;
+ threadFactory = defaultThreadFactory();
// create thread pool
ExecutorService executor = Executors.newCachedThreadPool(threadFactory);
return new ThreadPool(executor, false, initialSize);
diff --git a/jdk/src/share/classes/sun/nio/cs/UTF_8.java b/jdk/src/share/classes/sun/nio/cs/UTF_8.java
index bfb7b7a977b..3ee2341f000 100644
--- a/jdk/src/share/classes/sun/nio/cs/UTF_8.java
+++ b/jdk/src/share/classes/sun/nio/cs/UTF_8.java
@@ -111,12 +111,18 @@ class UTF_8 extends Unicode
(b4 & 0xc0) != 0x80;
}
- // only used when there is less than 4 bytes left in src buffer
+ // only used when there is less than 4 bytes left in src buffer.
+ // both b1 and b2 should be "& 0xff" before passed in.
private static boolean isMalformed4_2(int b1, int b2) {
- return (b1 == 0xf0 && b2 == 0x90) ||
+ return (b1 == 0xf0 && (b2 < 0x90 || b2 > 0xbf)) ||
+ (b1 == 0xf4 && (b2 & 0xf0) != 0x80) ||
(b2 & 0xc0) != 0x80;
}
+ // tests if b1 and b2 are malformed as the first 2 bytes of a
+ // legal`4-byte utf-8 byte sequence.
+ // only used when there is less than 4 bytes left in src buffer,
+ // after isMalformed4_2 has been invoked.
private static boolean isMalformed4_3(int b3) {
return (b3 & 0xc0) != 0x80;
}
@@ -280,7 +286,9 @@ class UTF_8 extends Unicode
// 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int srcRemaining = sl - sp;
if (srcRemaining < 4 || dl - dp < 2) {
- if (srcRemaining > 1 && isMalformed4_2(b1, sa[sp + 1]))
+ b1 &= 0xff;
+ if (b1 > 0xf4 ||
+ srcRemaining > 1 && isMalformed4_2(b1, sa[sp + 1] & 0xff))
return malformedForLength(src, sp, dst, dp, 1);
if (srcRemaining > 2 && isMalformed4_3(sa[sp + 2]))
return malformedForLength(src, sp, dst, dp, 2);
@@ -363,7 +371,9 @@ class UTF_8 extends Unicode
// 4 bytes, 21 bits: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
int srcRemaining = limit - mark;
if (srcRemaining < 4 || dst.remaining() < 2) {
- if (srcRemaining > 1 && isMalformed4_2(b1, src.get()))
+ b1 &= 0xff;
+ if (b1 > 0xf4 ||
+ srcRemaining > 1 && isMalformed4_2(b1, src.get() & 0xff))
return malformedForLength(src, mark, 1);
if (srcRemaining > 2 && isMalformed4_3(src.get()))
return malformedForLength(src, mark, 2);
@@ -518,8 +528,9 @@ class UTF_8 extends Unicode
}
if (malformedInputAction() != CodingErrorAction.REPLACE)
return -1;
-
- if (sp < sl && isMalformed4_2(b1, sa[sp])) {
+ b1 &= 0xff;
+ if (b1 > 0xf4 ||
+ sp < sl && isMalformed4_2(b1, sa[sp] & 0xff)) {
da[dp++] = replacement().charAt(0);
continue;
}
diff --git a/jdk/src/share/classes/sun/security/pkcs/PKCS7.java b/jdk/src/share/classes/sun/security/pkcs/PKCS7.java
index fdc295c692d..19211ae7b0e 100644
--- a/jdk/src/share/classes/sun/security/pkcs/PKCS7.java
+++ b/jdk/src/share/classes/sun/security/pkcs/PKCS7.java
@@ -802,7 +802,8 @@ public class PKCS7 {
byte[] content,
String signatureAlgorithm,
URI tsaURI,
- String tSAPolicyID)
+ String tSAPolicyID,
+ String tSADigestAlg)
throws CertificateException, IOException, NoSuchAlgorithmException
{
@@ -811,7 +812,8 @@ public class PKCS7 {
if (tsaURI != null) {
// Timestamp the signature
HttpTimestamper tsa = new HttpTimestamper(tsaURI);
- byte[] tsToken = generateTimestampToken(tsa, tSAPolicyID, signature);
+ byte[] tsToken = generateTimestampToken(
+ tsa, tSAPolicyID, tSADigestAlg, signature);
// Insert the timestamp token into the PKCS #7 signer info element
// (as an unsigned attribute)
@@ -869,6 +871,7 @@ public class PKCS7 {
*/
private static byte[] generateTimestampToken(Timestamper tsa,
String tSAPolicyID,
+ String tSADigestAlg,
byte[] toBeTimestamped)
throws IOException, CertificateException
{
@@ -876,11 +879,10 @@ public class PKCS7 {
MessageDigest messageDigest = null;
TSRequest tsQuery = null;
try {
- // SHA-1 is always used.
- messageDigest = MessageDigest.getInstance("SHA-1");
+ messageDigest = MessageDigest.getInstance(tSADigestAlg);
tsQuery = new TSRequest(tSAPolicyID, toBeTimestamped, messageDigest);
} catch (NoSuchAlgorithmException e) {
- // ignore
+ throw new IllegalArgumentException(e);
}
// Generate a nonce
@@ -908,9 +910,13 @@ public class PKCS7 {
PKCS7 tsToken = tsReply.getToken();
TimestampToken tst = tsReply.getTimestampToken();
- if (!tst.getHashAlgorithm().getName().equals("SHA-1")) {
- throw new IOException("Digest algorithm not SHA-1 in "
- + "timestamp token");
+ try {
+ if (!tst.getHashAlgorithm().equals(AlgorithmId.get(tSADigestAlg))) {
+ throw new IOException("Digest algorithm not " + tSADigestAlg + " in "
+ + "timestamp token");
+ }
+ } catch (NoSuchAlgorithmException nase) {
+ throw new IllegalArgumentException(); // should have been caught before
}
if (!MessageDigest.isEqual(tst.getHashedMessage(),
tsQuery.getHashedMessage())) {
diff --git a/jdk/src/share/classes/sun/security/provider/SeedGenerator.java b/jdk/src/share/classes/sun/security/provider/SeedGenerator.java
index 4856662b4c2..c4438da2a90 100644
--- a/jdk/src/share/classes/sun/security/provider/SeedGenerator.java
+++ b/jdk/src/share/classes/sun/security/provider/SeedGenerator.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -179,8 +179,8 @@ abstract class SeedGenerator {
md.update(p.getProperty(s).getBytes());
}
- md.update
- (InetAddress.getLocalHost().toString().getBytes());
+ // Include network adapter names (and a Mac address)
+ addNetworkAdapterInfo(md);
// The temporary dir
File f = new File(p.getProperty("java.io.tmpdir"));
@@ -221,6 +221,31 @@ abstract class SeedGenerator {
return md.digest();
}
+ /*
+ * Include network adapter names and, if available, a Mac address
+ *
+ * See also java.util.concurrent.ThreadLocalRandom.initialSeed()
+ */
+ private static void addNetworkAdapterInfo(MessageDigest md) {
+
+ try {
+ Enumeration ifcs =
+ NetworkInterface.getNetworkInterfaces();
+ while (ifcs.hasMoreElements()) {
+ NetworkInterface ifc = ifcs.nextElement();
+ md.update(ifc.toString().getBytes());
+ if (!ifc.isVirtual()) { // skip fake addresses
+ byte[] bs = ifc.getHardwareAddress();
+ if (bs != null) {
+ md.update(bs);
+ break;
+ }
+ }
+ }
+ } catch (Exception ignore) {
+ }
+ }
+
/**
* Helper function to convert a long into a byte array (least significant
* byte first).
diff --git a/jdk/src/share/classes/sun/security/provider/certpath/AlgorithmChecker.java b/jdk/src/share/classes/sun/security/provider/certpath/AlgorithmChecker.java
index ab75ff00eef..4b6ff56cf40 100644
--- a/jdk/src/share/classes/sun/security/provider/certpath/AlgorithmChecker.java
+++ b/jdk/src/share/classes/sun/security/provider/certpath/AlgorithmChecker.java
@@ -75,7 +75,7 @@ final public class AlgorithmChecker extends PKIXCertPathChecker {
private PublicKey prevPubKey;
private final static Set SIGNATURE_PRIMITIVE_SET =
- EnumSet.of(CryptoPrimitive.SIGNATURE);
+ Collections.unmodifiableSet(EnumSet.of(CryptoPrimitive.SIGNATURE));
private final static DisabledAlgorithmConstraints
certPathDefaultConstraints = new DisabledAlgorithmConstraints(
diff --git a/jdk/src/share/classes/sun/security/rsa/RSAPadding.java b/jdk/src/share/classes/sun/security/rsa/RSAPadding.java
index 35def8b25f2..35b0b64d4a2 100644
--- a/jdk/src/share/classes/sun/security/rsa/RSAPadding.java
+++ b/jdk/src/share/classes/sun/security/rsa/RSAPadding.java
@@ -25,11 +25,9 @@
package sun.security.rsa;
-import java.math.BigInteger;
import java.util.*;
import java.security.*;
-import java.security.interfaces.*;
import java.security.spec.*;
import javax.crypto.BadPaddingException;
@@ -41,21 +39,41 @@ import sun.security.jca.JCAUtil;
/**
* RSA padding and unpadding.
*
- * Format of PKCS#1 v1.5 padding is:
+ * The various PKCS#1 versions can be found in the EMC/RSA Labs
+ * web site, which is currently:
+ *
+ * http://www.emc.com/emc-plus/rsa-labs/index.htm
+ *
+ * or in the IETF RFCs derived from the above PKCS#1 standards.
+ *
+ * RFC 2313: v1.5
+ * RFC 2437: v2.0
+ * RFC 3447: v2.1
+ *
+ * The format of PKCS#1 v1.5 padding is:
+ *
* 0x00 | BT | PS...PS | 0x00 | data...data
+ *
* where BT is the blocktype (1 or 2). The length of the entire string
* must be the same as the size of the modulus (i.e. 128 byte for a 1024 bit
* key). Per spec, the padding string must be at least 8 bytes long. That
* leaves up to (length of key in bytes) - 11 bytes for the data.
*
- * OAEP padding is a bit more complicated and has a number of options.
- * We support:
+ * OAEP padding was introduced in PKCS#1 v2.0 and is a bit more complicated
+ * and has a number of options. We support:
+ *
* . arbitrary hash functions ('Hash' in the specification), MessageDigest
* implementation must be available
* . MGF1 as the mask generation function
* . the empty string as the default value for label L and whatever
* specified in javax.crypto.spec.OAEPParameterSpec
*
+ * The algorithms (representations) are forwards-compatible: that is,
+ * the algorithm described in previous releases are in later releases.
+ * However, additional comments/checks/clarifications were added to the
+ * later versions based on real-world experience (e.g. stricter v1.5
+ * format checking.)
+ *
* Note: RSA keys should be at least 512 bits long
*
* @since 1.5
@@ -156,7 +174,8 @@ public final class RSAPadding {
throw new InvalidAlgorithmParameterException
("Unsupported MGF algo: " + mgfName);
}
- mgfMdName = ((MGF1ParameterSpec)spec.getMGFParameters()).getDigestAlgorithm();
+ mgfMdName = ((MGF1ParameterSpec)spec.getMGFParameters())
+ .getDigestAlgorithm();
PSource pSrc = spec.getPSource();
String pSrcAlgo = pSrc.getAlgorithm();
if (!pSrcAlgo.equalsIgnoreCase("PSpecified")) {
@@ -198,7 +217,7 @@ public final class RSAPadding {
*/
private static byte[] getInitialHash(MessageDigest md,
byte[] digestInput) {
- byte[] result = null;
+ byte[] result;
if ((digestInput == null) || (digestInput.length == 0)) {
String digestName = md.getAlgorithm();
result = emptyHashes.get(digestName);
@@ -213,8 +232,8 @@ public final class RSAPadding {
}
/**
- * Return the maximum size of the plaintext data that can be processed using
- * this object.
+ * Return the maximum size of the plaintext data that can be processed
+ * using this object.
*/
public int getMaxDataSize() {
return maxDataSize;
@@ -262,7 +281,7 @@ public final class RSAPadding {
*/
public byte[] unpad(byte[] padded) throws BadPaddingException {
if (padded.length != paddedSize) {
- throw new BadPaddingException("Padded length must be " + paddedSize);
+ throw new BadPaddingException("Decryption error");
}
switch (type) {
case PAD_NONE:
@@ -282,7 +301,8 @@ public final class RSAPadding {
*/
private byte[] padV15(byte[] data) throws BadPaddingException {
byte[] padded = new byte[paddedSize];
- System.arraycopy(data, 0, padded, paddedSize - data.length, data.length);
+ System.arraycopy(data, 0, padded, paddedSize - data.length,
+ data.length);
int psSize = paddedSize - 3 - data.length;
int k = 0;
padded[k++] = 0;
@@ -317,55 +337,53 @@ public final class RSAPadding {
}
/**
- * PKCS#1 v1.5 unpadding (blocktype 1 and 2).
+ * PKCS#1 v1.5 unpadding (blocktype 1 (signature) and 2 (encryption)).
*
* Note that we want to make it a constant-time operation
*/
private byte[] unpadV15(byte[] padded) throws BadPaddingException {
int k = 0;
- BadPaddingException bpe = null;
+ boolean bp = false;
if (padded[k++] != 0) {
- bpe = new BadPaddingException("Data must start with zero");
+ bp = true;
}
- if (padded[k++] != type && bpe == null) {
- bpe = new BadPaddingException("Blocktype mismatch: " + padded[1]);
+ if (padded[k++] != type) {
+ bp = true;
}
int p = 0;
while (k < padded.length) {
int b = padded[k++] & 0xff;
- if (b == 0 && p == 0) {
+ if ((b == 0) && (p == 0)) {
p = k;
}
- if (k == padded.length && p == 0 && bpe == null) {
- bpe = new BadPaddingException("Padding string not terminated");
+ if ((k == padded.length) && (p == 0)) {
+ bp = true;
}
if ((type == PAD_BLOCKTYPE_1) && (b != 0xff) &&
- p == 0 && bpe == null) {
- bpe = new BadPaddingException("Padding byte not 0xff: " + b);
+ (p == 0)) {
+ bp = true;
}
}
int n = padded.length - p;
- if (n > maxDataSize && bpe == null) {
- bpe = new BadPaddingException("Padding string too short");
+ if (n > maxDataSize) {
+ bp = true;
}
// copy useless padding array for a constant-time method
- //
- // Is it necessary?
byte[] padding = new byte[p];
System.arraycopy(padded, 0, padding, 0, p);
byte[] data = new byte[n];
System.arraycopy(padded, p, data, 0, n);
- if (bpe == null) {
- bpe = new BadPaddingException("Unused exception");
- } else {
- throw bpe;
- }
+ BadPaddingException bpe = new BadPaddingException("Decryption error");
- return data;
+ if (bp) {
+ throw bpe;
+ } else {
+ return data;
+ }
}
/**
@@ -424,10 +442,11 @@ public final class RSAPadding {
*/
private byte[] unpadOAEP(byte[] padded) throws BadPaddingException {
byte[] EM = padded;
+ boolean bp = false;
int hLen = lHash.length;
if (EM[0] != 0) {
- throw new BadPaddingException("Data must start with zero");
+ bp = true;
}
int seedStart = 1;
@@ -442,29 +461,48 @@ public final class RSAPadding {
// verify lHash == lHash'
for (int i = 0; i < hLen; i++) {
if (lHash[i] != EM[dbStart + i]) {
- throw new BadPaddingException("lHash mismatch");
+ bp = true;
}
}
- // skip over padding (0x00 bytes)
- int i = dbStart + hLen;
- while (EM[i] == 0) {
- i++;
- if (i >= EM.length) {
- throw new BadPaddingException("Padding string not terminated");
+ int padStart = dbStart + hLen;
+ int onePos = -1;
+
+ for (int i = padStart; i < EM.length; i++) {
+ int value = EM[i];
+ if (onePos == -1) {
+ if (value == 0x00) {
+ // continue;
+ } else if (value == 0x01) {
+ onePos = i;
+ } else { // Anything other than {0,1} is bad.
+ bp = true;
+ }
}
}
- if (EM[i++] != 1) {
- throw new BadPaddingException
- ("Padding string not terminated by 0x01 byte");
+ // We either ran off the rails or found something other than 0/1.
+ if (onePos == -1) {
+ bp = true;
+ onePos = EM.length - 1; // Don't inadvertently return any data.
}
- int mLen = EM.length - i;
- byte[] m = new byte[mLen];
- System.arraycopy(EM, i, m, 0, mLen);
+ int mStart = onePos + 1;
- return m;
+ // copy useless padding array for a constant-time method
+ byte [] tmp = new byte[mStart - padStart];
+ System.arraycopy(EM, padStart, tmp, 0, tmp.length);
+
+ byte [] m = new byte[EM.length - mStart];
+ System.arraycopy(EM, mStart, m, 0, m.length);
+
+ BadPaddingException bpe = new BadPaddingException("Decryption error");
+
+ if (bp) {
+ throw bpe;
+ } else {
+ return m;
+ }
}
/**
@@ -499,5 +537,4 @@ public final class RSAPadding {
}
}
}
-
}
diff --git a/jdk/src/share/classes/sun/security/ssl/BaseSSLSocketImpl.java b/jdk/src/share/classes/sun/security/ssl/BaseSSLSocketImpl.java
index 240bc052d47..d816a580ae4 100644
--- a/jdk/src/share/classes/sun/security/ssl/BaseSSLSocketImpl.java
+++ b/jdk/src/share/classes/sun/security/ssl/BaseSSLSocketImpl.java
@@ -28,6 +28,7 @@ package sun.security.ssl;
import java.io.*;
import java.nio.channels.SocketChannel;
import java.net.*;
+import java.util.Set;
import javax.net.ssl.*;
@@ -634,6 +635,34 @@ abstract class BaseSSLSocketImpl extends SSLSocket {
}
}
+ @Override
+ public Socket setOption(SocketOption name,
+ T value) throws IOException {
+ if (self == this) {
+ return super.setOption(name, value);
+ } else {
+ return self.setOption(name, value);
+ }
+ }
+
+ @Override
+ public T getOption(SocketOption name) throws IOException {
+ if (self == this) {
+ return super.getOption(name);
+ } else {
+ return self.getOption(name);
+ }
+ }
+
+ @Override
+ public Set> supportedOptions() {
+ if (self == this) {
+ return super.supportedOptions();
+ } else {
+ return self.supportedOptions();
+ }
+ }
+
boolean isLayered() {
return (self != this);
}
diff --git a/jdk/src/share/classes/sun/security/ssl/SignatureAndHashAlgorithm.java b/jdk/src/share/classes/sun/security/ssl/SignatureAndHashAlgorithm.java
index 0d9f14cd5b8..9640ffb8589 100644
--- a/jdk/src/share/classes/sun/security/ssl/SignatureAndHashAlgorithm.java
+++ b/jdk/src/share/classes/sun/security/ssl/SignatureAndHashAlgorithm.java
@@ -68,7 +68,7 @@ final class SignatureAndHashAlgorithm {
// performance optimization
private final static Set SIGNATURE_PRIMITIVE_SET =
- EnumSet.of(CryptoPrimitive.SIGNATURE);
+ Collections.unmodifiableSet(EnumSet.of(CryptoPrimitive.SIGNATURE));
// supported pairs of signature and hash algorithm
private final static Map supportedMap;
diff --git a/jdk/src/share/classes/sun/security/tools/jarsigner/Main.java b/jdk/src/share/classes/sun/security/tools/jarsigner/Main.java
index 75aab4e79b9..ec2247d81b6 100644
--- a/jdk/src/share/classes/sun/security/tools/jarsigner/Main.java
+++ b/jdk/src/share/classes/sun/security/tools/jarsigner/Main.java
@@ -90,9 +90,6 @@ public class Main {
private static final String META_INF = "META-INF/";
- // prefix for new signature-related files in META-INF directory
- private static final String SIG_PREFIX = META_INF + "SIG-";
-
private static final Class>[] PARAM_STRING = { String.class };
private static final String NONE = "NONE";
@@ -142,6 +139,7 @@ public class Main {
String tsaAlias; // alias for the Timestamping Authority's certificate
String altCertChain; // file to read alternative cert chain from
String tSAPolicyID;
+ String tSADigestAlg = "SHA-256";
boolean verify = false; // verify the jar
String verbose = null; // verbose output when signing/verifying
boolean showcerts = false; // show certs when verifying
@@ -345,6 +343,9 @@ public class Main {
} else if (collator.compare(flags, "-tsapolicyid") ==0) {
if (++n == args.length) usageNoArg();
tSAPolicyID = args[n];
+ } else if (collator.compare(flags, "-tsadigestalg") ==0) {
+ if (++n == args.length) usageNoArg();
+ tSADigestAlg = args[n];
} else if (collator.compare(flags, "-debug") ==0) {
debug = true;
} else if (collator.compare(flags, "-keypass") ==0) {
@@ -538,6 +539,9 @@ public class Main {
System.out.println(rb.getString
(".tsapolicyid.tsapolicyid.for.Timestamping.Authority"));
System.out.println();
+ System.out.println(rb.getString
+ (".tsadigestalg.algorithm.of.digest.data.in.timestamping.request"));
+ System.out.println();
System.out.println(rb.getString
(".altsigner.class.class.name.of.an.alternative.signing.mechanism"));
System.out.println();
@@ -1273,8 +1277,8 @@ public class Main {
try {
block =
sf.generateBlock(privateKey, sigalg, certChain,
- externalSF, tsaUrl, tsaCert, tSAPolicyID, signingMechanism, args,
- zipFile);
+ externalSF, tsaUrl, tsaCert, tSAPolicyID, tSADigestAlg,
+ signingMechanism, args, zipFile);
} catch (SocketTimeoutException e) {
// Provide a helpful message when TSA is beyond a firewall
error(rb.getString("unable.to.sign.jar.") +
@@ -1522,22 +1526,7 @@ public class Main {
* . META-INF/*.EC
*/
private boolean signatureRelated(String name) {
- String ucName = name.toUpperCase(Locale.ENGLISH);
- if (ucName.equals(JarFile.MANIFEST_NAME) ||
- ucName.equals(META_INF) ||
- (ucName.startsWith(SIG_PREFIX) &&
- ucName.indexOf("/") == ucName.lastIndexOf("/"))) {
- return true;
- }
-
- if (ucName.startsWith(META_INF) &&
- SignatureFileVerifier.isBlockOrSF(ucName)) {
- // .SF/.DSA/.RSA/.EC files in META-INF subdirs
- // are not considered signature-related
- return (ucName.indexOf("/") == ucName.lastIndexOf("/"));
- }
-
- return false;
+ return SignatureFileVerifier.isSigningRelated(name);
}
Map cacheForSignerInfo = new IdentityHashMap<>();
@@ -2272,13 +2261,14 @@ class SignatureFile {
boolean externalSF, String tsaUrl,
X509Certificate tsaCert,
String tSAPolicyID,
+ String tSADigestAlg,
ContentSigner signingMechanism,
String[] args, ZipFile zipFile)
throws NoSuchAlgorithmException, InvalidKeyException, IOException,
SignatureException, CertificateException
{
return new Block(this, privateKey, sigalg, certChain, externalSF,
- tsaUrl, tsaCert, tSAPolicyID, signingMechanism, args, zipFile);
+ tsaUrl, tsaCert, tSAPolicyID, tSADigestAlg, signingMechanism, args, zipFile);
}
@@ -2292,8 +2282,8 @@ class SignatureFile {
*/
Block(SignatureFile sfg, PrivateKey privateKey, String sigalg,
X509Certificate[] certChain, boolean externalSF, String tsaUrl,
- X509Certificate tsaCert, String tSAPolicyID, ContentSigner signingMechanism,
- String[] args, ZipFile zipFile)
+ X509Certificate tsaCert, String tSAPolicyID, String tSADigestAlg,
+ ContentSigner signingMechanism, String[] args, ZipFile zipFile)
throws NoSuchAlgorithmException, InvalidKeyException, IOException,
SignatureException, CertificateException {
@@ -2375,7 +2365,8 @@ class SignatureFile {
// Assemble parameters for the signing mechanism
ContentSignerParameters params =
- new JarSignerParameters(args, tsaUri, tsaCert, tSAPolicyID, signature,
+ new JarSignerParameters(args, tsaUri, tsaCert, tSAPolicyID,
+ tSADigestAlg, signature,
signatureAlgorithm, certChain, content, zipFile);
// Generate the signature block
@@ -2420,24 +2411,26 @@ class JarSignerParameters implements ContentSignerParameters {
private byte[] content;
private ZipFile source;
private String tSAPolicyID;
+ private String tSADigestAlg;
/**
* Create a new object.
*/
JarSignerParameters(String[] args, URI tsa, X509Certificate tsaCertificate,
- String tSAPolicyID,
+ String tSAPolicyID, String tSADigestAlg,
byte[] signature, String signatureAlgorithm,
X509Certificate[] signerCertificateChain, byte[] content,
ZipFile source) {
if (signature == null || signatureAlgorithm == null ||
- signerCertificateChain == null) {
+ signerCertificateChain == null || tSADigestAlg == null) {
throw new NullPointerException();
}
this.args = args;
this.tsa = tsa;
this.tsaCertificate = tsaCertificate;
this.tSAPolicyID = tSAPolicyID;
+ this.tSADigestAlg = tSADigestAlg;
this.signature = signature;
this.signatureAlgorithm = signatureAlgorithm;
this.signerCertificateChain = signerCertificateChain;
@@ -2476,6 +2469,10 @@ class JarSignerParameters implements ContentSignerParameters {
return tSAPolicyID;
}
+ public String getTSADigestAlg() {
+ return tSADigestAlg;
+ }
+
/**
* Retrieves the signature.
*
diff --git a/jdk/src/share/classes/sun/security/tools/jarsigner/Resources.java b/jdk/src/share/classes/sun/security/tools/jarsigner/Resources.java
index 77b06282636..db35b1e5855 100644
--- a/jdk/src/share/classes/sun/security/tools/jarsigner/Resources.java
+++ b/jdk/src/share/classes/sun/security/tools/jarsigner/Resources.java
@@ -88,6 +88,8 @@ public class Resources extends java.util.ListResourceBundle {
"[-tsacert ] public key certificate for Timestamping Authority"},
{".tsapolicyid.tsapolicyid.for.Timestamping.Authority",
"[-tsapolicyid ] TSAPolicyID for Timestamping Authority"},
+ {".tsadigestalg.algorithm.of.digest.data.in.timestamping.request",
+ "[-tsadigestalg ] algorithm of digest data in timestamping request"},
{".altsigner.class.class.name.of.an.alternative.signing.mechanism",
"[-altsigner ] class name of an alternative signing mechanism"},
{".altsignerpath.pathlist.location.of.an.alternative.signing.mechanism",
diff --git a/jdk/src/share/classes/sun/security/tools/jarsigner/TimestampedSigner.java b/jdk/src/share/classes/sun/security/tools/jarsigner/TimestampedSigner.java
index 3e504195367..df9159f78fb 100644
--- a/jdk/src/share/classes/sun/security/tools/jarsigner/TimestampedSigner.java
+++ b/jdk/src/share/classes/sun/security/tools/jarsigner/TimestampedSigner.java
@@ -134,7 +134,8 @@ public final class TimestampedSigner extends ContentSigner {
}
return PKCS7.generateSignedData(signature, signerChain, content,
params.getSignatureAlgorithm(), tsaURI,
- params.getTSAPolicyID());
+ params.getTSAPolicyID(),
+ params.getTSADigestAlg());
}
/**
diff --git a/jdk/src/share/classes/sun/security/util/SignatureFileVerifier.java b/jdk/src/share/classes/sun/security/util/SignatureFileVerifier.java
index 4148dcf67f0..083e23a3700 100644
--- a/jdk/src/share/classes/sun/security/util/SignatureFileVerifier.java
+++ b/jdk/src/share/classes/sun/security/util/SignatureFileVerifier.java
@@ -152,6 +152,52 @@ public class SignatureFileVerifier {
return false;
}
+ /**
+ * Yet another utility method used by JarVerifier and JarSigner
+ * to determine what files are signature related, which includes
+ * the MANIFEST, SF files, known signature block files, and other
+ * unknown signature related files (those starting with SIG- with
+ * an optional [A-Z0-9]{1,3} extension right inside META-INF).
+ *
+ * @param s file name
+ * @return true if the input file name is signature related
+ */
+ public static boolean isSigningRelated(String name) {
+ name = name.toUpperCase(Locale.ENGLISH);
+ if (!name.startsWith("META-INF/")) {
+ return false;
+ }
+ name = name.substring(9);
+ if (name.indexOf('/') != -1) {
+ return false;
+ }
+ if (isBlockOrSF(name) || name.equals("MANIFEST.MF")) {
+ return true;
+ } else if (name.startsWith("SIG-")) {
+ // check filename extension
+ // see http://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html#Digital_Signatures
+ // for what filename extensions are legal
+ int extIndex = name.lastIndexOf('.');
+ if (extIndex != -1) {
+ String ext = name.substring(extIndex + 1);
+ // validate length first
+ if (ext.length() > 3 || ext.length() < 1) {
+ return false;
+ }
+ // then check chars, must be in [a-zA-Z0-9] per the jar spec
+ for (int index = 0; index < ext.length(); index++) {
+ char cc = ext.charAt(index);
+ // chars are promoted to uppercase so skip lowercase checks
+ if ((cc < 'A' || cc > 'Z') && (cc < '0' || cc > '9')) {
+ return false;
+ }
+ }
+ }
+ return true; // no extension is OK
+ }
+ return false;
+ }
+
/** get digest from cache */
private MessageDigest getDigest(String algorithm)
diff --git a/jdk/src/share/classes/sun/tools/jinfo/JInfo.java b/jdk/src/share/classes/sun/tools/jinfo/JInfo.java
index f02eb27d2e2..4911ef713d9 100644
--- a/jdk/src/share/classes/sun/tools/jinfo/JInfo.java
+++ b/jdk/src/share/classes/sun/tools/jinfo/JInfo.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,42 +39,73 @@ import sun.tools.attach.HotSpotVirtualMachine;
* and decides if the command should be satisfied using the VM attach mechanism
* or an SA tool.
*/
-public class JInfo {
+final public class JInfo {
+ private boolean useSA = false;
+ private String[] args = null;
- @SuppressWarnings("fallthrough")
- public static void main(String[] args) throws Exception {
+ private JInfo(String[] args) throws IllegalArgumentException {
if (args.length == 0) {
- usage(1); // no arguments
+ throw new IllegalArgumentException();
}
+ int argCopyIndex = 0;
// First determine if we should launch SA or not
- boolean useSA = false;
if (args[0].equals("-F")) {
// delete the -F
- args = Arrays.copyOfRange(args, 1, args.length);
+ argCopyIndex = 1;
useSA = true;
} else if (args[0].equals("-flags")
- || args[0].equals("-sysprops"))
+ || args[0].equals("-sysprops"))
{
if (args.length == 2) {
- if (!args[1].matches("[0-9]+")) {
+ if (!isPid(args[1])) {
// If args[1] doesn't parse to a number then
// it must be the SA debug server
// (otherwise it is the pid)
useSA = true;
}
- }
- if (args.length == 3) {
+ } else if (args.length == 3) {
// arguments include an executable and a core file
useSA = true;
+ } else {
+ throw new IllegalArgumentException();
}
} else if (!args[0].startsWith("-")) {
if (args.length == 2) {
// the only arguments are an executable and a core file
useSA = true;
+ } else if (args.length == 1) {
+ if (!isPid(args[0])) {
+ // The only argument is not a PID; it must be SA debug
+ // server
+ useSA = true;
+ }
+ } else {
+ throw new IllegalArgumentException();
}
- } else if (args[0].equals("-h")
- || args[0].equals("-help")) {
+ } else if (args[0].equals("-h") || args[0].equals("-help")) {
+ if (args.length > 1) {
+ throw new IllegalArgumentException();
+ }
+ } else if (args[0].equals("-flag")) {
+ if (args.length == 3) {
+ if (!isPid(args[2])) {
+ throw new IllegalArgumentException();
+ }
+ } else {
+ throw new IllegalArgumentException();
+ }
+ } else {
+ throw new IllegalArgumentException();
+ }
+
+ this.args = Arrays.copyOfRange(args, argCopyIndex, args.length);
+ }
+
+ @SuppressWarnings("fallthrough")
+ private void execute() throws Exception {
+ if (args[0].equals("-h")
+ || args[0].equals("-help")) {
usage(0);
}
@@ -87,55 +118,69 @@ public class JInfo {
}
// invoke SA which does it's own argument parsing
- runTool(args);
+ runTool();
} else {
// Now we can parse arguments for the non-SA case
String pid = null;
switch(args[0]) {
- case "-flag":
- if (args.length != 3) {
- usage(1);
- }
- String option = args[1];
- pid = args[2];
- flag(pid, option);
- break;
- case "-flags":
- if (args.length != 2) {
- usage(1);
- }
- pid = args[1];
- flags(pid);
- break;
- case "-sysprops":
- if (args.length != 2) {
- usage(1);
- }
- pid = args[1];
- sysprops(pid);
- break;
- case "-help":
- case "-h":
- usage(0);
- // Fall through
- default:
- if (args.length == 1) {
- // no flags specified, we do -sysprops and -flags
- pid = args[0];
- sysprops(pid);
- System.out.println();
- flags(pid);
- } else {
- usage(1);
- }
+ case "-flag":
+ if (args.length != 3) {
+ usage(1);
+ }
+ String option = args[1];
+ pid = args[2];
+ flag(pid, option);
+ break;
+ case "-flags":
+ if (args.length != 2) {
+ usage(1);
+ }
+ pid = args[1];
+ flags(pid);
+ break;
+ case "-sysprops":
+ if (args.length != 2) {
+ usage(1);
+ }
+ pid = args[1];
+ sysprops(pid);
+ break;
+ case "-help":
+ case "-h":
+ usage(0);
+ // Fall through
+ default:
+ if (args.length == 1) {
+ // no flags specified, we do -sysprops and -flags
+ pid = args[0];
+ sysprops(pid);
+ System.out.println();
+ flags(pid);
+ } else {
+ usage(1);
+ }
}
}
}
+ public static void main(String[] args) throws Exception {
+ JInfo jinfo = null;
+ try {
+ jinfo = new JInfo(args);
+ jinfo.execute();
+ } catch (IllegalArgumentException e) {
+ usage(1);
+ }
+ }
+
+ private static boolean isPid(String arg) {
+ return arg.matches("[0-9]+");
+ }
+
// Invoke SA tool with the given arguments
- private static void runTool(String args[]) throws Exception {
+ private void runTool() throws Exception {
String tool = "sun.jvm.hotspot.tools.JInfo";
// Tool not available on this platform.
Class> c = loadClass(tool);
diff --git a/jdk/src/share/demo/nio/zipfs/README.txt b/jdk/src/share/demo/nio/zipfs/README.txt
deleted file mode 100644
index e147b2900ec..00000000000
--- a/jdk/src/share/demo/nio/zipfs/README.txt
+++ /dev/null
@@ -1,26 +0,0 @@
-ZipFileSystem is a file system provider that treats the contents of a zip or
-JAR file as a java.nio.file.FileSystem.
-
-The factory methods defined by the java.nio.file.FileSystems class can be
-used to create a FileSystem, eg:
-
- // use file type detection
- Path jarfile = Paths.get("foo.jar");
- FileSystem fs = FileSystems.newFileSystem(jarfile, null);
-
--or
-
- // locate file system by the legacy JAR URL syntax
- Map env = Collections.emptyMap();
- URI uri = URI.create("jar:file:/mydir/foo.jar");
- FileSystem fs = FileSystems.newFileSystem(uri, env);
-
-Once a FileSystem is created then classes in the java.nio.file package
-can be used to access files in the zip/JAR file, eg:
-
- Path mf = fs.getPath("/META-INF/MANIFEST.MF");
- InputStream in = mf.newInputStream();
-
-See Demo.java for more interesting usages.
-
-
diff --git a/jdk/src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider b/jdk/src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider
deleted file mode 100644
index 58ee3a6b972..00000000000
--- a/jdk/src/share/demo/nio/zipfs/src/META-INF/services/java.nio.file.spi.FileSystemProvider
+++ /dev/null
@@ -1,2 +0,0 @@
-com.sun.nio.zipfs.ZipFileSystemProvider
-
diff --git a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/JarFileSystemProvider.java b/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/JarFileSystemProvider.java
deleted file mode 100644
index e1c43d18e12..00000000000
--- a/jdk/src/share/demo/nio/zipfs/src/com/sun/nio/zipfs/JarFileSystemProvider.java
+++ /dev/null
@@ -1,97 +0,0 @@
-/*
- * Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
- *
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
- *
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-package com.sun.nio.zipfs;
-
-import java.nio.file.*;
-import java.nio.file.spi.*;
-import java.nio.file.attribute.*;
-import java.nio.file.spi.FileSystemProvider;
-
-import java.net.URI;
-import java.io.IOException;
-import java.net.URISyntaxException;
-import java.nio.channels.FileChannel;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Set;
-
-public class JarFileSystemProvider extends ZipFileSystemProvider
-{
-
- @Override
- public String getScheme() {
- return "jar";
- }
-
- @Override
- protected Path uriToPath(URI uri) {
- String scheme = uri.getScheme();
- if ((scheme == null) || !scheme.equalsIgnoreCase(getScheme())) {
- throw new IllegalArgumentException("URI scheme is not '" + getScheme() + "'");
- }
- try {
- String uristr = uri.toString();
- int end = uristr.indexOf("!/");
- uristr = uristr.substring(4, (end == -1) ? uristr.length() : end);
- uri = new URI(uristr);
- return Paths.get(new URI("file", uri.getHost(), uri.getPath(), null))
- .toAbsolutePath();
- } catch (URISyntaxException e) {
- throw new AssertionError(e); //never thrown
- }
- }
-
- @Override
- public Path getPath(URI uri) {
- FileSystem fs = getFileSystem(uri);
- String path = uri.getFragment();
- if (path == null) {
- String uristr = uri.toString();
- int off = uristr.indexOf("!/");
- if (off != -1)
- path = uristr.substring(off + 2);
- }
- if (path != null)
- return fs.getPath(path);
- throw new IllegalArgumentException("URI: "
- + uri
- + " does not contain path fragment ex. jar:///c:/foo.zip!/BAR");
- }
-}
diff --git a/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp b/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp
index f3dd2cc1096..daf1b042428 100644
--- a/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp
+++ b/jdk/src/share/native/com/sun/java/util/jar/pack/unpack.cpp
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -5166,39 +5166,7 @@ void unpacker::redirect_stdio() {
} else if (log_file[0] != '\0' && (errstrm = fopen(log_file,"a+")) != NULL) {
return;
} else {
- char log_file_name[PATH_MAX+100];
- char tmpdir[PATH_MAX];
-#ifdef WIN32
- int n = GetTempPath(PATH_MAX,tmpdir); //API returns with trailing '\'
- if (n < 1 || n > PATH_MAX) {
- sprintf(tmpdir,"C:\\");
- }
- sprintf(log_file_name, "%sunpack.log", tmpdir);
-#else
- sprintf(tmpdir,"/tmp");
- sprintf(log_file_name, "/tmp/unpack.log");
-#endif
- if ((errstrm = fopen(log_file_name, "a+")) != NULL) {
- log_file = errstrm_name = saveStr(log_file_name);
- return ;
- }
-
- char *tname = tempnam(tmpdir,"#upkg");
- if (tname == NULL) return;
- sprintf(log_file_name, "%s", tname);
- ::free(tname);
- if ((errstrm = fopen(log_file_name, "a+")) != NULL) {
- log_file = errstrm_name = saveStr(log_file_name);
- return ;
- }
-#ifndef WIN32
- sprintf(log_file_name, "/dev/null");
- // On windows most likely it will fail.
- if ( (errstrm = fopen(log_file_name, "a+")) != NULL) {
- log_file = errstrm_name = saveStr(log_file_name);
- return ;
- }
-#endif
+ fprintf(stderr, "Can not open log file %s\n", log_file);
// Last resort
// (Do not use stdout, since it might be jarout->jarfp.)
errstrm = stderr;
diff --git a/jdk/src/share/native/java/net/net_util.h b/jdk/src/share/native/java/net/net_util.h
index a31d849e0b9..43739a2c498 100644
--- a/jdk/src/share/native/java/net/net_util.h
+++ b/jdk/src/share/native/java/net/net_util.h
@@ -40,7 +40,7 @@
#define IPv6 2
#define NET_ERROR(env, ex, msg) \
-{ if (!(*env)->ExceptionOccurred(env)) JNU_ThrowByName(env, ex, msg) }
+{ if (!(*env)->ExceptionOccurred(env)) JNU_ThrowByName(env, ex, msg); }
/************************************************************************
* Cached field IDs
diff --git a/jdk/src/share/native/sun/awt/giflib/dgif_lib.c b/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
index 742ae9c3335..1a9e2cce125 100644
--- a/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
+++ b/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
@@ -435,9 +435,7 @@ DGifGetImageDesc(GifFileType * GifFile) {
Private->PixelCount = (long)GifFile->Image.Width *
(long)GifFile->Image.Height;
- DGifSetupDecompress(GifFile); /* Reset decompress algorithm parameters. */
-
- return GIF_OK;
+ return DGifSetupDecompress(GifFile); /* Reset decompress algorithm parameters. */
}
/******************************************************************************
diff --git a/jdk/src/share/native/sun/awt/image/gif/gifdecoder.c b/jdk/src/share/native/sun/awt/image/gif/gifdecoder.c
index 6730695c51b..e93feb6c8e9 100644
--- a/jdk/src/share/native/sun/awt/image/gif/gifdecoder.c
+++ b/jdk/src/share/native/sun/awt/image/gif/gifdecoder.c
@@ -249,6 +249,7 @@ Java_sun_awt_image_GifImageDecoder_parseImage(JNIEnv *env,
/* fill the block */
len = (*env)->CallIntMethod(env, this, readID,
blockh, remain, blockLength + 1);
+ if (len > blockLength + 1) len = blockLength + 1;
if ((*env)->ExceptionOccurred(env)) {
return 0;
}
diff --git a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
index 3698bc49b2e..f108dde9f8b 100644
--- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
+++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
@@ -945,6 +945,9 @@ imageio_fill_input_buffer(j_decompress_ptr cinfo)
JPEGImageReader_readInputDataID,
sb->hstreamBuffer, 0,
sb->bufferLength);
+ if ((ret > 0) && ((unsigned int)ret > sb->bufferLength)) {
+ ret = sb->bufferLength;
+ }
if ((*env)->ExceptionOccurred(env)
|| !GET_ARRAYS(env, data, &(src->next_input_byte))) {
cinfo->err->error_exit((j_common_ptr) cinfo);
@@ -1041,6 +1044,7 @@ imageio_fill_suspended_buffer(j_decompress_ptr cinfo)
JPEGImageReader_readInputDataID,
sb->hstreamBuffer,
offset, buflen);
+ if ((ret > 0) && ((unsigned int)ret > buflen)) ret = buflen;
if ((*env)->ExceptionOccurred(env)
|| !GET_ARRAYS(env, data, &(src->next_input_byte))) {
cinfo->err->error_exit((j_common_ptr) cinfo);
diff --git a/jdk/src/share/native/sun/awt/image/jpeg/jdmarker.c b/jdk/src/share/native/sun/awt/image/jpeg/jdmarker.c
index eeb9b64fd1e..2bcf4714376 100644
--- a/jdk/src/share/native/sun/awt/image/jpeg/jdmarker.c
+++ b/jdk/src/share/native/sun/awt/image/jpeg/jdmarker.c
@@ -349,6 +349,12 @@ get_sos (j_decompress_ptr cinfo)
TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
compptr->dc_tbl_no, compptr->ac_tbl_no);
+
+ /* This CSi (cc) should differ from the previous CSi */
+ for (ci = 0; ci < i; ci++) {
+ if (cinfo->cur_comp_info[ci] == compptr)
+ ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
+ }
}
/* Collect the additional scan parameters Ss, Se, Ah/Al. */
diff --git a/jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c b/jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c
index 1ccfc390b24..ba8405c86c3 100644
--- a/jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c
+++ b/jdk/src/share/native/sun/awt/image/jpeg/jpegdecoder.c
@@ -289,6 +289,7 @@ sun_jpeg_fill_input_buffer(j_decompress_ptr cinfo)
buflen = (*env)->GetArrayLength(env, src->hInputBuffer);
ret = (*env)->CallIntMethod(env, src->hInputStream, InputStream_readID,
src->hInputBuffer, 0, buflen);
+ if (ret > buflen) ret = buflen;
if ((*env)->ExceptionOccurred(env) || !GET_ARRAYS(env, src)) {
cinfo->err->error_exit((struct jpeg_common_struct *) cinfo);
}
@@ -349,6 +350,7 @@ sun_jpeg_fill_suspended_buffer(j_decompress_ptr cinfo)
}
ret = (*env)->CallIntMethod(env, src->hInputStream, InputStream_readID,
src->hInputBuffer, offset, buflen);
+ if ((ret > 0) && ((unsigned int)ret > buflen)) ret = buflen;
if ((*env)->ExceptionOccurred(env) || !GET_ARRAYS(env, src)) {
cinfo->err->error_exit((struct jpeg_common_struct *) cinfo);
}
@@ -424,6 +426,7 @@ sun_jpeg_skip_input_data(j_decompress_ptr cinfo, long num_bytes)
ret = (*env)->CallIntMethod(env, src->hInputStream,
InputStream_readID,
src->hInputBuffer, 0, buflen);
+ if (ret > buflen) ret = buflen;
if ((*env)->ExceptionOccurred(env)) {
cinfo->err->error_exit((struct jpeg_common_struct *) cinfo);
}
diff --git a/jdk/src/share/native/sun/awt/libpng/pngrtran.c b/jdk/src/share/native/sun/awt/libpng/pngrtran.c
index e2a04160fea..98d28140b6d 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngrtran.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngrtran.c
@@ -1862,6 +1862,9 @@ png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
info_ptr->bit_depth = 8;
info_ptr->num_trans = 0;
+
+ if (png_ptr->palette == NULL)
+ png_error (png_ptr, "Palette is NULL in indexed image");
}
else
{
diff --git a/jdk/src/share/native/sun/awt/libpng/pngset.c b/jdk/src/share/native/sun/awt/libpng/pngset.c
index e4f675c679a..819605f5025 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngset.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngset.c
@@ -512,6 +512,17 @@ png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
}
}
+ if ((num_palette > 0 && palette == NULL) ||
+ (num_palette == 0
+# ifdef PNG_MNG_FEATURES_SUPPORTED
+ && (png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) == 0
+# endif
+ ))
+ {
+ png_error(png_ptr, "Invalid palette");
+ return;
+ }
+
/* It may not actually be necessary to set png_ptr->palette here;
* we do it for backward compatibility with the way the png_handle_tRNS
* function used to do the allocation.
diff --git a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
index db69fd78e4f..1ed87f7b58f 100644
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
@@ -228,6 +228,49 @@ getMlibEdgeHint(jint edgeHint) {
}
}
+/*
+ * We have to make sure that awt_setPixels can be safely applied to the given pair of
+ * raster and mlib image.
+ *
+ * In particular, make sure that
+ * - dimension is the same
+ * - number of channels in mlib image corresponds to the number of bands in the raster
+ * - sample size in image and raster are the same.
+ *
+ * Returns:
+ * -1 to indicate failure,
+ * 1 to indicate success
+ */
+static int setPixelsFormMlibImage(JNIEnv *env, RasterS_t *rasterP, mlib_image* img) {
+ if (rasterP->width != img->width || rasterP->height != img->height) {
+ /* dimension does not match */
+ return -1;
+ }
+
+ if (rasterP->numBands != img->channels) {
+ /* number of bands does not match */
+ return -1;
+ }
+
+ switch (rasterP->dataType) {
+ case BYTE_DATA_TYPE:
+ if (img->type != MLIB_BYTE) {
+ return -1;
+ }
+ break;
+ case SHORT_DATA_TYPE:
+ if (img->type != MLIB_SHORT && img->type != MLIB_USHORT) {
+ return -1;
+ }
+ break;
+ default:
+ /* awt_setPixels does not support such rasters */
+ return -1;
+ }
+
+ return awt_setPixels(env, rasterP, mlib_ImageGetData(img));
+}
+
/***************************************************************************
* External Functions *
***************************************************************************/
@@ -700,7 +743,9 @@ Java_sun_awt_image_ImagingLib_convolveRaster(JNIEnv *env, jobject this,
/* Means that we couldn't write directly into the destination buffer */
if (ddata == NULL) {
- retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
+ if (storeRasterArray(env, srcRasterP, dstRasterP, dst) < 0) {
+ retStatus = setPixelsFormMlibImage(env, dstRasterP, dst);
+ }
}
/* Release the pinned memory */
@@ -1107,7 +1152,7 @@ fprintf(stderr,"Flags : %d\n",dst->flags);
/* Need to store it back into the array */
if (storeRasterArray(env, srcRasterP, dstRasterP, dst) < 0) {
(*env)->ExceptionClear(env); // Could not store the array, try another way
- retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
+ retStatus = setPixelsFormMlibImage(env, dstRasterP, dst);
}
}
@@ -1433,6 +1478,14 @@ Java_sun_awt_image_ImagingLib_lookupByteBI(JNIEnv *env, jobject thisLib,
retStatus = 0;
}
+ /* Release the LUT */
+ for (i=0; i < lut_nbands; i++) {
+ (*env)->ReleasePrimitiveArrayCritical(env, jtable[i].jArray,
+ (jbyte *) jtable[i].table, JNI_ABORT);
+ }
+ free ((void *) jtable);
+ free ((void *) tbl);
+
/*
* Means that we couldn't write directly into
* the destination buffer
@@ -1446,13 +1499,6 @@ Java_sun_awt_image_ImagingLib_lookupByteBI(JNIEnv *env, jobject thisLib,
}
}
- /* Release the LUT */
- for (i=0; i < lut_nbands; i++) {
- (*env)->ReleasePrimitiveArrayCritical(env, jtable[i].jArray,
- (jbyte *) jtable[i].table, JNI_ABORT);
- }
- free ((void *) jtable);
- free ((void *) tbl);
/* Release the pinned memory */
freeArray(env, srcImageP, src, sdata, dstImageP, dst, ddata);
@@ -1670,18 +1716,20 @@ Java_sun_awt_image_ImagingLib_lookupByteRaster(JNIEnv *env,
retStatus = 0;
}
+ /* Release the LUT */
+ for (i=0; i < lut_nbands; i++) {
+ (*env)->ReleasePrimitiveArrayCritical(env, jtable[i].jArray,
+ (jbyte *) jtable[i].table, JNI_ABORT);
+ }
+
/*
* Means that we couldn't write directly into
* the destination buffer
*/
if (ddata == NULL) {
- retStatus = awt_setPixels(env, dstRasterP, mlib_ImageGetData(dst));
- }
-
- /* Release the LUT */
- for (i=0; i < lut_nbands; i++) {
- (*env)->ReleasePrimitiveArrayCritical(env, jtable[i].jArray,
- (jbyte *) jtable[i].table, JNI_ABORT);
+ if (storeRasterArray(env, srcRasterP, dstRasterP, dst) < 0) {
+ retStatus = setPixelsFormMlibImage(env, dstRasterP, dst);
+ }
}
/* Release the pinned memory */
@@ -2643,7 +2691,7 @@ storeImageArray(JNIEnv *env, BufImageS_t *srcP, BufImageS_t *dstP,
}
}
else if (mlibImP->type == MLIB_SHORT) {
- return awt_setPixels(env, rasterP, mlibImP->data);
+ return setPixelsFormMlibImage(env, rasterP, mlibImP);
}
}
else {
diff --git a/jdk/src/share/native/sun/font/layout/ContextualGlyphSubstProc2.cpp b/jdk/src/share/native/sun/font/layout/ContextualGlyphSubstProc2.cpp
index 6e8d070be99..f6d93b48bf7 100644
--- a/jdk/src/share/native/sun/font/layout/ContextualGlyphSubstProc2.cpp
+++ b/jdk/src/share/native/sun/font/layout/ContextualGlyphSubstProc2.cpp
@@ -154,6 +154,7 @@ TTGlyphID ContextualGlyphSubstitutionProcessor2::lookup(le_uint32 offset, LEGlyp
TTGlyphID glyphCode = (TTGlyphID) LE_GET_GLYPH(gid);
if ((glyphCode >= firstGlyph) && (glyphCode < lastGlyph)) {
LEReferenceToArrayOf valueArray(lookupTable8, success, &lookupTable8->valueArray[0], glyphCount);
+ if (LE_FAILURE(success)) { return newGlyph; }
newGlyph = SWAPW(valueArray(glyphCode - firstGlyph, success));
}
}
diff --git a/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp b/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp
index 67a9c092330..3707efdfb4f 100644
--- a/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp
+++ b/jdk/src/share/native/sun/font/layout/ContextualSubstSubtables.cpp
@@ -110,6 +110,8 @@ le_bool ContextualSubstitutionBase::matchGlyphClasses(
LEErrorCode &success,
le_bool backtrack)
{
+ if (LE_FAILURE(success)) { return FALSE; }
+
le_int32 direction = 1;
le_int32 match = 0;
@@ -255,6 +257,7 @@ le_uint32 ContextualSubstitutionFormat1Subtable::process(const LETableReference
le_uint16 matchCount = SWAPW(subRuleTable->glyphCount) - 1;
le_uint16 substCount = SWAPW(subRuleTable->substCount);
LEReferenceToArrayOf inputGlyphArray(base, success, subRuleTable->inputGlyphArray, matchCount+2);
+ if (LE_FAILURE(success)) { return 0; }
if (matchGlyphIDs(inputGlyphArray, matchCount, glyphIterator)) {
LEReferenceToArrayOf
substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) &subRuleTable->inputGlyphArray[matchCount], substCount);
@@ -315,6 +318,7 @@ le_uint32 ContextualSubstitutionFormat2Subtable::process(const LETableReference
LEReferenceToArrayOf classArray(base, success, subClassRuleTable->classArray, matchCount+1);
+ if (LE_FAILURE(success)) { return 0; }
if (matchGlyphClasses(classArray, matchCount, glyphIterator, classDefinitionTable, success)) {
LEReferenceToArrayOf
substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) &subClassRuleTable->classArray[matchCount], substCount);
@@ -573,7 +577,7 @@ le_uint32 ChainingContextualSubstitutionFormat2Subtable::process(const LETableRe
if (matchGlyphClasses(inputClassArray, inputGlyphCount, glyphIterator, inputClassDefinitionTable, success)) {
LEReferenceToArrayOf
substLookupRecordArray(base, success, (const SubstitutionLookupRecord *) lookaheadClassArray.getAlias(lookaheadGlyphCount + 1, success), substCount);
-
+ if (LE_FAILURE(success)) { return 0; }
applySubstitutionLookups(lookupProcessor, substLookupRecordArray, substCount, glyphIterator, fontInstance, position, success);
return inputGlyphCount + 1;
@@ -601,9 +605,10 @@ le_uint32 ChainingContextualSubstitutionFormat3Subtable::process(const LETableRe
le_uint16 backtrkGlyphCount = SWAPW(backtrackGlyphCount);
le_uint16 inputGlyphCount = (le_uint16) SWAPW(backtrackCoverageTableOffsetArray[backtrkGlyphCount]);
LEReferenceToArrayOf inputCoverageTableOffsetArray(base, success, &backtrackCoverageTableOffsetArray[backtrkGlyphCount + 1], inputGlyphCount+2); // offset
+ if (LE_FAILURE(success)) { return 0; }
const le_uint16 lookaheadGlyphCount = (le_uint16) SWAPW(inputCoverageTableOffsetArray[inputGlyphCount]);
- if( LE_FAILURE(success) ) { return 0; }
+ if( LE_FAILURE(success)) { return 0; }
LEReferenceToArrayOf lookaheadCoverageTableOffsetArray(base, success, inputCoverageTableOffsetArray.getAlias(inputGlyphCount + 1, success), lookaheadGlyphCount+2);
if( LE_FAILURE(success) ) { return 0; }
diff --git a/jdk/src/share/native/sun/font/layout/LigatureSubstProc2.cpp b/jdk/src/share/native/sun/font/layout/LigatureSubstProc2.cpp
index 2e570bfe62d..8e5b1cfa93d 100644
--- a/jdk/src/share/native/sun/font/layout/LigatureSubstProc2.cpp
+++ b/jdk/src/share/native/sun/font/layout/LigatureSubstProc2.cpp
@@ -95,7 +95,7 @@ le_uint16 LigatureSubstitutionProcessor2::processStateEntry(LEGlyphStorage &glyp
if (actionOffset != 0) {
LEReferenceTo ap(stHeader, success, ligActionOffset); // byte offset
- ap.addObject(ligActionIndex - 1, success); // index offset ( one before the actual start, because we will pre-increment)
+ ap.addObject(ligActionIndex, success);
LEReferenceToArrayOf ligatureTable(stHeader, success, ligatureOffset, LE_UNBOUNDED_ARRAY);
LigatureActionEntry action;
le_int32 offset, i = 0;
@@ -111,7 +111,6 @@ le_uint16 LigatureSubstitutionProcessor2::processStateEntry(LEGlyphStorage &glyp
do {
le_uint32 componentGlyph = componentStack[m--]; // pop off
- ap.addObject(success);
action = SWAPL(*ap.getAlias());
if (m < 0) {
@@ -145,7 +144,8 @@ le_uint16 LigatureSubstitutionProcessor2::processStateEntry(LEGlyphStorage &glyp
LE_DEBUG_BAD_FONT("m<0")
}
#endif
- } while (!(action & lafLast) && (m>=0) ); // stop if last bit is set, or if run out of items
+ ap.addObject(success);
+ } while (LE_SUCCESS(success) && !(action & lafLast) && (m>=0) ); // stop if last bit is set, or if run out of items
while (mm >= 0) {
if (++m >= nComponents) {
diff --git a/jdk/src/share/native/sun/font/layout/LookupProcessor.cpp b/jdk/src/share/native/sun/font/layout/LookupProcessor.cpp
index 44c78c389d4..b5d750d9a98 100644
--- a/jdk/src/share/native/sun/font/layout/LookupProcessor.cpp
+++ b/jdk/src/share/native/sun/font/layout/LookupProcessor.cpp
@@ -282,6 +282,7 @@ LookupProcessor::LookupProcessor(const LETableReference &baseAddress,
for (le_uint16 feature = 0; feature < featureCount; feature += 1) {
LEReferenceToArrayOf featureIndexArray(langSysTable, success, langSysTable->featureIndexArray, featureCount);
+ if (LE_FAILURE(success)) { continue; }
le_uint16 featureIndex = SWAPW(featureIndexArray.getObject(feature,success));
// don't add the required feature to the list more than once...
diff --git a/jdk/src/share/native/sun/font/layout/MarkToBasePosnSubtables.cpp b/jdk/src/share/native/sun/font/layout/MarkToBasePosnSubtables.cpp
index aaa99fd5b25..74feb89f236 100644
--- a/jdk/src/share/native/sun/font/layout/MarkToBasePosnSubtables.cpp
+++ b/jdk/src/share/native/sun/font/layout/MarkToBasePosnSubtables.cpp
@@ -67,6 +67,7 @@ le_int32 MarkToBasePositioningSubtable::process(const LETableReference &base, Gl
LEPoint markAnchor;
LEReferenceTo markArray(base, success, (const MarkArray *) ((char *) this + SWAPW(markArrayOffset)));
+ if(LE_FAILURE(success)) return 0;
le_int32 markClass = markArray->getMarkClass(markArray, markGlyph, markCoverage, fontInstance, markAnchor, success);
le_uint16 mcCount = SWAPW(classCount);
diff --git a/jdk/src/share/native/sun/font/layout/OpenTypeUtilities.cpp b/jdk/src/share/native/sun/font/layout/OpenTypeUtilities.cpp
index 4d810df69f8..716b575622b 100644
--- a/jdk/src/share/native/sun/font/layout/OpenTypeUtilities.cpp
+++ b/jdk/src/share/native/sun/font/layout/OpenTypeUtilities.cpp
@@ -79,8 +79,8 @@ le_int8 OpenTypeUtilities::highBit(le_int32 value)
Offset OpenTypeUtilities::getTagOffset(LETag tag, const LEReferenceToArrayOf &records, LEErrorCode &success)
{
- const TagAndOffsetRecord *r0 = (const TagAndOffsetRecord*)records.getAlias();
if(LE_FAILURE(success)) return 0;
+ const TagAndOffsetRecord *r0 = (const TagAndOffsetRecord*)records.getAlias();
le_uint32 recordCount = records.getCount();
le_uint8 bit = highBit(recordCount);
diff --git a/jdk/src/share/native/sun/font/layout/SegmentArrayProcessor.cpp b/jdk/src/share/native/sun/font/layout/SegmentArrayProcessor.cpp
index ecc63cb67be..f0cb95d80c5 100644
--- a/jdk/src/share/native/sun/font/layout/SegmentArrayProcessor.cpp
+++ b/jdk/src/share/native/sun/font/layout/SegmentArrayProcessor.cpp
@@ -73,6 +73,7 @@ void SegmentArrayProcessor::process(LEGlyphStorage &glyphStorage, LEErrorCode &s
if (offset != 0) {
LEReferenceToArrayOf glyphArray(subtableHeader, success, offset, LE_UNBOUNDED_ARRAY);
+ if (LE_FAILURE(success)) { continue; }
TTGlyphID newGlyph = SWAPW(glyphArray(LE_GET_GLYPH(thisGlyph) - firstGlyph, success));
glyphStorage[glyph] = LE_SET_GLYPH(thisGlyph, newGlyph);
}
diff --git a/jdk/src/share/native/sun/font/layout/StateTableProcessor.cpp b/jdk/src/share/native/sun/font/layout/StateTableProcessor.cpp
index 0f135c70b2b..9924a903708 100644
--- a/jdk/src/share/native/sun/font/layout/StateTableProcessor.cpp
+++ b/jdk/src/share/native/sun/font/layout/StateTableProcessor.cpp
@@ -97,6 +97,7 @@ void StateTableProcessor::process(LEGlyphStorage &glyphStorage, LEErrorCode &suc
LEReferenceToArrayOf stateArray(stHeader, success, currentState, LE_UNBOUNDED_ARRAY);
EntryTableIndex entryTableIndex = stateArray.getObject((le_uint8)classCode, success);
+ if (LE_FAILURE(success)) { break; }
LE_STATE_PATIENCE_CURR(le_int32, currGlyph);
currentState = processStateEntry(glyphStorage, currGlyph, entryTableIndex);
LE_STATE_PATIENCE_INCR(currGlyph);
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
index a408497e250..38d164ad3cf 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
@@ -81,7 +81,7 @@ typedef struct {
cmsUInt32Number surround;
cmsFloat64Number n, Nbb, Ncb, z, FL, D;
- cmsContext ContextID;
+ cmsContext ContextID;
} cmsCIECAM02;
@@ -467,6 +467,7 @@ void CMSEXPORT cmsCIECAM02Forward(cmsHANDLE hModel, const cmsCIEXYZ* pIn, cmsJCh
CAM02COLOR clr;
cmsCIECAM02* lpMod = (cmsCIECAM02*) hModel;
+ memset(&clr, 0, sizeof(clr));
_cmsAssert(lpMod != NULL);
_cmsAssert(pIn != NULL);
_cmsAssert(pOut != NULL);
@@ -491,6 +492,7 @@ void CMSEXPORT cmsCIECAM02Reverse(cmsHANDLE hModel, const cmsJCh* pIn, cmsCIEXYZ
CAM02COLOR clr;
cmsCIECAM02* lpMod = (cmsCIECAM02*) hModel;
+ memset(&clr, 0, sizeof(clr));
_cmsAssert(lpMod != NULL);
_cmsAssert(pIn != NULL);
_cmsAssert(pOut != NULL);
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
index bf5015604a7..11fe36e6c2c 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
@@ -59,8 +59,8 @@
// IT8.7 / CGATS.17-200x handling -----------------------------------------------------------------------------
-#define MAXID 128 // Max lenght of identifier
-#define MAXSTR 1024 // Max lenght of string
+#define MAXID 128 // Max length of identifier
+#define MAXSTR 1024 // Max length of string
#define MAXTABLES 255 // Max Number of tables in a single stream
#define MAXINCLUDE 20 // Max number of nested includes
@@ -383,28 +383,28 @@ static const char* PredefinedSampleID[] = {
//Forward declaration of some internal functions
static void* AllocChunk(cmsIT8* it8, cmsUInt32Number size);
-// Checks if c is a separator
+// Checks whatever c is a separator
static
cmsBool isseparator(int c)
{
- return (c == ' ') || (c == '\t') || (c == '\r');
+ return (c == ' ') || (c == '\t') ;
}
-// Checks whatever if c is a valid identifier char
+// Checks whatever c is a valid identifier char
static
cmsBool ismiddle(int c)
{
return (!isseparator(c) && (c != '#') && (c !='\"') && (c != '\'') && (c > 32) && (c < 127));
}
-// Checks whatsever if c is a valid identifier middle char.
+// Checks whatsever c is a valid identifier middle char.
static
cmsBool isidchar(int c)
{
return isalnum(c) || ismiddle(c);
}
-// Checks whatsever if c is a valid identifier first char.
+// Checks whatsever c is a valid identifier first char.
static
cmsBool isfirstidchar(int c)
{
@@ -436,7 +436,6 @@ cmsBool isabsolutepath(const char *path)
}
-
// Makes a file path based on a given reference path
// NOTE: this function doesn't check if the path exists or even if it's legal
static
@@ -634,6 +633,7 @@ cmsFloat64Number ParseFloatNumber(const char *Buffer)
cmsFloat64Number dnum = 0.0;
int sign = 1;
+ // keep safe
if (Buffer == NULL) return 0.0;
if (*Buffer == '-' || *Buffer == '+') {
@@ -869,6 +869,14 @@ void InSymbol(cmsIT8* it8)
// Next line
+ case '\r':
+ NextCh(it8);
+ if (it8 ->ch == '\n')
+ NextCh(it8);
+ it8->sy = SEOLN;
+ it8->lineno++;
+ break;
+
case '\n':
NextCh(it8);
it8->sy = SEOLN;
@@ -878,7 +886,7 @@ void InSymbol(cmsIT8* it8)
// Comment
case '#':
NextCh(it8);
- while (it8->ch && it8->ch != '\n')
+ while (it8->ch && it8->ch != '\n' && it8->ch != '\r')
NextCh(it8);
it8->sy = SCOMMENT;
@@ -996,6 +1004,9 @@ cmsBool GetVal(cmsIT8* it8, char* Buffer, cmsUInt32Number max, const char* Error
{
switch (it8->sy) {
+ case SEOLN: // Empty value
+ Buffer[0]=0;
+ break;
case SIDENT: strncpy(Buffer, it8->id, max);
Buffer[max-1]=0;
break;
@@ -1145,9 +1156,9 @@ cmsBool IsAvailableOnList(KEYVALUE* p, const char* Key, const char* Subkey, KEYV
if (*Key != '#') { // Comments are ignored
if (cmsstrcasecmp(Key, p->Keyword) == 0)
- break;
- }
+ break;
}
+ }
if (p == NULL)
return FALSE;
@@ -1157,11 +1168,13 @@ cmsBool IsAvailableOnList(KEYVALUE* p, const char* Key, const char* Subkey, KEYV
for (; p != NULL; p = p->NextSubkey) {
+ if (p ->Subkey == NULL) continue;
+
if (LastPtr) *LastPtr = p;
if (cmsstrcasecmp(Subkey, p->Subkey) == 0)
- return TRUE;
- }
+ return TRUE;
+ }
return FALSE;
}
@@ -1284,7 +1297,7 @@ cmsInt32Number CMSEXPORT cmsIT8SetTable(cmsHANDLE IT8, cmsUInt32Number nTable)
it8 ->nTable = nTable;
- return nTable;
+ return (cmsInt32Number) nTable;
}
@@ -1389,7 +1402,7 @@ cmsBool CMSEXPORT cmsIT8SetPropertyHex(cmsHANDLE hIT8, const char* cProp, cmsUIn
cmsIT8* it8 = (cmsIT8*) hIT8;
char Buffer[1024];
- sprintf(Buffer, "%d", Val);
+ sprintf(Buffer, "%u", Val);
return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_HEXADECIMAL) != NULL;
}
@@ -1426,6 +1439,8 @@ cmsFloat64Number CMSEXPORT cmsIT8GetPropertyDbl(cmsHANDLE hIT8, const char* cPro
{
const char *v = cmsIT8GetProperty(hIT8, cProp);
+ if (v == NULL) return 0.0;
+
return ParseFloatNumber(v);
}
@@ -1458,7 +1473,7 @@ void AllocateDataFormat(cmsIT8* it8)
t -> nSamples = 10;
}
- t -> DataFormat = (char**) AllocChunk (it8, (t->nSamples + 1) * sizeof(char *));
+ t -> DataFormat = (char**) AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * sizeof(char *));
if (t->DataFormat == NULL) {
SynError(it8, "AllocateDataFormat: Unable to allocate dataFormat array");
@@ -1514,7 +1529,7 @@ void AllocateDataSet(cmsIT8* it8)
t-> nSamples = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_FIELDS"));
t-> nPatches = atoi(cmsIT8GetProperty(it8, "NUMBER_OF_SETS"));
- t-> Data = (char**)AllocChunk (it8, (t->nSamples + 1) * (t->nPatches + 1) *sizeof (char*));
+ t-> Data = (char**)AllocChunk (it8, ((cmsUInt32Number) t->nSamples + 1) * ((cmsUInt32Number) t->nPatches + 1) *sizeof (char*));
if (t->Data == NULL) {
SynError(it8, "AllocateDataSet: Unable to allocate data array");
@@ -1573,7 +1588,7 @@ void WriteStr(SAVESTREAM* f, const char *str)
if (str == NULL)
str = " ";
- // Lenghth to write
+ // Length to write
len = (cmsUInt32Number) strlen(str);
f ->Used += len;
@@ -2097,7 +2112,7 @@ cmsBool ParseIT8(cmsIT8* it8, cmsBool nosheet)
NextCh(it8);
// If a newline is found, then this is a type string
- if (it8 ->ch == '\n') {
+ if (it8 ->ch == '\n' || it8->ch == '\r') {
cmsIT8SetSheetType(it8, it8 ->id);
InSymbol(it8);
@@ -2212,7 +2227,7 @@ void CookPointers(cmsIT8* it8)
char Buffer[256];
char *Type = p ->Value;
- int nTable = k;
+ int nTable = (int) k;
snprintf(Buffer, 255, "%s %d %s", Label, nTable, Type );
@@ -2566,6 +2581,8 @@ cmsFloat64Number CMSEXPORT cmsIT8GetDataRowColDbl(cmsHANDLE hIT8, int row, int c
Buffer = cmsIT8GetDataRowCol(hIT8, row, col);
+ if (Buffer == NULL) return 0.0;
+
return ParseFloatNumber(Buffer);
}
@@ -2778,7 +2795,7 @@ void CMSEXPORT cmsIT8DefineDblFormat(cmsHANDLE hIT8, const char* Formatter)
if (Formatter == NULL)
strcpy(it8->DoubleFormatter, DEFAULT_DBL_FORMAT);
else
- strcpy(it8->DoubleFormatter, Formatter);
+ strncpy(it8->DoubleFormatter, Formatter, sizeof(it8->DoubleFormatter));
it8 ->DoubleFormatter[sizeof(it8 ->DoubleFormatter)-1] = 0;
}
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
index d1a1cc99804..cea3b8bb424 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
@@ -270,7 +270,7 @@ cmsBool ComputeAbsoluteIntent(cmsFloat64Number AdaptationState,
// m2 holds CHAD from output white to D50 times abs. col. scaling
// Observer is not adapted, undo the chromatic adaptation
- _cmsMAT3per(m, &m3, ChromaticAdaptationMatrixOut);
+ _cmsMAT3per(m, &m2, ChromaticAdaptationMatrixOut);
m3 = *ChromaticAdaptationMatrixIn;
if (!_cmsMAT3inverse(&m3, &m4)) return FALSE;
@@ -411,57 +411,61 @@ cmsBool AddConversion(cmsPipeline* Result, cmsColorSpaceSignature InPCS, cmsColo
// Handle PCS mismatches. A specialized stage is added to the LUT in such case
switch (InPCS) {
- case cmsSigXYZData: // Input profile operates in XYZ
+ case cmsSigXYZData: // Input profile operates in XYZ
- switch (OutPCS) {
+ switch (OutPCS) {
- case cmsSigXYZData: // XYZ -> XYZ
- if (!IsEmptyLayer(m, off))
- cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
- break;
+ case cmsSigXYZData: // XYZ -> XYZ
+ if (!IsEmptyLayer(m, off) &&
+ !cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl)))
+ return FALSE;
+ break;
- case cmsSigLabData: // XYZ -> Lab
- if (!IsEmptyLayer(m, off))
- cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
- cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID));
- break;
+ case cmsSigLabData: // XYZ -> Lab
+ if (!IsEmptyLayer(m, off) &&
+ !cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl)))
+ return FALSE;
+ if (!cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID)))
+ return FALSE;
+ break;
- default:
- return FALSE; // Colorspace mismatch
- }
- break;
+ default:
+ return FALSE; // Colorspace mismatch
+ }
+ break;
+ case cmsSigLabData: // Input profile operates in Lab
- case cmsSigLabData: // Input profile operates in Lab
+ switch (OutPCS) {
- switch (OutPCS) {
+ case cmsSigXYZData: // Lab -> XYZ
- case cmsSigXYZData: // Lab -> XYZ
+ if (!cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID)))
+ return FALSE;
+ if (!IsEmptyLayer(m, off) &&
+ !cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl)))
+ return FALSE;
+ break;
- cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID));
- if (!IsEmptyLayer(m, off))
- cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
- break;
+ case cmsSigLabData: // Lab -> Lab
- case cmsSigLabData: // Lab -> Lab
-
- if (!IsEmptyLayer(m, off)) {
- cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID));
- cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl));
- cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID));
- }
- break;
-
- default:
- return FALSE; // Mismatch
+ if (!IsEmptyLayer(m, off)) {
+ if (!cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocLab2XYZ(Result ->ContextID)) ||
+ !cmsPipelineInsertStage(Result, cmsAT_END, cmsStageAllocMatrix(Result ->ContextID, 3, 3, m_as_dbl, off_as_dbl)) ||
+ !cmsPipelineInsertStage(Result, cmsAT_END, _cmsStageAllocXYZ2Lab(Result ->ContextID)))
+ return FALSE;
}
break;
-
- // On colorspaces other than PCS, check for same space
default:
- if (InPCS != OutPCS) return FALSE;
- break;
+ return FALSE; // Mismatch
+ }
+ break;
+
+ // On colorspaces other than PCS, check for same space
+ default:
+ if (InPCS != OutPCS) return FALSE;
+ break;
}
return TRUE;
@@ -497,7 +501,8 @@ cmsPipeline* DefaultICCintents(cmsContext ContextID,
cmsFloat64Number AdaptationStates[],
cmsUInt32Number dwFlags)
{
- cmsPipeline* Lut, *Result;
+ cmsPipeline* Lut = NULL;
+ cmsPipeline* Result;
cmsHPROFILE hProfile;
cmsMAT3 m;
cmsVEC3 off;
@@ -593,8 +598,11 @@ cmsPipeline* DefaultICCintents(cmsContext ContextID,
}
// Concatenate to the output LUT
- cmsPipelineCat(Result, Lut);
+ if (!cmsPipelineCat(Result, Lut))
+ goto Error;
+
cmsPipelineFree(Lut);
+ Lut = NULL;
// Update current space
CurrentColorSpace = ColorSpaceOut;
@@ -604,6 +612,7 @@ cmsPipeline* DefaultICCintents(cmsContext ContextID,
Error:
+ if (Lut != NULL) cmsPipelineFree(Lut);
if (Result != NULL) cmsPipelineFree(Result);
return NULL;
@@ -742,7 +751,8 @@ cmsPipeline* BlackPreservingKOnlyIntents(cmsContext ContextID,
if (CLUT == NULL) goto Error;
// This is the one and only MPE in this LUT
- cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT);
+ if (!cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT))
+ goto Error;
// Sample it. We cannot afford pre/post linearization this time.
if (!cmsStageSampleCLut16bit(CLUT, BlackPreservingGrayOnlySampler, (void*) &bp, 0))
@@ -959,7 +969,8 @@ cmsPipeline* BlackPreservingKPlaneIntents(cmsContext ContextID,
CLUT = cmsStageAllocCLut16bit(ContextID, nGridPoints, 4, 4, NULL);
if (CLUT == NULL) goto Cleanup;
- cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT);
+ if (!cmsPipelineInsertStage(Result, cmsAT_BEGIN, CLUT))
+ goto Cleanup;
cmsStageSampleCLut16bit(CLUT, BlackPreservingSampler, (void*) &bp, 0);
@@ -1057,7 +1068,7 @@ cmsUInt32Number CMSEXPORT cmsGetSupportedIntents(cmsUInt32Number nMax, cmsUInt32
}
// The plug-in registration. User can add new intents or override default routines
-cmsBool _cmsRegisterRenderingIntentPlugin(cmsPluginBase* Data)
+cmsBool _cmsRegisterRenderingIntentPlugin(cmsContext id, cmsPluginBase* Data)
{
cmsPluginRenderingIntent* Plugin = (cmsPluginRenderingIntent*) Data;
cmsIntentsList* fl;
@@ -1072,7 +1083,7 @@ cmsBool _cmsRegisterRenderingIntentPlugin(cmsPluginBase* Data)
fl = SearchIntent(Plugin ->Intent);
if (fl == NULL) {
- fl = (cmsIntentsList*) _cmsPluginMalloc(sizeof(cmsIntentsList));
+ fl = (cmsIntentsList*) _cmsPluginMalloc(id, sizeof(cmsIntentsList));
if (fl == NULL) return FALSE;
}
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
index a18a59a1ffa..bf1e2606324 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
@@ -302,8 +302,6 @@ _cmsSubAllocator_chunk* _cmsCreateSubAllocChunk(cmsContext ContextID, cmsUInt32N
return NULL;
}
-
-
chunk ->BlockSize = Initial;
chunk ->Used = 0;
chunk ->next = NULL;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
index 9ee36e2d538..79affb09fb4 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
@@ -30,7 +30,7 @@
//---------------------------------------------------------------------------------
//
// Little Color Management System
-// Copyright (c) 1998-2012 Marti Maria Saguer
+// Copyright (c) 1998-2013 Marti Maria Saguer
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -99,7 +99,7 @@ static _cmsParametricCurvesCollection DefaultCurves = {
static _cmsParametricCurvesCollection* ParametricCurves = &DefaultCurves;
// As a way to install new parametric curves
-cmsBool _cmsRegisterParametricCurvesPlugin(cmsPluginBase* Data)
+cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext id, cmsPluginBase* Data)
{
cmsPluginParametricCurves* Plugin = (cmsPluginParametricCurves*) Data;
_cmsParametricCurvesCollection* fl;
@@ -110,7 +110,7 @@ cmsBool _cmsRegisterParametricCurvesPlugin(cmsPluginBase* Data)
return TRUE;
}
- fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(sizeof(_cmsParametricCurvesCollection));
+ fl = (_cmsParametricCurvesCollection*) _cmsPluginMalloc(id, sizeof(_cmsParametricCurvesCollection));
if (fl == NULL) return FALSE;
// Copy the parameters
@@ -258,7 +258,8 @@ cmsToneCurve* AllocateToneCurveStruct(cmsContext ContextID, cmsInt32Number nEntr
}
p ->InterpParams = _cmsComputeInterpParams(ContextID, p ->nEntries, 1, 1, p->Table16, CMS_LERP_FLAGS_16BITS);
- return p;
+ if (p->InterpParams != NULL)
+ return p;
Error:
if (p -> Segments) _cmsFree(ContextID, p ->Segments);
@@ -423,7 +424,7 @@ cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Nu
if (e > 0)
Val = pow(e, Params[0]) + Params[5];
else
- Val = 0;
+ Val = Params[5];
}
else
Val = R*Params[3] + Params[6];
@@ -458,7 +459,7 @@ cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Nu
e = Params[1]*R + Params[2];
if (e < 0)
- Val = 0;
+ Val = Params[3];
else
Val = pow(e, Params[0]) + Params[3];
break;
@@ -478,7 +479,7 @@ cmsFloat64Number DefaultEvalParametricFn(cmsInt32Number Type, const cmsFloat64Nu
e = Params[2] * pow(R, Params[0]) + Params[3];
if (e <= 0)
- Val = 0;
+ Val = Params[4];
else
Val = Params[1]*log10(e) + Params[4];
break;
@@ -544,7 +545,7 @@ cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R)
// Type == 0 means segment is sampled
if (g ->Segments[i].Type == 0) {
- cmsFloat32Number R1 = (cmsFloat32Number) (R - g ->Segments[i].x0);
+ cmsFloat32Number R1 = (cmsFloat32Number) (R - g ->Segments[i].x0) / (g ->Segments[i].x1 - g ->Segments[i].x0);
cmsFloat32Number Out;
// Setup the table (TODO: clean that)
@@ -629,20 +630,21 @@ cmsToneCurve* CMSEXPORT cmsBuildSegmentedToneCurve(cmsContext ContextID,
// Use a segmented curve to store the floating point table
cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cmsUInt32Number nEntries, const cmsFloat32Number values[])
{
- cmsCurveSegment Seg[2];
+ cmsCurveSegment Seg[3];
- // Initialize segmented curve part up to 0
- Seg[0].x0 = -1;
+ // A segmented tone curve should have function segments in the first and last positions
+ // Initialize segmented curve part up to 0 to constant value = samples[0]
+ Seg[0].x0 = MINUS_INF;
Seg[0].x1 = 0;
Seg[0].Type = 6;
Seg[0].Params[0] = 1;
Seg[0].Params[1] = 0;
Seg[0].Params[2] = 0;
- Seg[0].Params[3] = 0;
+ Seg[0].Params[3] = values[0];
Seg[0].Params[4] = 0;
- // From zero to any
+ // From zero to 1
Seg[1].x0 = 0;
Seg[1].x1 = 1.0;
Seg[1].Type = 0;
@@ -650,7 +652,19 @@ cmsToneCurve* CMSEXPORT cmsBuildTabulatedToneCurveFloat(cmsContext ContextID, cm
Seg[1].nGridPoints = nEntries;
Seg[1].SampledPoints = (cmsFloat32Number*) values;
- return cmsBuildSegmentedToneCurve(ContextID, 2, Seg);
+ // Final segment is constant = lastsample
+ Seg[2].x0 = 1.0;
+ Seg[2].x1 = PLUS_INF;
+ Seg[2].Type = 6;
+
+ Seg[2].Params[0] = 1;
+ Seg[2].Params[1] = 0;
+ Seg[2].Params[2] = 0;
+ Seg[2].Params[3] = values[nEntries-1];
+ Seg[2].Params[4] = 0;
+
+
+ return cmsBuildSegmentedToneCurve(ContextID, 3, Seg);
}
// Parametric curves
@@ -993,7 +1007,7 @@ cmsBool CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda
if (Tab == NULL) return FALSE;
- if (cmsIsToneCurveLinear(Tab)) return FALSE; // Nothing to do
+ if (cmsIsToneCurveLinear(Tab)) return TRUE; // Nothing to do
nItems = Tab -> nEntries;
@@ -1020,11 +1034,20 @@ cmsBool CMSEXPORT cmsSmoothToneCurve(cmsToneCurve* Tab, cmsFloat64Number lambda
if (z[i] == 0.) Zeros++;
if (z[i] >= 65535.) Poles++;
- if (z[i] < z[i-1]) return FALSE; // Non-Monotonic
+ if (z[i] < z[i-1]) {
+ cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Non-Monotonic.");
+ return FALSE;
+ }
}
- if (Zeros > (nItems / 3)) return FALSE; // Degenerated, mostly zeros
- if (Poles > (nItems / 3)) return FALSE; // Degenerated, mostly poles
+ if (Zeros > (nItems / 3)) {
+ cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly zeros.");
+ return FALSE;
+ }
+ if (Poles > (nItems / 3)) {
+ cmsSignalError(Tab ->InterpParams->ContextID, cmsERROR_RANGE, "cmsSmoothToneCurve: Degenerated, mostly poles.");
+ return FALSE;
+ }
// Seems ok
for (i=0; i < nItems; i++) {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
index d7fb6dd274e..8ace203e86d 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
@@ -249,13 +249,10 @@ int GamutSampler(register const cmsUInt16Number In[], register cmsUInt16Number O
cmsFloat64Number dE1, dE2, ErrorRatio;
// Assume in-gamut by default.
- dE1 = 0.;
- dE2 = 0;
ErrorRatio = 1.0;
// Convert input to Lab
- if (t -> hInput != NULL)
- cmsDoTransform(t -> hInput, In, &LabIn1, 1);
+ cmsDoTransform(t -> hInput, In, &LabIn1, 1);
// converts from PCS to colorant. This always
// does return in-gamut values,
@@ -267,7 +264,7 @@ int GamutSampler(register const cmsUInt16Number In[], register cmsUInt16Number O
memmove(&LabIn2, &LabOut1, sizeof(cmsCIELab));
// Try again, but this time taking Check as input
- cmsDoTransform(t -> hForward, &LabOut1, Proof2, 1);
+ cmsDoTransform(t -> hForward, &LabOut1, Proof2, 1);
cmsDoTransform(t -> hReverse, Proof2, &LabOut2, 1);
// Take difference of direct value
@@ -374,7 +371,7 @@ cmsPipeline* _cmsCreateGamutCheckPipeline(cmsContext ContextID,
ProfileList[nGamutPCSposition] = hLab;
BPCList[nGamutPCSposition] = 0;
AdaptationList[nGamutPCSposition] = 1.0;
- Intents[nGamutPCSposition] = INTENT_RELATIVE_COLORIMETRIC;
+ IntentList[nGamutPCSposition] = INTENT_RELATIVE_COLORIMETRIC;
ColorSpace = cmsGetColorSpace(hGamut);
@@ -385,45 +382,48 @@ cmsPipeline* _cmsCreateGamutCheckPipeline(cmsContext ContextID,
// 16 bits to Lab double
Chain.hInput = cmsCreateExtendedTransform(ContextID,
- nGamutPCSposition + 1,
- ProfileList,
- BPCList,
- Intents,
- AdaptationList,
- NULL, 0,
- dwFormat, TYPE_Lab_DBL,
- cmsFLAGS_NOCACHE);
+ nGamutPCSposition + 1,
+ ProfileList,
+ BPCList,
+ IntentList,
+ AdaptationList,
+ NULL, 0,
+ dwFormat, TYPE_Lab_DBL,
+ cmsFLAGS_NOCACHE);
// Does create the forward step. Lab double to device
dwFormat = (CHANNELS_SH(nChannels)|BYTES_SH(2));
Chain.hForward = cmsCreateTransformTHR(ContextID,
- hLab, TYPE_Lab_DBL,
- hGamut, dwFormat,
- INTENT_RELATIVE_COLORIMETRIC,
- cmsFLAGS_NOCACHE);
+ hLab, TYPE_Lab_DBL,
+ hGamut, dwFormat,
+ INTENT_RELATIVE_COLORIMETRIC,
+ cmsFLAGS_NOCACHE);
// Does create the backwards step
Chain.hReverse = cmsCreateTransformTHR(ContextID, hGamut, dwFormat,
- hLab, TYPE_Lab_DBL,
- INTENT_RELATIVE_COLORIMETRIC,
- cmsFLAGS_NOCACHE);
+ hLab, TYPE_Lab_DBL,
+ INTENT_RELATIVE_COLORIMETRIC,
+ cmsFLAGS_NOCACHE);
// All ok?
- if (Chain.hForward && Chain.hReverse) {
+ if (Chain.hInput && Chain.hForward && Chain.hReverse) {
// Go on, try to compute gamut LUT from PCS. This consist on a single channel containing
// dE when doing a transform back and forth on the colorimetric intent.
Gamut = cmsPipelineAlloc(ContextID, 3, 1);
-
if (Gamut != NULL) {
- CLUT = cmsStageAllocCLut16bit(ContextID, nGridpoints, nChannels, 1, NULL);
- cmsPipelineInsertStage(Gamut, cmsAT_BEGIN, CLUT);
-
- cmsStageSampleCLut16bit(CLUT, GamutSampler, (void*) &Chain, 0);
+ CLUT = cmsStageAllocCLut16bit(ContextID, nGridpoints, nChannels, 1, NULL);
+ if (!cmsPipelineInsertStage(Gamut, cmsAT_BEGIN, CLUT)) {
+ cmsPipelineFree(Gamut);
+ Gamut = NULL;
+ }
+ else {
+ cmsStageSampleCLut16bit(CLUT, GamutSampler, (void*) &Chain, 0);
+ }
}
}
else
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
index 51ec140cfbe..ad971b5bc60 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
@@ -83,7 +83,6 @@ cmsBool _cmsRegisterInterpPlugin(cmsPluginBase* Data)
// Set the interpolation method
-
cmsBool _cmsSetInterpolationRoutine(cmsInterpParams* p)
{
// Invoke factory, possibly in the Plug-in
@@ -831,7 +830,7 @@ void Eval4Inputs(register const cmsUInt16Number Input[],
register cmsUInt16Number Output[],
register const cmsInterpParams* p16)
{
- const cmsUInt16Number* LutTable = (cmsUInt16Number*) p16 -> Table;
+ const cmsUInt16Number* LutTable;
cmsS15Fixed16Number fk;
cmsS15Fixed16Number k0, rk;
int K0, K1;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
index 80104145454..8f421c2f4ec 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
@@ -154,7 +154,6 @@ cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromNULL(cmsContext ContextID)
return iohandler;
Error:
- if (fm) _cmsFree(ContextID, fm);
if (iohandler) _cmsFree(ContextID, iohandler);
return NULL;
@@ -223,12 +222,17 @@ cmsUInt32Number MemoryTell(struct _cms_io_handler* iohandler)
// Writes data to memory, also keeps used space for further reference.
static
-cmsBool MemoryWrite(struct _cms_io_handler* iohandler, cmsUInt32Number size, const void *Ptr)
+cmsBool MemoryWrite(struct _cms_io_handler* iohandler, cmsUInt32Number size, const void *Ptr)
{
FILEMEM* ResData = (FILEMEM*) iohandler ->stream;
if (ResData == NULL) return FALSE; // Housekeeping
+ // Check for available space. Clip.
+ if (iohandler ->UsedSpace + size > ResData->Size) {
+ size = ResData ->Size - iohandler ->UsedSpace;
+ }
+
if (size == 0) return TRUE; // Write zero bytes is ok, but does nothing
memmove(ResData ->Block + ResData ->Pointer, Ptr, size);
@@ -350,7 +354,7 @@ cmsUInt32Number FileRead(cmsIOHANDLER* iohandler, void *Buffer, cmsUInt32Number
return nReaded;
}
-// Position file pointer in the file
+// Postion file pointer in the file
static
cmsBool FileSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
{
@@ -389,13 +393,15 @@ cmsBool FileClose(cmsIOHANDLER* iohandler)
return TRUE;
}
-// Create a iohandler for disk based files. if FileName is NULL, then 'stream' member is also set
-// to NULL and no real writting is performed. This only happens in writting access mode
+// Create a iohandler for disk based files.
cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromFile(cmsContext ContextID, const char* FileName, const char* AccessMode)
{
cmsIOHANDLER* iohandler = NULL;
FILE* fm = NULL;
+ _cmsAssert(FileName != NULL);
+ _cmsAssert(AccessMode != NULL);
+
iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
if (iohandler == NULL) return NULL;
@@ -432,11 +438,8 @@ cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromFile(cmsContext ContextID, const cha
iohandler ->UsedSpace = 0;
// Keep track of the original file
- if (FileName != NULL) {
-
- strncpy(iohandler -> PhysicalFile, FileName, sizeof(iohandler -> PhysicalFile)-1);
- iohandler -> PhysicalFile[sizeof(iohandler -> PhysicalFile)-1] = 0;
- }
+ strncpy(iohandler -> PhysicalFile, FileName, sizeof(iohandler -> PhysicalFile)-1);
+ iohandler -> PhysicalFile[sizeof(iohandler -> PhysicalFile)-1] = 0;
iohandler ->Read = FileRead;
iohandler ->Seek = FileSeek;
@@ -616,6 +619,31 @@ cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
return _cmsSearchTag(Icc, sig, FALSE) >= 0;
}
+/*
+ * Enforces that the profile version is per. spec.
+ * Operates on the big endian bytes from the profile.
+ * Called before converting to platform endianness.
+ * Byte 0 is BCD major version, so max 9.
+ * Byte 1 is 2 BCD digits, one per nibble.
+ * Reserved bytes 2 & 3 must be 0.
+ */
+static cmsUInt32Number _validatedVersion(cmsUInt32Number DWord)
+{
+ cmsUInt8Number* pByte = (cmsUInt8Number*)&DWord;
+ cmsUInt8Number temp1;
+ cmsUInt8Number temp2;
+
+ if (*pByte > 0x09) *pByte = (cmsUInt8Number)9;
+ temp1 = *(pByte+1) & 0xf0;
+ temp2 = *(pByte+1) & 0x0f;
+ if (temp1 > 0x90) temp1 = 0x90;
+ if (temp2 > 9) temp2 = 0x09;
+ *(pByte+1) = (cmsUInt8Number)(temp1 | temp2);
+ *(pByte+2) = (cmsUInt8Number)0;
+ *(pByte+3) = (cmsUInt8Number)0;
+
+ return DWord;
+}
// Read profile header and validate it
cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
@@ -643,12 +671,15 @@ cmsBool _cmsReadHeader(_cmsICCPROFILE* Icc)
Icc -> DeviceClass = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
Icc -> ColorSpace = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Header.colorSpace);
Icc -> PCS = (cmsColorSpaceSignature) _cmsAdjustEndianess32(Header.pcs);
+
Icc -> RenderingIntent = _cmsAdjustEndianess32(Header.renderingIntent);
Icc -> flags = _cmsAdjustEndianess32(Header.flags);
Icc -> manufacturer = _cmsAdjustEndianess32(Header.manufacturer);
Icc -> model = _cmsAdjustEndianess32(Header.model);
+ Icc -> creator = _cmsAdjustEndianess32(Header.creator);
+
_cmsAdjustEndianess64(&Icc -> attributes, &Header.attributes);
- Icc -> Version = _cmsAdjustEndianess32(Header.version);
+ Icc -> Version = _cmsAdjustEndianess32(_validatedVersion(Header.version));
// Get size as reported in header
HeaderSize = _cmsAdjustEndianess32(Header.size);
@@ -815,28 +846,33 @@ void CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags)
cmsUInt32Number CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile)
{
_cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
- return (cmsUInt32Number) Icc ->manufacturer;
+ return Icc ->manufacturer;
}
void CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer)
{
_cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
- Icc -> manufacturer = (cmsUInt32Number) manufacturer;
+ Icc -> manufacturer = manufacturer;
+}
+
+cmsUInt32Number CMSEXPORT cmsGetHeaderCreator(cmsHPROFILE hProfile)
+{
+ _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+ return Icc ->creator;
}
cmsUInt32Number CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile)
{
_cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
- return (cmsUInt32Number) Icc ->model;
+ return Icc ->model;
}
void CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model)
{
_cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
- Icc -> model = (cmsUInt32Number) model;
+ Icc -> model = model;
}
-
void CMSEXPORT cmsGetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number* Flags)
{
_cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
@@ -1073,7 +1109,6 @@ cmsHPROFILE CMSEXPORT cmsOpenProfileFromMem(const void* MemPtr, cmsUInt32Number
return cmsOpenProfileFromMemTHR(NULL, MemPtr, dwSize);
}
-
static
cmsBool SanityCheck(_cmsICCPROFILE* profile)
{
@@ -1112,11 +1147,13 @@ cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
cmsIOHANDLER* io = Icc ->IOhandler;
cmsTagDescriptor* TagDescriptor;
cmsTagTypeSignature TypeBase;
+ cmsTagTypeSignature Type;
cmsTagTypeHandler* TypeHandler;
+ cmsFloat64Number Version = cmsGetProfileVersion((cmsHPROFILE) Icc);
+ cmsTagTypeHandler LocalTypeHandler;
for (i=0; i < Icc -> TagCount; i++) {
-
if (Icc ->TagNames[i] == 0) continue;
// Linked tags are not written
@@ -1168,7 +1205,16 @@ cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
TagDescriptor = _cmsGetTagDescriptor(Icc -> TagNames[i]);
if (TagDescriptor == NULL) continue; // Unsupported, ignore it
- TypeHandler = Icc ->TagTypeHandlers[i];
+ if (TagDescriptor ->DecideType != NULL) {
+
+ Type = TagDescriptor ->DecideType(Version, Data);
+ }
+ else {
+
+ Type = TagDescriptor ->SupportedTypes[0];
+ }
+
+ TypeHandler = _cmsGetTagTypeHandler(Type);
if (TypeHandler == NULL) {
cmsSignalError(Icc ->ContextID, cmsERROR_INTERNAL, "(Internal) no handler for tag %x", Icc -> TagNames[i]);
@@ -1179,9 +1225,10 @@ cmsBool SaveTags(_cmsICCPROFILE* Icc, _cmsICCPROFILE* FileOrig)
if (!_cmsWriteTypeBase(io, TypeBase))
return FALSE;
- TypeHandler ->ContextID = Icc ->ContextID;
- TypeHandler ->ICCVersion = Icc ->Version;
- if (!TypeHandler ->WritePtr(TypeHandler, io, Data, TagDescriptor ->ElemCount)) {
+ LocalTypeHandler = *TypeHandler;
+ LocalTypeHandler.ContextID = Icc ->ContextID;
+ LocalTypeHandler.ICCVersion = Icc ->Version;
+ if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, io, Data, TagDescriptor ->ElemCount)) {
char String[5];
@@ -1318,8 +1365,8 @@ cmsBool CMSEXPORT cmsSaveProfileToMem(cmsHPROFILE hProfile, void *MemPtr, cmsUIn
// Should we just calculate the needed space?
if (MemPtr == NULL) {
- *BytesNeeded = cmsSaveProfileToIOhandler(hProfile, NULL);
- return (*BytesNeeded == 0 ? FALSE : TRUE);
+ *BytesNeeded = cmsSaveProfileToIOhandler(hProfile, NULL);
+ return (*BytesNeeded == 0 ? FALSE : TRUE);
}
// That is a real write operation
@@ -1357,10 +1404,11 @@ cmsBool CMSEXPORT cmsCloseProfile(cmsHPROFILE hProfile)
cmsTagTypeHandler* TypeHandler = Icc ->TagTypeHandlers[i];
if (TypeHandler != NULL) {
+ cmsTagTypeHandler LocalTypeHandler = *TypeHandler;
- TypeHandler ->ContextID = Icc ->ContextID; // As an additional parameters
- TypeHandler ->ICCVersion = Icc ->Version;
- TypeHandler ->FreePtr(TypeHandler, Icc -> TagPtrs[i]);
+ LocalTypeHandler.ContextID = Icc ->ContextID; // As an additional parameters
+ LocalTypeHandler.ICCVersion = Icc ->Version;
+ LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
}
else
_cmsFree(Icc ->ContextID, Icc ->TagPtrs[i]);
@@ -1404,6 +1452,7 @@ void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
_cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
cmsIOHANDLER* io = Icc ->IOhandler;
cmsTagTypeHandler* TypeHandler;
+ cmsTagTypeHandler LocalTypeHandler;
cmsTagDescriptor* TagDescriptor;
cmsTagTypeSignature BaseType;
cmsUInt32Number Offset, TagSize;
@@ -1427,7 +1476,7 @@ void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
// Seek to its location
if (!io -> Seek(io, Offset))
- return NULL;
+ return NULL;
// Search for support on this tag
TagDescriptor = _cmsGetTagDescriptor(sig);
@@ -1444,14 +1493,15 @@ void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
// Get type handler
TypeHandler = _cmsGetTagTypeHandler(BaseType);
if (TypeHandler == NULL) return NULL;
+ LocalTypeHandler = *TypeHandler;
// Read the tag
Icc -> TagTypeHandlers[n] = TypeHandler;
- TypeHandler ->ContextID = Icc ->ContextID;
- TypeHandler ->ICCVersion = Icc ->Version;
- Icc -> TagPtrs[n] = TypeHandler ->ReadPtr(TypeHandler, io, &ElemCount, TagSize);
+ LocalTypeHandler.ContextID = Icc ->ContextID;
+ LocalTypeHandler.ICCVersion = Icc ->Version;
+ Icc -> TagPtrs[n] = LocalTypeHandler.ReadPtr(&LocalTypeHandler, io, &ElemCount, TagSize);
// The tag type is supported, but something wrong happend and we cannot read the tag.
// let know the user about this (although it is just a warning)
@@ -1472,7 +1522,7 @@ void* CMSEXPORT cmsReadTag(cmsHPROFILE hProfile, cmsTagSignature sig)
_cmsTagSignature2String(String, sig);
cmsSignalError(Icc ->ContextID, cmsERROR_CORRUPTION_DETECTED, "'%s' Inconsistent number of items: expected %d, got %d",
- String, TagDescriptor ->ElemCount, ElemCount);
+ String, TagDescriptor ->ElemCount, ElemCount);
}
@@ -1504,6 +1554,7 @@ cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const v
{
_cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
cmsTagTypeHandler* TypeHandler = NULL;
+ cmsTagTypeHandler LocalTypeHandler;
cmsTagDescriptor* TagDescriptor = NULL;
cmsTagTypeSignature Type;
int i;
@@ -1534,9 +1585,10 @@ cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const v
if (TypeHandler != NULL) {
- TypeHandler ->ContextID = Icc ->ContextID; // As an additional parameter
- TypeHandler ->ICCVersion = Icc ->Version;
- TypeHandler->FreePtr(TypeHandler, Icc -> TagPtrs[i]);
+ LocalTypeHandler = *TypeHandler;
+ LocalTypeHandler.ContextID = Icc ->ContextID; // As an additional parameter
+ LocalTypeHandler.ICCVersion = Icc ->Version;
+ LocalTypeHandler.FreePtr(&LocalTypeHandler, Icc -> TagPtrs[i]);
}
}
}
@@ -1575,7 +1627,7 @@ cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const v
// Let the tag descriptor to decide the type base on depending on
// the data. This is useful for example on parametric curves, where
// curves specified by a table cannot be saved as parametric and needs
- // to be revented to single v2-curves, even on v4 profiles.
+ // to be casted to single v2-curves, even on v4 profiles.
Type = TagDescriptor ->DecideType(Version, data);
}
@@ -1613,9 +1665,10 @@ cmsBool CMSEXPORT cmsWriteTag(cmsHPROFILE hProfile, cmsTagSignature sig, const v
Icc ->TagSizes[i] = 0;
Icc ->TagOffsets[i] = 0;
- TypeHandler ->ContextID = Icc ->ContextID;
- TypeHandler ->ICCVersion = Icc ->Version;
- Icc ->TagPtrs[i] = TypeHandler ->DupPtr(TypeHandler, data, TagDescriptor ->ElemCount);
+ LocalTypeHandler = *TypeHandler;
+ LocalTypeHandler.ContextID = Icc ->ContextID;
+ LocalTypeHandler.ICCVersion = Icc ->Version;
+ Icc ->TagPtrs[i] = LocalTypeHandler.DupPtr(&LocalTypeHandler, data, TagDescriptor ->ElemCount);
if (Icc ->TagPtrs[i] == NULL) {
@@ -1642,6 +1695,7 @@ cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig
int i;
cmsIOHANDLER* MemIO;
cmsTagTypeHandler* TypeHandler = NULL;
+ cmsTagTypeHandler LocalTypeHandler;
cmsTagDescriptor* TagDescriptor = NULL;
cmsUInt32Number rc;
cmsUInt32Number Offset, TagSize;
@@ -1657,15 +1711,16 @@ cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig
Offset = Icc ->TagOffsets[i];
TagSize = Icc ->TagSizes[i];
-
// read the data directly, don't keep copy
if (data != NULL) {
if (BufferSize < TagSize)
- TagSize = BufferSize;
+ TagSize = BufferSize;
if (!Icc ->IOhandler ->Seek(Icc ->IOhandler, Offset)) return 0;
if (!Icc ->IOhandler ->Read(Icc ->IOhandler, data, 1, TagSize)) return 0;
+
+ return TagSize;
}
return Icc ->TagSizes[i];
@@ -1679,9 +1734,11 @@ cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig
TagSize = Icc ->TagSizes[i];
if (BufferSize < TagSize)
- TagSize = BufferSize;
+ TagSize = BufferSize;
memmove(data, Icc ->TagPtrs[i], TagSize);
+
+ return TagSize;
}
return Icc ->TagSizes[i];
@@ -1697,7 +1754,7 @@ cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig
if (data == NULL) {
MemIO = cmsOpenIOhandlerFromNULL(cmsGetProfileContextID(hProfile));
} else{
- MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
+ MemIO = cmsOpenIOhandlerFromMem(cmsGetProfileContextID(hProfile), data, BufferSize, "w");
}
if (MemIO == NULL) return 0;
@@ -1705,20 +1762,22 @@ cmsInt32Number CMSEXPORT cmsReadRawTag(cmsHPROFILE hProfile, cmsTagSignature sig
TypeHandler = Icc ->TagTypeHandlers[i];
TagDescriptor = _cmsGetTagDescriptor(sig);
if (TagDescriptor == NULL) {
- cmsCloseIOhandler(MemIO);
- return 0;
+ cmsCloseIOhandler(MemIO);
+ return 0;
}
+ // FIXME: No handling for TypeHandler == NULL here?
// Serialize
- TypeHandler ->ContextID = Icc ->ContextID;
- TypeHandler ->ICCVersion = Icc ->Version;
+ LocalTypeHandler = *TypeHandler;
+ LocalTypeHandler.ContextID = Icc ->ContextID;
+ LocalTypeHandler.ICCVersion = Icc ->Version;
if (!_cmsWriteTypeBase(MemIO, TypeHandler ->Signature)) {
cmsCloseIOhandler(MemIO);
return 0;
}
- if (!TypeHandler ->WritePtr(TypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) {
+ if (!LocalTypeHandler.WritePtr(&LocalTypeHandler, MemIO, Object, TagDescriptor ->ElemCount)) {
cmsCloseIOhandler(MemIO);
return 0;
}
@@ -1756,7 +1815,7 @@ cmsBool CMSEXPORT cmsWriteRawTag(cmsHPROFILE hProfile, cmsTagSignature sig, cons
// Using this function you can collapse several tag entries to the same block in the profile
cmsBool CMSEXPORT cmsLinkTag(cmsHPROFILE hProfile, cmsTagSignature sig, cmsTagSignature dest)
{
- _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
+ _cmsICCPROFILE* Icc = (_cmsICCPROFILE*) hProfile;
int i;
if (!_cmsNewTag(Icc, sig, &i)) return FALSE;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
index 2dd12f79b4d..efdc6bf9d24 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
@@ -129,7 +129,6 @@ cmsBool _cmsReadCHAD(cmsMAT3* Dest, cmsHPROFILE hProfile)
Tag = (cmsMAT3*) cmsReadTag(hProfile, cmsSigChromaticAdaptationTag);
if (Tag != NULL) {
-
*Dest = *Tag;
return TRUE;
}
@@ -193,7 +192,8 @@ cmsPipeline* BuildGrayInputMatrixPipeline(cmsHPROFILE hProfile)
if (GrayTRC == NULL) return NULL;
Lut = cmsPipelineAlloc(ContextID, 1, 3);
- if (Lut == NULL) return NULL;
+ if (Lut == NULL)
+ goto Error;
if (cmsGetPCS(hProfile) == cmsSigLabData) {
@@ -204,28 +204,35 @@ cmsPipeline* BuildGrayInputMatrixPipeline(cmsHPROFILE hProfile)
EmptyTab = cmsBuildTabulatedToneCurve16(ContextID, 2, Zero);
- if (EmptyTab == NULL) {
-
- cmsPipelineFree(Lut);
- return NULL;
- }
+ if (EmptyTab == NULL)
+ goto Error;
LabCurves[0] = GrayTRC;
LabCurves[1] = EmptyTab;
LabCurves[2] = EmptyTab;
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 1, OneToThreeInputMatrix, NULL));
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, LabCurves));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 1, OneToThreeInputMatrix, NULL)) ||
+ !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, LabCurves))) {
+ cmsFreeToneCurve(EmptyTab);
+ goto Error;
+ }
cmsFreeToneCurve(EmptyTab);
}
else {
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &GrayTRC));
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 1, GrayInputMatrix, NULL));
+
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &GrayTRC)) ||
+ !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 1, GrayInputMatrix, NULL)))
+ goto Error;
}
return Lut;
+
+Error:
+ cmsFreeToneCurve(GrayTRC);
+ cmsPipelineFree(Lut);
+ return NULL;
}
// RGB Matrix shaper
@@ -259,49 +266,31 @@ cmsPipeline* BuildRGBInputMatrixShaper(cmsHPROFILE hProfile)
Lut = cmsPipelineAlloc(ContextID, 3, 3);
if (Lut != NULL) {
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, Shapes));
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Mat, NULL));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, Shapes)) ||
+ !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Mat, NULL)))
+ goto Error;
// Note that it is certainly possible a single profile would have a LUT based
// tag for output working in lab and a matrix-shaper for the fallback cases.
// This is not allowed by the spec, but this code is tolerant to those cases
if (cmsGetPCS(hProfile) == cmsSigLabData) {
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocXYZ2Lab(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocXYZ2Lab(ContextID)))
+ goto Error;
}
}
return Lut;
+
+Error:
+ cmsPipelineFree(Lut);
+ return NULL;
}
// Read the DToAX tag, adjusting the encoding of Lab or XYZ if neded
-/*static
-cmsPipeline* _cmsReadFloatInputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
-{
- cmsContext ContextID = cmsGetProfileContextID(hProfile);
- cmsPipeline* Lut = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
- cmsColorSpaceSignature spc = cmsGetColorSpace(hProfile);
-
- if (Lut == NULL) return NULL;
-
- // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding,
- // and since the formatter has already accomodated to 0..1.0, we should undo this change
- if ( spc == cmsSigLabData)
- {
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID));
- }
- else
- if (spc == cmsSigXYZData)
- {
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID));
- }
-
- return Lut;
-}
-*/
static
cmsPipeline* _cmsReadFloatInputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
{
@@ -316,23 +305,31 @@ cmsPipeline* _cmsReadFloatInputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloa
// these need to be normalized into the appropriate ranges (Lab = 100,0,0, XYZ=1.0,1.0,1.0)
if ( spc == cmsSigLabData)
{
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
+ goto Error;
}
else if (spc == cmsSigXYZData)
{
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
+ goto Error;
}
if ( PCS == cmsSigLabData)
{
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
+ goto Error;
}
else if( PCS == cmsSigXYZData)
{
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
+ goto Error;
}
return Lut;
+
+Error:
+ cmsPipelineFree(Lut);
+ return NULL;
}
@@ -359,8 +356,11 @@ cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent)
return NULL;
}
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, TRUE));
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, TRUE)) ||
+ !cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID))) {
+ cmsPipelineFree(Lut);
+ return NULL;
+ }
return Lut;
}
@@ -395,12 +395,18 @@ cmsPipeline* _cmsReadInputLUT(cmsHPROFILE hProfile, int Intent)
return Lut;
// If the input is Lab, add also a conversion at the begin
- if (cmsGetColorSpace(hProfile) == cmsSigLabData)
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
+ if (cmsGetColorSpace(hProfile) == cmsSigLabData &&
+ !cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
+ goto Error;
// Add a matrix for conversion V2 to V4 Lab PCS
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+ goto Error;
+
return Lut;
+Error:
+ cmsPipelineFree(Lut);
+ return NULL;
}
// Lut was not found, try to create a matrix-shaper
@@ -445,21 +451,27 @@ cmsPipeline* BuildGrayOutputPipeline(cmsHPROFILE hProfile)
if (cmsGetPCS(hProfile) == cmsSigLabData) {
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1, 3, PickLstarMatrix, NULL));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1, 3, PickLstarMatrix, NULL)))
+ goto Error;
}
else {
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1, 3, PickYMatrix, NULL));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 1, 3, PickYMatrix, NULL)))
+ goto Error;
}
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &RevGrayTRC));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 1, &RevGrayTRC)))
+ goto Error;
+
cmsFreeToneCurve(RevGrayTRC);
-
return Lut;
+
+Error:
+ cmsFreeToneCurve(RevGrayTRC);
+ cmsPipelineFree(Lut);
+ return NULL;
}
-
-
static
cmsPipeline* BuildRGBOutputMatrixShaper(cmsHPROFILE hProfile)
{
@@ -506,15 +518,21 @@ cmsPipeline* BuildRGBOutputMatrixShaper(cmsHPROFILE hProfile)
// This is not allowed by the spec, but this code is tolerant to those cases
if (cmsGetPCS(hProfile) == cmsSigLabData) {
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLab2XYZ(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLab2XYZ(ContextID)))
+ goto Error;
}
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Inv, NULL));
- cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, InvShapes));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocMatrix(ContextID, 3, 3, (cmsFloat64Number*) &Inv, NULL)) ||
+ !cmsPipelineInsertStage(Lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, 3, InvShapes)))
+ goto Error;
}
cmsFreeToneCurveTriple(InvShapes);
return Lut;
+Error:
+ cmsFreeToneCurveTriple(InvShapes);
+ cmsPipelineFree(Lut);
+ return NULL;
}
@@ -540,30 +558,6 @@ void ChangeInterpolationToTrilinear(cmsPipeline* Lut)
// Read the DToAX tag, adjusting the encoding of Lab or XYZ if neded
-/*static
-cmsPipeline* _cmsReadFloatOutputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
-{
- cmsContext ContextID = cmsGetProfileContextID(hProfile);
- cmsPipeline* Lut = cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
- cmsColorSpaceSignature PCS = cmsGetPCS(hProfile);
-
- if (Lut == NULL) return NULL;
-
- // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding,
- // and since the formatter has already accomodated to 0..1.0, we should undo this change
- if ( PCS == cmsSigLabData)
- {
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID));
- }
- else
- if (PCS == cmsSigXYZData)
- {
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID));
- }
-
- return Lut;
-}*/
-
static
cmsPipeline* _cmsReadFloatOutputTag(cmsHPROFILE hProfile, cmsTagSignature tagFloat)
{
@@ -578,25 +572,33 @@ cmsPipeline* _cmsReadFloatOutputTag(cmsHPROFILE hProfile, cmsTagSignature tagFlo
// and since the formatter has already accomodated to 0..1.0, we should undo this change
if ( PCS == cmsSigLabData)
{
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
+ goto Error;
}
else
if (PCS == cmsSigXYZData)
{
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
+ goto Error;
}
// the output can be Lab or XYZ, in which case normalisation is needed on the end of the pipeline
if ( dataSpace == cmsSigLabData)
{
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
+ goto Error;
}
- else if ( dataSpace == cmsSigXYZData)
+ else if (dataSpace == cmsSigXYZData)
{
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
+ goto Error;
}
return Lut;
+
+Error:
+ cmsPipelineFree(Lut);
+ return NULL;
}
// Create an output MPE LUT from agiven profile. Version mismatches are handled here
@@ -636,30 +638,35 @@ cmsPipeline* _cmsReadOutputLUT(cmsHPROFILE hProfile, int Intent)
// Now it is time for a controversial stuff. I found that for 3D LUTS using
// Lab used as indexer space, trilinear interpolation should be used
if (cmsGetPCS(hProfile) == cmsSigLabData)
- ChangeInterpolationToTrilinear(Lut);
+ ChangeInterpolationToTrilinear(Lut);
// We need to adjust data only for Lab and Lut16 type
if (OriginalType != cmsSigLut16Type || cmsGetPCS(hProfile) != cmsSigLabData)
return Lut;
// Add a matrix for conversion V4 to V2 Lab PCS
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
+ goto Error;
// If the output is Lab, add also a conversion at the end
if (cmsGetColorSpace(hProfile) == cmsSigLabData)
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+ goto Error;
return Lut;
+Error:
+ cmsPipelineFree(Lut);
+ return NULL;
}
// Lut not found, try to create a matrix-shaper
// Check if this is a grayscale profile.
- if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
+ if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
- // if so, build appropiate conversion tables.
- // The tables are the PCS iluminant, scaled across GrayTRC
- return BuildGrayOutputPipeline(hProfile);
+ // if so, build appropiate conversion tables.
+ // The tables are the PCS iluminant, scaled across GrayTRC
+ return BuildGrayOutputPipeline(hProfile);
}
// Not gray, create a normal matrix-shaper, which only operates in XYZ space
@@ -681,25 +688,32 @@ cmsPipeline* _cmsReadFloatDevicelinkTag(cmsHPROFILE hProfile, cmsTagSignature ta
if (spc == cmsSigLabData)
{
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
+ goto Error;
}
else
if (spc == cmsSigXYZData)
{
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToXyzFloat(ContextID)))
+ goto Error;
}
if (PCS == cmsSigLabData)
{
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromLabFloat(ContextID)))
+ goto Error;
}
else
if (PCS == cmsSigXYZData)
{
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageNormalizeFromXyzFloat(ContextID)))
+ goto Error;
}
- return Lut;
+ return Lut;
+Error:
+ cmsPipelineFree(Lut);
+ return NULL;
}
// This one includes abstract profiles as well. Matrix-shaper cannot be obtained on that device class. The
@@ -721,15 +735,21 @@ cmsPipeline* _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent)
if (nc == NULL) return NULL;
Lut = cmsPipelineAlloc(ContextID, 0, 0);
- if (Lut == NULL) {
- cmsFreeNamedColorList(nc);
- return NULL;
- }
+ if (Lut == NULL)
+ goto Error;
+
+ if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, FALSE)))
+ goto Error;
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocNamedColor(nc, FALSE));
if (cmsGetColorSpace(hProfile) == cmsSigLabData)
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
+ if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+ goto Error;
+
return Lut;
+Error:
+ cmsPipelineFree(Lut);
+ cmsFreeNamedColorList(nc);
+ return NULL;
}
if (cmsIsTag(hProfile, tagFloat)) { // Float tag takes precedence
@@ -760,10 +780,10 @@ cmsPipeline* _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent)
Lut = cmsPipelineDup(Lut);
if (Lut == NULL) return NULL;
- // Now it is time for a controversial stuff. I found that for 3D LUTS using
- // Lab used as indexer space, trilinear interpolation should be used
+ // Now it is time for a controversial stuff. I found that for 3D LUTS using
+ // Lab used as indexer space, trilinear interpolation should be used
if (cmsGetColorSpace(hProfile) == cmsSigLabData)
- ChangeInterpolationToTrilinear(Lut);
+ ChangeInterpolationToTrilinear(Lut);
// After reading it, we have info about the original type
OriginalType = _cmsGetTagTrueType(hProfile, tag16);
@@ -774,16 +794,20 @@ cmsPipeline* _cmsReadDevicelinkLUT(cmsHPROFILE hProfile, int Intent)
// Here it is possible to get Lab on both sides
if (cmsGetPCS(hProfile) == cmsSigLabData) {
- cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID));
+ if(!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
+ goto Error2;
}
if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
- cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID));
+ if(!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+ goto Error2;
}
return Lut;
-
+Error2:
+ cmsPipelineFree(Lut);
+ return NULL;
}
// ---------------------------------------------------------------------------------------------------------------
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
index 07bc7cf8d2f..8aded52aecb 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
@@ -264,10 +264,10 @@ Error:
if (NewElem ->TheCurves != NULL) {
for (i=0; i < NewElem ->nCurves; i++) {
if (NewElem ->TheCurves[i])
- cmsFreeToneCurve(Data ->TheCurves[i]);
+ cmsFreeToneCurve(NewElem ->TheCurves[i]);
}
}
- _cmsFree(mpe ->ContextID, Data ->TheCurves);
+ _cmsFree(mpe ->ContextID, NewElem ->TheCurves);
_cmsFree(mpe ->ContextID, NewElem);
return NULL;
}
@@ -392,6 +392,8 @@ static
void MatrixElemTypeFree(cmsStage* mpe)
{
_cmsStageMatrixData* Data = (_cmsStageMatrixData*) mpe ->Data;
+ if (Data == NULL)
+ return;
if (Data ->Double)
_cmsFree(mpe ->ContextID, Data ->Double);
@@ -526,10 +528,15 @@ void* CLUTElemDup(cmsStage* mpe)
if (Data ->Tab.T) {
- if (Data ->HasFloatValues)
+ if (Data ->HasFloatValues) {
NewElem ->Tab.TFloat = (cmsFloat32Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.TFloat, Data ->nEntries * sizeof (cmsFloat32Number));
- else
+ if (NewElem ->Tab.TFloat == NULL)
+ goto Error;
+ } else {
NewElem ->Tab.T = (cmsUInt16Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.T, Data ->nEntries * sizeof (cmsUInt16Number));
+ if (NewElem ->Tab.TFloat == NULL)
+ goto Error;
+ }
}
NewElem ->Params = _cmsComputeInterpParamsEx(mpe ->ContextID,
@@ -538,8 +545,14 @@ void* CLUTElemDup(cmsStage* mpe)
Data ->Params ->nOutputs,
NewElem ->Tab.T,
Data ->Params ->dwFlags);
-
- return (void*) NewElem;
+ if (NewElem->Params != NULL)
+ return (void*) NewElem;
+ Error:
+ if (NewElem->Tab.T)
+ // This works for both types
+ _cmsFree(mpe ->ContextID, NewElem -> Tab.T);
+ _cmsFree(mpe ->ContextID, NewElem);
+ return NULL;
}
@@ -636,7 +649,6 @@ cmsStage* CMSEXPORT cmsStageAllocCLut16bit(cmsContext ContextID,
for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
Dimensions[i] = nGridPoints;
-
return cmsStageAllocCLut16bitGranular(ContextID, Dimensions, inputChan, outputChan, Table);
}
@@ -706,15 +718,12 @@ cmsStage* CMSEXPORT cmsStageAllocCLutFloatGranular(cmsContext ContextID, const c
}
}
-
NewElem ->Params = _cmsComputeInterpParamsEx(ContextID, clutPoints, inputChan, outputChan, NewElem ->Tab.TFloat, CMS_LERP_FLAGS_FLOAT);
if (NewElem ->Params == NULL) {
cmsStageFree(NewMPE);
return NULL;
}
-
-
return NewMPE;
}
@@ -772,7 +781,7 @@ cmsBool CMSEXPORT cmsStageSampleCLut16bit(cmsStage* mpe, cmsSAMPLER16 Sampler, v
int i, t, nTotalPoints, index, rest;
int nInputs, nOutputs;
cmsUInt32Number* nSamples;
- cmsUInt16Number In[cmsMAXCHANNELS], Out[MAX_STAGE_CHANNELS];
+ cmsUInt16Number In[MAX_INPUT_DIMENSIONS+1], Out[MAX_STAGE_CHANNELS];
_cmsStageCLutData* clut;
if (mpe == NULL) return FALSE;
@@ -785,7 +794,9 @@ cmsBool CMSEXPORT cmsStageSampleCLut16bit(cmsStage* mpe, cmsSAMPLER16 Sampler, v
nInputs = clut->Params ->nInputs;
nOutputs = clut->Params ->nOutputs;
- if (nInputs >= cmsMAXCHANNELS) return FALSE;
+ if (nInputs <= 0) return FALSE;
+ if (nOutputs <= 0) return FALSE;
+ if (nInputs > MAX_INPUT_DIMENSIONS) return FALSE;
if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
nTotalPoints = CubeSize(nSamples, nInputs);
@@ -832,14 +843,16 @@ cmsBool CMSEXPORT cmsStageSampleCLutFloat(cmsStage* mpe, cmsSAMPLERFLOAT Sampler
int i, t, nTotalPoints, index, rest;
int nInputs, nOutputs;
cmsUInt32Number* nSamples;
- cmsFloat32Number In[cmsMAXCHANNELS], Out[MAX_STAGE_CHANNELS];
+ cmsFloat32Number In[MAX_INPUT_DIMENSIONS+1], Out[MAX_STAGE_CHANNELS];
_cmsStageCLutData* clut = (_cmsStageCLutData*) mpe->Data;
nSamples = clut->Params ->nSamples;
nInputs = clut->Params ->nInputs;
nOutputs = clut->Params ->nOutputs;
- if (nInputs >= cmsMAXCHANNELS) return FALSE;
+ if (nInputs <= 0) return FALSE;
+ if (nOutputs <= 0) return FALSE;
+ if (nInputs > MAX_INPUT_DIMENSIONS) return FALSE;
if (nOutputs >= MAX_STAGE_CHANNELS) return FALSE;
nTotalPoints = CubeSize(nSamples, nInputs);
@@ -1021,8 +1034,7 @@ cmsStage* _cmsStageAllocLabV2ToV4curves(cmsContext ContextID)
mpe = cmsStageAllocToneCurves(ContextID, 3, LabTable);
cmsFreeToneCurveTriple(LabTable);
- if (mpe == NULL) return mpe;
-
+ if (mpe == NULL) return NULL;
mpe ->Implements = cmsSigLabV2toV4;
return mpe;
}
@@ -1248,12 +1260,22 @@ cmsStage* CMSEXPORT cmsStageDup(cmsStage* mpe)
NULL);
if (NewMPE == NULL) return NULL;
- NewMPE ->Implements = mpe ->Implements;
+ NewMPE ->Implements = mpe ->Implements;
+
+ if (mpe ->DupElemPtr) {
+
+ NewMPE ->Data = mpe ->DupElemPtr(mpe);
+
+ if (NewMPE->Data == NULL) {
+
+ cmsStageFree(NewMPE);
+ return NULL;
+ }
+
+ } else {
- if (mpe ->DupElemPtr)
- NewMPE ->Data = mpe ->DupElemPtr(mpe);
- else
NewMPE ->Data = NULL;
+ }
return NewMPE;
}
@@ -1266,7 +1288,7 @@ cmsStage* CMSEXPORT cmsStageDup(cmsStage* mpe)
static
void BlessLUT(cmsPipeline* lut)
{
- // We can set the input/output channels only if we have elements.
+ // We can set the input/ouput channels only if we have elements.
if (lut ->Elements != NULL) {
cmsStage *First, *Last;
@@ -1466,12 +1488,12 @@ cmsPipeline* CMSEXPORT cmsPipelineDup(const cmsPipeline* lut)
}
-void CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe)
+int CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe)
{
cmsStage* Anterior = NULL, *pt;
- _cmsAssert(lut != NULL);
- _cmsAssert(mpe != NULL);
+ if (lut == NULL || mpe == NULL)
+ return FALSE;
switch (loc) {
@@ -1495,9 +1517,11 @@ void CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStag
}
break;
default:;
+ return FALSE;
}
BlessLUT(lut);
+ return TRUE;
}
// Unlink an element and return the pointer to it
@@ -1559,7 +1583,7 @@ void CMSEXPORT cmsPipelineUnlinkStage(cmsPipeline* lut, cmsStageLoc loc, cmsStag
// Concatenate two LUT into a new single one
cmsBool CMSEXPORT cmsPipelineCat(cmsPipeline* l1, const cmsPipeline* l2)
{
- cmsStage* mpe, *NewMPE;
+ cmsStage* mpe;
// If both LUTS does not have elements, we need to inherit
// the number of channels
@@ -1574,17 +1598,12 @@ cmsBool CMSEXPORT cmsPipelineCat(cmsPipeline* l1, const cmsPipeline* l2)
mpe = mpe ->Next) {
// We have to dup each element
- NewMPE = cmsStageDup(mpe);
-
- if (NewMPE == NULL) {
- return FALSE;
- }
-
- cmsPipelineInsertStage(l1, cmsAT_END, NewMPE);
+ if (!cmsPipelineInsertStage(l1, cmsAT_END, cmsStageDup(mpe)))
+ return FALSE;
}
- BlessLUT(l1);
- return TRUE;
+ BlessLUT(l1);
+ return TRUE;
}
@@ -1714,16 +1733,11 @@ cmsBool CMSEXPORT cmsPipelineEvalReverseFloat(cmsFloat32Number Target[],
cmsFloat32Number fx[4], x[4], xd[4], fxd[4];
cmsVEC3 tmp, tmp2;
cmsMAT3 Jacobian;
- cmsFloat64Number LastResult[4];
-
// Only 3->3 and 4->3 are supported
if (lut ->InputChannels != 3 && lut ->InputChannels != 4) return FALSE;
if (lut ->OutputChannels != 3) return FALSE;
- // Mark result of -1
- LastResult[0] = LastResult[1] = LastResult[2] = -1.0f;
-
// Take the hint as starting point if specified
if (Hint == NULL) {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
index ae00376ce3c..c238e4168eb 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
@@ -338,7 +338,7 @@ cmsBool CMSEXPORT cmsMD5computeID(cmsHPROFILE hProfile)
Error:
// Free resources as something went wrong
- if (MD5 != NULL) _cmsFree(ContextID, MD5);
+ // "MD5" cannot be other than NULL here, so no need to free it
if (Mem != NULL) _cmsFree(ContextID, Mem);
memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
return FALSE;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
index de4a0fd1f06..4da41537f7b 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
@@ -359,9 +359,9 @@ const wchar_t* _cmsMLUgetWide(const cmsMLU* mlu,
if (Best == -1)
Best = 0;
- v = mlu ->Entries + Best;
+ v = mlu ->Entries + Best;
- if (UsedLanguageCode != NULL) *UsedLanguageCode = v ->Language;
+ if (UsedLanguageCode != NULL) *UsedLanguageCode = v ->Language;
if (UsedCountryCode != NULL) *UsedCountryCode = v ->Country;
if (len != NULL) *len = v ->Len;
@@ -475,6 +475,35 @@ CMSAPI cmsBool CMSEXPORT cmsMLUgetTranslation(const cmsMLU* mlu,
}
+
+// Get the number of translations in the MLU object
+cmsUInt32Number CMSEXPORT cmsMLUtranslationsCount(const cmsMLU* mlu)
+{
+ if (mlu == NULL) return 0;
+ return mlu->UsedEntries;
+}
+
+// Get the language and country codes for a specific MLU index
+cmsBool CMSEXPORT cmsMLUtranslationsCodes(const cmsMLU* mlu,
+ cmsUInt32Number idx,
+ char LanguageCode[3],
+ char CountryCode[3])
+{
+ _cmsMLUentry *entry;
+
+ if (mlu == NULL) return FALSE;
+
+ if (idx >= (cmsUInt32Number) mlu->UsedEntries) return FALSE;
+
+ entry = &mlu->Entries[idx];
+
+ *(cmsUInt16Number *)LanguageCode = _cmsAdjustEndianess16(entry->Language);
+ *(cmsUInt16Number *)CountryCode = _cmsAdjustEndianess16(entry->Country);
+
+ return TRUE;
+}
+
+
// Named color lists --------------------------------------------------------------------------------------------
// Grow the list to keep at least NumElements
@@ -517,9 +546,9 @@ cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID, cmsUIn
while (v -> Allocated < n)
GrowNamedColorList(v);
- strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix) - 1);
- strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix) - 1);
- v->Prefix[sizeof(v ->Prefix) - 1] = v->Suffix[sizeof(v ->Suffix) - 1] = 0;
+ strncpy(v ->Prefix, Prefix, sizeof(v ->Prefix)-1);
+ strncpy(v ->Suffix, Suffix, sizeof(v ->Suffix)-1);
+ v->Prefix[32] = v->Suffix[32] = 0;
v -> ColorantCount = ColorantCount;
@@ -529,8 +558,9 @@ cmsNAMEDCOLORLIST* CMSEXPORT cmsAllocNamedColorList(cmsContext ContextID, cmsUIn
// Free a list
void CMSEXPORT cmsFreeNamedColorList(cmsNAMEDCOLORLIST* v)
{
+ if (v == NULL) return;
if (v ->List) _cmsFree(v ->ContextID, v ->List);
- if (v) _cmsFree(v ->ContextID, v);
+ _cmsFree(v ->ContextID, v);
}
cmsNAMEDCOLORLIST* CMSEXPORT cmsDupNamedColorList(const cmsNAMEDCOLORLIST* v)
@@ -576,11 +606,8 @@ cmsBool CMSEXPORT cmsAppendNamedColor(cmsNAMEDCOLORLIST* NamedColorList,
if (Name != NULL) {
- strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name,
- sizeof(NamedColorList ->List[NamedColorList ->nColors].Name) - 1);
-
- NamedColorList ->List[NamedColorList ->nColors].
- Name[sizeof(NamedColorList ->List[NamedColorList ->nColors].Name) - 1] = 0;
+ strncpy(NamedColorList ->List[NamedColorList ->nColors].Name, Name, cmsMAX_PATH-1);
+ NamedColorList ->List[NamedColorList ->nColors].Name[cmsMAX_PATH-1] = 0;
}
else
@@ -891,7 +918,6 @@ cmsHANDLE CMSEXPORT cmsDictDup(cmsHANDLE hDict)
{
_cmsDICT* old_dict = (_cmsDICT*) hDict;
cmsHANDLE hNew;
- _cmsDICT* new_dict;
cmsDICTentry *entry;
_cmsAssert(old_dict != NULL);
@@ -899,8 +925,6 @@ cmsHANDLE CMSEXPORT cmsDictDup(cmsHANDLE hDict)
hNew = cmsDictAlloc(old_dict ->ContextID);
if (hNew == NULL) return NULL;
- new_dict = (_cmsDICT*) hNew;
-
// Walk the list freeing all nodes
entry = old_dict ->head;
while (entry != NULL) {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
index 281f722f9f6..d184ed74b44 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
@@ -27,6 +27,7 @@
// However, the following notice accompanied the original version of this
// file:
//
+
//---------------------------------------------------------------------------------
//
// Little Color Management System
@@ -81,10 +82,6 @@ typedef struct {
int nInputs;
int nOutputs;
- // Since there is no limitation of the output number of channels, this buffer holding the connexion CLUT-shaper
- // has to be dynamically allocated. This is not the case of first step shaper-CLUT, which is limited to max inputs
- cmsUInt16Number* StageDEF;
-
_cmsInterpFn16 EvalCurveIn16[MAX_INPUT_DIMENSIONS]; // The maximum number of input channels is known in advance
cmsInterpParams* ParamsCurveIn16[MAX_INPUT_DIMENSIONS];
@@ -202,8 +199,6 @@ cmsBool PreOptimize(cmsPipeline* Lut)
{
cmsBool AnyOpt = FALSE, Opt;
- AnyOpt = FALSE;
-
do {
Opt = FALSE;
@@ -253,6 +248,7 @@ void PrelinEval16(register const cmsUInt16Number Input[],
{
Prelin16Data* p16 = (Prelin16Data*) D;
cmsUInt16Number StageABC[MAX_INPUT_DIMENSIONS];
+ cmsUInt16Number StageDEF[cmsMAXCHANNELS];
int i;
for (i=0; i < p16 ->nInputs; i++) {
@@ -260,11 +256,11 @@ void PrelinEval16(register const cmsUInt16Number Input[],
p16 ->EvalCurveIn16[i](&Input[i], &StageABC[i], p16 ->ParamsCurveIn16[i]);
}
- p16 ->EvalCLUT(StageABC, p16 ->StageDEF, p16 ->CLUTparams);
+ p16 ->EvalCLUT(StageABC, StageDEF, p16 ->CLUTparams);
for (i=0; i < p16 ->nOutputs; i++) {
- p16 ->EvalCurveOut16[i](&p16->StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]);
+ p16 ->EvalCurveOut16[i](&StageDEF[i], &Output[i], p16 ->ParamsCurveOut16[i]);
}
}
@@ -274,7 +270,6 @@ void PrelinOpt16free(cmsContext ContextID, void* ptr)
{
Prelin16Data* p16 = (Prelin16Data*) ptr;
- _cmsFree(ContextID, p16 ->StageDEF);
_cmsFree(ContextID, p16 ->EvalCurveOut16);
_cmsFree(ContextID, p16 ->ParamsCurveOut16);
@@ -289,7 +284,6 @@ void* Prelin16dup(cmsContext ContextID, const void* ptr)
if (Duped == NULL) return NULL;
- Duped ->StageDEF = _cmsCalloc(ContextID, p16 ->nOutputs, sizeof(cmsUInt16Number));
Duped ->EvalCurveOut16 = _cmsDupMem(ContextID, p16 ->EvalCurveOut16, p16 ->nOutputs * sizeof(_cmsInterpFn16));
Duped ->ParamsCurveOut16 = _cmsDupMem(ContextID, p16 ->ParamsCurveOut16, p16 ->nOutputs * sizeof(cmsInterpParams* ));
@@ -328,7 +322,6 @@ Prelin16Data* PrelinOpt16alloc(cmsContext ContextID,
p16 ->EvalCLUT = ColorMap ->Interpolation.Lerp16;
- p16 -> StageDEF = _cmsCalloc(ContextID, p16 ->nOutputs, sizeof(cmsUInt16Number));
p16 -> EvalCurveOut16 = (_cmsInterpFn16*) _cmsCalloc(ContextID, nOutputs, sizeof(_cmsInterpFn16));
p16 -> ParamsCurveOut16 = (cmsInterpParams**) _cmsCalloc(ContextID, nOutputs, sizeof(cmsInterpParams* ));
@@ -413,7 +406,7 @@ cmsBool PatchLUT(cmsStage* CLUT, cmsUInt16Number At[], cmsUInt16Number Value[],
int i, index;
if (CLUT -> Type != cmsSigCLutElemType) {
- cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut MPE");
+ cmsSignalError(CLUT->ContextID, cmsERROR_INTERNAL, "(internal) Attempt to PatchLUT on non-lut stage");
return FALSE;
}
@@ -579,8 +572,8 @@ cmsBool FixWhiteMisalignment(cmsPipeline* Lut, cmsColorSpaceSignature EntryColor
static
cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt32Number* InputFormat, cmsUInt32Number* OutputFormat, cmsUInt32Number* dwFlags)
{
- cmsPipeline* Src;
- cmsPipeline* Dest;
+ cmsPipeline* Src = NULL;
+ cmsPipeline* Dest = NULL;
cmsStage* mpe;
cmsStage* CLUT;
cmsStage *KeepPreLin = NULL, *KeepPostLin = NULL;
@@ -593,7 +586,6 @@ cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
cmsToneCurve** DataSetOut;
Prelin16Data* p16;
-
// This is a loosy optimization! does not apply in floating-point cases
if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
@@ -607,10 +599,10 @@ cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
Src = *Lut;
- // Named color pipelines cannot be optimized either
- for (mpe = cmsPipelineGetPtrToFirstStage(Src);
- mpe != NULL;
- mpe = cmsStageNext(mpe)) {
+ // Named color pipelines cannot be optimized either
+ for (mpe = cmsPipelineGetPtrToFirstStage(Src);
+ mpe != NULL;
+ mpe = cmsStageNext(mpe)) {
if (cmsStageType(mpe) == cmsSigNamedColorElemType) return FALSE;
}
@@ -632,7 +624,8 @@ cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
// All seems ok, proceed.
NewPreLin = cmsStageDup(PreLin);
- cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin);
+ if(!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, NewPreLin))
+ goto Error;
// Remove prelinearization. Since we have duplicated the curve
// in destination LUT, the sampling shoud be applied after this stage.
@@ -646,7 +639,9 @@ cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
if (CLUT == NULL) return FALSE;
// Add the CLUT to the destination LUT
- cmsPipelineInsertStage(Dest, cmsAT_END, CLUT);
+ if (!cmsPipelineInsertStage(Dest, cmsAT_END, CLUT)) {
+ goto Error;
+ }
// Postlinearization tables are kept unless indicated by flags
if (*dwFlags & cmsFLAGS_CLUT_POST_LINEARIZATION) {
@@ -662,7 +657,8 @@ cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
// All seems ok, proceed.
NewPostLin = cmsStageDup(PostLin);
- cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin);
+ if (!cmsPipelineInsertStage(Dest, cmsAT_END, NewPostLin))
+ goto Error;
// In destination LUT, the sampling shoud be applied after this stage.
cmsPipelineUnlinkStage(Src, cmsAT_END, &KeepPostLin);
@@ -673,10 +669,18 @@ cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
// Now its time to do the sampling. We have to ignore pre/post linearization
// The source LUT whithout pre/post curves is passed as parameter.
if (!cmsStageSampleCLut16bit(CLUT, XFormSampler16, (void*) Src, 0)) {
-
+Error:
// Ops, something went wrong, Restore stages
- if (KeepPreLin != NULL) cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin);
- if (KeepPostLin != NULL) cmsPipelineInsertStage(Src, cmsAT_END, KeepPostLin);
+ if (KeepPreLin != NULL) {
+ if (!cmsPipelineInsertStage(Src, cmsAT_BEGIN, KeepPreLin)) {
+ _cmsAssert(0); // This never happens
+ }
+ }
+ if (KeepPostLin != NULL) {
+ if (!cmsPipelineInsertStage(Src, cmsAT_END, KeepPostLin)) {
+ _cmsAssert(0); // This never happens
+ }
+ }
cmsPipelineFree(Dest);
return FALSE;
}
@@ -703,12 +707,11 @@ cmsBool OptimizeByResampling(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
else {
p16 = PrelinOpt16alloc(Dest ->ContextID,
- DataCLUT ->Params,
- Dest ->InputChannels,
- DataSetIn,
- Dest ->OutputChannels,
- DataSetOut);
-
+ DataCLUT ->Params,
+ Dest ->InputChannels,
+ DataSetIn,
+ Dest ->OutputChannels,
+ DataSetOut);
_cmsPipelineSetOptimizationParameters(Dest, PrelinEval16, (void*) p16, PrelinOpt16free, Prelin16dup);
}
@@ -1062,7 +1065,8 @@ cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Inte
LutPlusCurves = cmsPipelineDup(OriginalLut);
if (LutPlusCurves == NULL) goto Error;
- cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse));
+ if (!cmsPipelineInsertStage(LutPlusCurves, cmsAT_BEGIN, cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, TransReverse)))
+ goto Error;
// Create the result LUT
OptimizedLUT = cmsPipelineAlloc(OriginalLut ->ContextID, OriginalLut ->InputChannels, OriginalLut ->OutputChannels);
@@ -1071,13 +1075,15 @@ cmsBool OptimizeByComputingLinearization(cmsPipeline** Lut, cmsUInt32Number Inte
OptimizedPrelinMpe = cmsStageAllocToneCurves(OriginalLut ->ContextID, OriginalLut ->InputChannels, Trans);
// Create and insert the curves at the beginning
- cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe);
+ if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_BEGIN, OptimizedPrelinMpe))
+ goto Error;
// Allocate the CLUT for result
OptimizedCLUTmpe = cmsStageAllocCLut16bit(OriginalLut ->ContextID, nGridPoints, OriginalLut ->InputChannels, OriginalLut ->OutputChannels, NULL);
// Add the CLUT to the destination LUT
- cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe);
+ if (!cmsPipelineInsertStage(OptimizedLUT, cmsAT_END, OptimizedCLUTmpe))
+ goto Error;
// Resample the LUT
if (!cmsStageSampleCLut16bit(OptimizedCLUTmpe, XFormSampler16, (void*) LutPlusCurves, 0)) goto Error;
@@ -1205,13 +1211,14 @@ Curves16Data* CurvesAlloc(cmsContext ContextID, int nCurves, int nElements, cmsT
for (i=0; i < nCurves; i++) {
c16->Curves[i] = _cmsCalloc(ContextID, nElements, sizeof(cmsUInt16Number));
+
if (c16->Curves[i] == NULL) {
+
for (j=0; j < i; j++) {
_cmsFree(ContextID, c16->Curves[j]);
}
_cmsFree(ContextID, c16->Curves);
_cmsFree(ContextID, c16);
-
return NULL;
}
@@ -1340,7 +1347,8 @@ cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUI
// Maybe the curves are linear at the end
if (!AllCurvesAreLinear(ObtainedCurves)) {
- cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves);
+ if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, ObtainedCurves))
+ goto Error;
// If the curves are to be applied in 8 bits, we can save memory
if (_cmsFormatterIs8bit(*InputFormat)) {
@@ -1348,6 +1356,7 @@ cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUI
_cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) ObtainedCurves ->Data;
Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 256, Data ->TheCurves);
+ if (c16 == NULL) goto Error;
*dwFlags |= cmsFLAGS_NOCACHE;
_cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves8, c16, CurvesFree, CurvesDup);
@@ -1357,6 +1366,7 @@ cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUI
_cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*) cmsStageData(ObtainedCurves);
Curves16Data* c16 = CurvesAlloc(Dest ->ContextID, Data ->nCurves, 65536, Data ->TheCurves);
+ if (c16 == NULL) goto Error;
*dwFlags |= cmsFLAGS_NOCACHE;
_cmsPipelineSetOptimizationParameters(Dest, FastEvaluateCurves16, c16, CurvesFree, CurvesDup);
}
@@ -1366,7 +1376,8 @@ cmsBool OptimizeByJoiningCurves(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUI
// LUT optimizes to nothing. Set the identity LUT
cmsStageFree(ObtainedCurves);
- cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels));
+ if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageAllocIdentity(Dest ->ContextID, Src ->InputChannels)))
+ goto Error;
*dwFlags |= cmsFLAGS_NOCACHE;
_cmsPipelineSetOptimizationParameters(Dest, FastIdentity16, (void*) Dest, NULL, NULL);
@@ -1596,10 +1607,14 @@ cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
if (!Dest) return FALSE;
// Assamble the new LUT
- cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1));
+ if (!cmsPipelineInsertStage(Dest, cmsAT_BEGIN, cmsStageDup(Curve1)))
+ goto Error;
+
if (!IdentityMat)
- cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest ->ContextID, 3, 3, (const cmsFloat64Number*) &res, Data2 ->Offset));
- cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2));
+ if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageAllocMatrix(Dest ->ContextID, 3, 3, (const cmsFloat64Number*) &res, Data2 ->Offset)))
+ goto Error;
+ if (!cmsPipelineInsertStage(Dest, cmsAT_END, cmsStageDup(Curve2)))
+ goto Error;
// If identity on matrix, we can further optimize the curves, so call the join curves routine
if (IdentityMat) {
@@ -1621,6 +1636,10 @@ cmsBool OptimizeMatrixShaper(cmsPipeline** Lut, cmsUInt32Number Intent, cmsUInt3
cmsPipelineFree(Src);
*Lut = Dest;
return TRUE;
+Error:
+ // Leave Src unchanged
+ cmsPipelineFree(Dest);
+ return FALSE;
}
@@ -1650,7 +1669,7 @@ static _cmsOptimizationCollection DefaultOptimization[] = {
static _cmsOptimizationCollection* OptimizationCollection = DefaultOptimization;
// Register new ways to optimize
-cmsBool _cmsRegisterOptimizationPlugin(cmsPluginBase* Data)
+cmsBool _cmsRegisterOptimizationPlugin(cmsContext id, cmsPluginBase* Data)
{
cmsPluginOptimization* Plugin = (cmsPluginOptimization*) Data;
_cmsOptimizationCollection* fl;
@@ -1664,7 +1683,7 @@ cmsBool _cmsRegisterOptimizationPlugin(cmsPluginBase* Data)
// Optimizer callback is required
if (Plugin ->OptimizePtr == NULL) return FALSE;
- fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(sizeof(_cmsOptimizationCollection));
+ fl = (_cmsOptimizationCollection*) _cmsPluginMalloc(id, sizeof(_cmsOptimizationCollection));
if (fl == NULL) return FALSE;
// Copy the parameters
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
index 0a2ba7b4499..b89830c5506 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
@@ -316,6 +316,23 @@ cmsUInt8Number* Unroll3BytesSkip1Swap(register _cmsTRANSFORM* info,
cmsUNUSED_PARAMETER(Stride);
}
+static
+cmsUInt8Number* Unroll3BytesSkip1SwapSwapFirst(register _cmsTRANSFORM* info,
+ register cmsUInt16Number wIn[],
+ register cmsUInt8Number* accum,
+ register cmsUInt32Number Stride)
+{
+ wIn[2] = FROM_8_TO_16(*accum); accum++; // B
+ wIn[1] = FROM_8_TO_16(*accum); accum++; // G
+ wIn[0] = FROM_8_TO_16(*accum); accum++; // R
+ accum++; // A
+
+ return accum;
+
+ cmsUNUSED_PARAMETER(info);
+ cmsUNUSED_PARAMETER(Stride);
+}
+
static
cmsUInt8Number* Unroll3BytesSkip1SwapFirst(register _cmsTRANSFORM* info,
register cmsUInt16Number wIn[],
@@ -2901,6 +2918,9 @@ static cmsFormatters16 InputFormatters16[] = {
{ CHANNELS_SH(3)|EXTRA_SH(1)|BYTES_SH(1)|DOSWAP_SH(1), ANYSPACE, Unroll3BytesSkip1Swap},
{ CHANNELS_SH(3)|EXTRA_SH(1)|BYTES_SH(1)|SWAPFIRST_SH(1), ANYSPACE, Unroll3BytesSkip1SwapFirst},
+ { CHANNELS_SH(3)|EXTRA_SH(1)|BYTES_SH(1)|DOSWAP_SH(1)|SWAPFIRST_SH(1),
+ ANYSPACE, Unroll3BytesSkip1SwapSwapFirst},
+
{ CHANNELS_SH(4)|BYTES_SH(1), ANYSPACE, Unroll4Bytes},
{ CHANNELS_SH(4)|BYTES_SH(1)|FLAVOR_SH(1), ANYSPACE, Unroll4BytesReverse},
{ CHANNELS_SH(4)|BYTES_SH(1)|SWAPFIRST_SH(1), ANYSPACE, Unroll4BytesSwapFirst},
@@ -3166,7 +3186,7 @@ static cmsFormattersFactoryList* FactoryList = NULL;
// Formatters management
-cmsBool _cmsRegisterFormattersPlugin(cmsPluginBase* Data)
+cmsBool _cmsRegisterFormattersPlugin(cmsContext id, cmsPluginBase* Data)
{
cmsPluginFormatters* Plugin = (cmsPluginFormatters*) Data;
cmsFormattersFactoryList* fl ;
@@ -3178,7 +3198,7 @@ cmsBool _cmsRegisterFormattersPlugin(cmsPluginBase* Data)
return TRUE;
}
- fl = (cmsFormattersFactoryList*) _cmsPluginMalloc(sizeof(cmsFormattersFactoryList));
+ fl = (cmsFormattersFactoryList*) _cmsPluginMalloc(id, sizeof(cmsFormattersFactoryList));
if (fl == NULL) return FALSE;
fl ->Factory = Plugin ->FormattersFactory;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
index 461f253a7b7..7d39aaa7ee3 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
@@ -898,9 +898,11 @@ cmsUInt32Number CMSEXPORT cmsChannelsOf(cmsColorSpaceSignature ColorSpace)
{
switch (ColorSpace) {
+ case cmsSigMCH1Data:
case cmsSig1colorData:
case cmsSigGrayData: return 1;
+ case cmsSigMCH2Data:
case cmsSig2colorData: return 2;
case cmsSigXYZData:
@@ -912,10 +914,12 @@ cmsUInt32Number CMSEXPORT cmsChannelsOf(cmsColorSpaceSignature ColorSpace)
case cmsSigHsvData:
case cmsSigHlsData:
case cmsSigCmyData:
+ case cmsSigMCH3Data:
case cmsSig3colorData: return 3;
case cmsSigLuvKData:
case cmsSigCmykData:
+ case cmsSigMCH4Data:
case cmsSig4colorData: return 4;
case cmsSigMCH5Data:
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
index 1e91d001231..3d434859e09 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
@@ -125,10 +125,14 @@ void CMSEXPORT _cmsAdjustEndianess64(cmsUInt64Number* Result, cmsUInt64Number*
pOut[0] = pIn[7];
#else
-
_cmsAssert(Result != NULL);
+# ifdef CMS_DONT_USE_INT64
+ (*Result)[0] = QWord[0];
+ (*Result)[1] = QWord[1];
+# else
*Result = *QWord;
+# endif
#endif
}
@@ -543,10 +547,10 @@ cmsBool CMSEXPORT _cmsIOPrintf(cmsIOHANDLER* io, const char* frm, ...)
static _cmsSubAllocator* PluginPool = NULL;
// Specialized malloc for plug-ins, that is freed upon exit.
-void* _cmsPluginMalloc(cmsUInt32Number size)
+void* _cmsPluginMalloc(cmsContext id, cmsUInt32Number size)
{
if (PluginPool == NULL)
- PluginPool = _cmsCreateSubAlloc(0, 4*1024);
+ PluginPool = _cmsCreateSubAlloc(id, 4*1024);
return _cmsSubAlloc(PluginPool, size);
}
@@ -554,6 +558,11 @@ void* _cmsPluginMalloc(cmsUInt32Number size)
// Main plug-in dispatcher
cmsBool CMSEXPORT cmsPlugin(void* Plug_in)
+{
+ return cmsPluginTHR(NULL, Plug_in);
+}
+
+cmsBool CMSEXPORT cmsPluginTHR(cmsContext id, void* Plug_in)
{
cmsPluginBase* Plugin;
@@ -583,35 +592,35 @@ cmsBool CMSEXPORT cmsPlugin(void* Plug_in)
break;
case cmsPluginTagTypeSig:
- if (!_cmsRegisterTagTypePlugin(Plugin)) return FALSE;
+ if (!_cmsRegisterTagTypePlugin(id, Plugin)) return FALSE;
break;
case cmsPluginTagSig:
- if (!_cmsRegisterTagPlugin(Plugin)) return FALSE;
+ if (!_cmsRegisterTagPlugin(id, Plugin)) return FALSE;
break;
case cmsPluginFormattersSig:
- if (!_cmsRegisterFormattersPlugin(Plugin)) return FALSE;
+ if (!_cmsRegisterFormattersPlugin(id, Plugin)) return FALSE;
break;
case cmsPluginRenderingIntentSig:
- if (!_cmsRegisterRenderingIntentPlugin(Plugin)) return FALSE;
+ if (!_cmsRegisterRenderingIntentPlugin(id, Plugin)) return FALSE;
break;
case cmsPluginParametricCurveSig:
- if (!_cmsRegisterParametricCurvesPlugin(Plugin)) return FALSE;
+ if (!_cmsRegisterParametricCurvesPlugin(id, Plugin)) return FALSE;
break;
case cmsPluginMultiProcessElementSig:
- if (!_cmsRegisterMultiProcessElementPlugin(Plugin)) return FALSE;
+ if (!_cmsRegisterMultiProcessElementPlugin(id, Plugin)) return FALSE;
break;
case cmsPluginOptimizationSig:
- if (!_cmsRegisterOptimizationPlugin(Plugin)) return FALSE;
+ if (!_cmsRegisterOptimizationPlugin(id, Plugin)) return FALSE;
break;
case cmsPluginTransformSig:
- if (!_cmsRegisterTransformPlugin(Plugin)) return FALSE;
+ if (!_cmsRegisterTransformPlugin(id, Plugin)) return FALSE;
break;
default:
@@ -630,14 +639,14 @@ void CMSEXPORT cmsUnregisterPlugins(void)
{
_cmsRegisterMemHandlerPlugin(NULL);
_cmsRegisterInterpPlugin(NULL);
- _cmsRegisterTagTypePlugin(NULL);
- _cmsRegisterTagPlugin(NULL);
- _cmsRegisterFormattersPlugin(NULL);
- _cmsRegisterRenderingIntentPlugin(NULL);
- _cmsRegisterParametricCurvesPlugin(NULL);
- _cmsRegisterMultiProcessElementPlugin(NULL);
- _cmsRegisterOptimizationPlugin(NULL);
- _cmsRegisterTransformPlugin(NULL);
+ _cmsRegisterTagTypePlugin(NULL, NULL);
+ _cmsRegisterTagPlugin(NULL, NULL);
+ _cmsRegisterFormattersPlugin(NULL, NULL);
+ _cmsRegisterRenderingIntentPlugin(NULL, NULL);
+ _cmsRegisterParametricCurvesPlugin(NULL, NULL);
+ _cmsRegisterMultiProcessElementPlugin(NULL, NULL);
+ _cmsRegisterOptimizationPlugin(NULL, NULL);
+ _cmsRegisterTransformPlugin(NULL, NULL);
if (PluginPool != NULL)
_cmsSubAllocDestroy(PluginPool);
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
index a9672bdf71a..2da5a2b6a0d 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
@@ -806,7 +806,6 @@ int EmitCIEBasedDEF(cmsIOHANDLER* m, cmsPipeline* Pipeline, int Intent, cmsCIEXY
mpe = Pipeline ->Elements;
-
switch (cmsStageInputChannels(mpe)) {
case 3:
@@ -838,8 +837,6 @@ int EmitCIEBasedDEF(cmsIOHANDLER* m, cmsPipeline* Pipeline, int Intent, cmsCIEXY
mpe = mpe ->Next;
}
-
-
if (cmsStageType(mpe) == cmsSigCLutElemType) {
_cmsIOPrintf(m, "/Table ");
@@ -854,7 +851,6 @@ int EmitCIEBasedDEF(cmsIOHANDLER* m, cmsPipeline* Pipeline, int Intent, cmsCIEXY
_cmsIOPrintf(m, " >>\n");
_cmsIOPrintf(m, "]\n");
-
return 1;
}
@@ -950,6 +946,7 @@ int WriteInputLUT(cmsIOHANDLER* m, cmsHPROFILE hProfile, int Intent, cmsUInt32Nu
rc = EmitCIEBasedDEF(m, DeviceLink, Intent, &BlackPointAdaptedToD50);
cmsPipelineFree(DeviceLink);
+ if (rc == 0) return 0;
}
break;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
index 2dccc5433ff..42a5bbfe249 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
@@ -56,6 +56,8 @@
#include "lcms2_internal.h"
+#define cmsmin(a, b) (((a) < (b)) ? (a) : (b))
+#define cmsmax(a, b) (((a) > (b)) ? (a) : (b))
// This file contains routines for resampling and LUT optimization, black point detection
// and black preservation.
@@ -67,13 +69,13 @@
static
cmsHTRANSFORM CreateRoundtripXForm(cmsHPROFILE hProfile, cmsUInt32Number nIntent)
{
- cmsHPROFILE hLab = cmsCreateLab4Profile(NULL);
+ cmsContext ContextID = cmsGetProfileContextID(hProfile);
+ cmsHPROFILE hLab = cmsCreateLab4ProfileTHR(ContextID, NULL);
cmsHTRANSFORM xform;
cmsBool BPC[4] = { FALSE, FALSE, FALSE, FALSE };
cmsFloat64Number States[4] = { 1.0, 1.0, 1.0, 1.0 };
cmsHPROFILE hProfiles[4];
cmsUInt32Number Intents[4];
- cmsContext ContextID = cmsGetProfileContextID(hProfile);
hProfiles[0] = hLab; hProfiles[1] = hProfile; hProfiles[2] = hProfile; hProfiles[3] = hLab;
Intents[0] = INTENT_RELATIVE_COLORIMETRIC; Intents[1] = nIntent; Intents[2] = INTENT_RELATIVE_COLORIMETRIC; Intents[3] = INTENT_RELATIVE_COLORIMETRIC;
@@ -141,8 +143,8 @@ cmsBool BlackPointAsDarkerColorant(cmsHPROFILE hInput,
cmsCloseProfile(hLab);
if (xform == NULL) {
- // Something went wrong. Get rid of open resources and return zero as black
+ // Something went wrong. Get rid of open resources and return zero as black
BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
return FALSE;
}
@@ -173,7 +175,6 @@ cmsBool BlackPointAsDarkerColorant(cmsHPROFILE hInput,
// Lab (0, 0, 0) -> [Perceptual] Profile -> CMYK -> [Rel. colorimetric] Profile -> Lab
static
cmsBool BlackPointUsingPerceptualBlack(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile)
-
{
cmsHTRANSFORM hRoundTrip;
cmsCIELab LabIn, LabOut;
@@ -218,17 +219,27 @@ cmsBool BlackPointUsingPerceptualBlack(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfi
// involves to turn BP to neutral and to use only L component.
cmsBool CMSEXPORT cmsDetectBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROFILE hProfile, cmsUInt32Number Intent, cmsUInt32Number dwFlags)
{
+ cmsProfileClassSignature devClass;
- // Zero for black point
- if (cmsGetDeviceClass(hProfile) == cmsSigLinkClass) {
+ // Make sure the device class is adequate
+ devClass = cmsGetDeviceClass(hProfile);
+ if (devClass == cmsSigLinkClass ||
+ devClass == cmsSigAbstractClass ||
+ devClass == cmsSigNamedColorClass) {
+ BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+ return FALSE;
+ }
- BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
- return FALSE;
+ // Make sure intent is adequate
+ if (Intent != INTENT_PERCEPTUAL &&
+ Intent != INTENT_RELATIVE_COLORIMETRIC &&
+ Intent != INTENT_SATURATION) {
+ BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+ return FALSE;
}
// v4 + perceptual & saturation intents does have its own black point, and it is
// well specified enough to use it. Black point tag is deprecated in V4.
-
if ((cmsGetEncodedICCversion(hProfile) >= 0x4000000) &&
(Intent == INTENT_PERCEPTUAL || Intent == INTENT_SATURATION)) {
@@ -303,7 +314,7 @@ cmsFloat64Number RootOfLeastSquaresFitQuadraticCurve(int n, cmsFloat64Number x[]
{
double sum_x = 0, sum_x2 = 0, sum_x3 = 0, sum_x4 = 0;
double sum_y = 0, sum_yx = 0, sum_yx2 = 0;
- double disc;
+ double d, a, b, c;
int i;
cmsMAT3 m;
cmsVEC3 v, res;
@@ -333,14 +344,32 @@ cmsFloat64Number RootOfLeastSquaresFitQuadraticCurve(int n, cmsFloat64Number x[]
if (!_cmsMAT3solve(&res, &m, &v)) return 0;
- // y = t x2 + u x + c
- // x = ( - u + Sqrt( u^2 - 4 t c ) ) / ( 2 t )
- disc = res.n[1]*res.n[1] - 4.0 * res.n[0] * res.n[2];
- if (disc < 0) return -1;
- return ( -1.0 * res.n[1] + sqrt( disc )) / (2.0 * res.n[0]);
+ a = res.n[2];
+ b = res.n[1];
+ c = res.n[0];
+
+ if (fabs(a) < 1.0E-10) {
+
+ return cmsmin(0, cmsmax(50, -c/b ));
+ }
+ else {
+
+ d = b*b - 4.0 * a * c;
+ if (d <= 0) {
+ return 0;
+ }
+ else {
+
+ double rt = (-b + sqrt(d)) / (2.0 * a);
+
+ return cmsmax(0, cmsmin(50, rt));
+ }
+ }
+
}
+/*
static
cmsBool IsMonotonic(int n, const cmsFloat64Number Table[])
{
@@ -361,6 +390,7 @@ cmsBool IsMonotonic(int n, const cmsFloat64Number Table[])
return TRUE;
}
+*/
// Calculates the black point of a destination profile.
// This algorithm comes from the Adobe paper disclosing its black point compensation method.
@@ -369,21 +399,30 @@ cmsBool CMSEXPORT cmsDetectDestinationBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROF
cmsColorSpaceSignature ColorSpace;
cmsHTRANSFORM hRoundTrip = NULL;
cmsCIELab InitialLab, destLab, Lab;
-
+ cmsFloat64Number inRamp[256], outRamp[256];
cmsFloat64Number MinL, MaxL;
- cmsBool NearlyStraightMidRange = FALSE;
- cmsFloat64Number L;
- cmsFloat64Number x[101], y[101];
- cmsFloat64Number lo, hi, NonMonoMin;
- int n, l, i, NonMonoIndx;
+ cmsBool NearlyStraightMidrange = TRUE;
+ cmsFloat64Number yRamp[256];
+ cmsFloat64Number x[256], y[256];
+ cmsFloat64Number lo, hi;
+ int n, l;
+ cmsProfileClassSignature devClass;
+ // Make sure the device class is adequate
+ devClass = cmsGetDeviceClass(hProfile);
+ if (devClass == cmsSigLinkClass ||
+ devClass == cmsSigAbstractClass ||
+ devClass == cmsSigNamedColorClass) {
+ BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+ return FALSE;
+ }
// Make sure intent is adequate
if (Intent != INTENT_PERCEPTUAL &&
Intent != INTENT_RELATIVE_COLORIMETRIC &&
Intent != INTENT_SATURATION) {
- BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
- return FALSE;
+ BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+ return FALSE;
}
@@ -415,10 +454,8 @@ cmsBool CMSEXPORT cmsDetectDestinationBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROF
return cmsDetectBlackPoint(BlackPoint, hProfile, Intent, dwFlags);
}
- // It is one of the valid cases!, presto chargo hocus pocus, go for the Adobe magic
+ // It is one of the valid cases!, use Adobe algorithm
- // Step 1
- // ======
// Set a first guess, that should work on good profiles.
if (Intent == INTENT_RELATIVE_COLORIMETRIC) {
@@ -449,71 +486,68 @@ cmsBool CMSEXPORT cmsDetectDestinationBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROF
hRoundTrip = CreateRoundtripXForm(hProfile, Intent);
if (hRoundTrip == NULL) return FALSE;
- // Calculate Min L*
- Lab = InitialLab;
- Lab.L = 0;
- cmsDoTransform(hRoundTrip, &Lab, &destLab, 1);
- MinL = destLab.L;
+ // Compute ramps
- // Calculate Max L*
- Lab = InitialLab;
- Lab.L = 100;
- cmsDoTransform(hRoundTrip, &Lab, &destLab, 1);
- MaxL = destLab.L;
+ for (l=0; l < 256; l++) {
- // Step 3
- // ======
+ Lab.L = (cmsFloat64Number) (l * 100.0) / 255.0;
+ Lab.a = cmsmin(50, cmsmax(-50, InitialLab.a));
+ Lab.b = cmsmin(50, cmsmax(-50, InitialLab.b));
- // check if quadratic estimation needs to be done.
+ cmsDoTransform(hRoundTrip, &Lab, &destLab, 1);
+
+ inRamp[l] = Lab.L;
+ outRamp[l] = destLab.L;
+ }
+
+ // Make monotonic
+ for (l = 254; l > 0; --l) {
+ outRamp[l] = cmsmin(outRamp[l], outRamp[l+1]);
+ }
+
+ // Check
+ if (! (outRamp[0] < outRamp[255])) {
+
+ cmsDeleteTransform(hRoundTrip);
+ BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+ return FALSE;
+ }
+
+
+ // Test for mid range straight (only on relative colorimetric)
+
+ NearlyStraightMidrange = TRUE;
+ MinL = outRamp[0]; MaxL = outRamp[255];
if (Intent == INTENT_RELATIVE_COLORIMETRIC) {
- // Conceptually, this code tests how close the source l and converted L are to one another in the mid-range
- // of the values. If the converted ramp of L values is close enough to a straight line y=x, then InitialLab
- // is good enough to be the DestinationBlackPoint,
- NearlyStraightMidRange = TRUE;
+ for (l=0; l < 256; l++) {
- for (l=0; l <= 100; l++) {
+ if (! ((inRamp[l] <= MinL + 0.2 * (MaxL - MinL) ) ||
+ (fabs(inRamp[l] - outRamp[l]) < 4.0 )))
+ NearlyStraightMidrange = FALSE;
+ }
- Lab.L = l;
- Lab.a = InitialLab.a;
- Lab.b = InitialLab.b;
+ // If the mid range is straight (as determined above) then the
+ // DestinationBlackPoint shall be the same as initialLab.
+ // Otherwise, the DestinationBlackPoint shall be determined
+ // using curve fitting.
- cmsDoTransform(hRoundTrip, &Lab, &destLab, 1);
+ if (NearlyStraightMidrange) {
- L = destLab.L;
-
- // Check the mid range in 20% after MinL
- if (L > (MinL + 0.2 * (MaxL - MinL))) {
-
- // Is close enough?
- if (fabs(L - l) > 4.0) {
-
- // Too far away, profile is buggy!
- NearlyStraightMidRange = FALSE;
- break;
- }
- }
+ cmsLab2XYZ(NULL, BlackPoint, &InitialLab);
+ cmsDeleteTransform(hRoundTrip);
+ return TRUE;
}
}
- else {
- // Check is always performed for perceptual and saturation intents
- NearlyStraightMidRange = FALSE;
- }
- // If no furter checking is needed, we are done
- if (NearlyStraightMidRange) {
-
- cmsLab2XYZ(NULL, BlackPoint, &InitialLab);
- cmsDeleteTransform(hRoundTrip);
- return TRUE;
- }
-
- // The round-trip curve normally looks like a nearly constant section at the black point,
+ // curve fitting: The round-trip curve normally looks like a nearly constant section at the black point,
// with a corner and a nearly straight line to the white point.
- // STEP 4
- // =======
+ for (l=0; l < 256; l++) {
+
+ yRamp[l] = (outRamp[l] - MinL) / (MaxL - MinL);
+ }
// find the black point using the least squares error quadratic curve fitting
@@ -528,62 +562,32 @@ cmsBool CMSEXPORT cmsDetectDestinationBlackPoint(cmsCIEXYZ* BlackPoint, cmsHPROF
hi = 0.25;
}
- // Capture points for the fitting.
+ // Capture shadow points for the fitting.
n = 0;
- for (l=0; l <= 100; l++) {
+ for (l=0; l < 256; l++) {
- cmsFloat64Number ff;
-
- Lab.L = (cmsFloat64Number) l;
- Lab.a = InitialLab.a;
- Lab.b = InitialLab.b;
-
- cmsDoTransform(hRoundTrip, &Lab, &destLab, 1);
-
- ff = (destLab.L - MinL)/(MaxL - MinL);
+ cmsFloat64Number ff = yRamp[l];
if (ff >= lo && ff < hi) {
-
- x[n] = Lab.L;
- y[n] = ff;
+ x[n] = inRamp[l];
+ y[n] = yRamp[l];
n++;
}
-
}
- // This part is not on the Adobe paper, but I found is necessary for getting any result.
- if (IsMonotonic(n, y)) {
-
- // Monotonic means lower point is stil valid
- cmsLab2XYZ(NULL, BlackPoint, &InitialLab);
+ // No suitable points
+ if (n < 3 ) {
cmsDeleteTransform(hRoundTrip);
- return TRUE;
+ BlackPoint -> X = BlackPoint ->Y = BlackPoint -> Z = 0.0;
+ return FALSE;
}
- // No suitable points, regret and use safer algorithm
- if (n == 0) {
- cmsDeleteTransform(hRoundTrip);
- return cmsDetectBlackPoint(BlackPoint, hProfile, Intent, dwFlags);
- }
-
-
- NonMonoMin = 100;
- NonMonoIndx = 0;
- for (i=0; i < n; i++) {
-
- if (y[i] < NonMonoMin) {
- NonMonoIndx = i;
- NonMonoMin = y[i];
- }
- }
-
- Lab.L = x[NonMonoIndx];
// fit and get the vertex of quadratic curve
Lab.L = RootOfLeastSquaresFitQuadraticCurve(n, x, y);
- if (Lab.L < 0.0 || Lab.L > 50.0) { // clip to zero L* if the vertex is negative
+ if (Lab.L < 0.0) { // clip to zero L* if the vertex is negative
Lab.L = 0;
}
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
index 79cdda7c43e..f434cfde6b0 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
@@ -91,7 +91,7 @@ typedef struct _cmsTagTypeLinkedList_st {
// Register a new type handler. This routine is shared between normal types and MPE
static
-cmsBool RegisterTypesPlugin(cmsPluginBase* Data, _cmsTagTypeLinkedList* LinkedList, cmsUInt32Number DefaultListCount)
+cmsBool RegisterTypesPlugin(cmsContext id, cmsPluginBase* Data, _cmsTagTypeLinkedList* LinkedList, cmsUInt32Number DefaultListCount)
{
cmsPluginTagType* Plugin = (cmsPluginTagType*) Data;
_cmsTagTypeLinkedList *pt, *Anterior = NULL;
@@ -118,7 +118,7 @@ cmsBool RegisterTypesPlugin(cmsPluginBase* Data, _cmsTagTypeLinkedList* LinkedLi
}
// Registering happens in plug-in memory pool
- pt = (_cmsTagTypeLinkedList*) _cmsPluginMalloc(sizeof(_cmsTagTypeLinkedList));
+ pt = (_cmsTagTypeLinkedList*) _cmsPluginMalloc(id, sizeof(_cmsTagTypeLinkedList));
if (pt == NULL) return FALSE;
pt ->Handler = Plugin ->Handler;
@@ -208,10 +208,10 @@ cmsBool ReadPositionTable(struct _cms_typehandler_struct* self,
cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL;
// Let's take the offsets to each element
- ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number *));
+ ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number));
if (ElementOffsets == NULL) goto Error;
- ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number *));
+ ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number));
if (ElementSizes == NULL) goto Error;
for (i=0; i < Count; i++) {
@@ -257,10 +257,10 @@ cmsBool WritePositionTable(struct _cms_typehandler_struct* self,
cmsUInt32Number *ElementOffsets = NULL, *ElementSizes = NULL;
// Create table
- ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number *));
+ ElementOffsets = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number));
if (ElementOffsets == NULL) goto Error;
- ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number *));
+ ElementSizes = (cmsUInt32Number *) _cmsCalloc(io ->ContextID, Count, sizeof(cmsUInt32Number));
if (ElementSizes == NULL) goto Error;
// Keep starting position of curve offsets
@@ -456,6 +456,7 @@ static
void* Type_Chromaticity_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
{
return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsCIExyYTRIPLE));
+
cmsUNUSED_PARAMETER(n);
}
@@ -1106,8 +1107,6 @@ void *Type_Curve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cm
{
cmsUInt32Number Count;
cmsToneCurve* NewGamma;
- cmsUInt16Number Linear[2] = { 0, 0xffff };
-
*nItems = 0;
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
@@ -1115,11 +1114,14 @@ void *Type_Curve_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cm
switch (Count) {
case 0: // Linear.
+ {
+ cmsFloat64Number SingleGamma = 1.0;
- NewGamma = cmsBuildTabulatedToneCurve16(self ->ContextID, 2, Linear);
- if (!NewGamma) return NULL;
- *nItems = 1;
- return NewGamma;
+ NewGamma = cmsBuildParametricToneCurve(self ->ContextID, 1, &SingleGamma);
+ if (!NewGamma) return NULL;
+ *nItems = 1;
+ return NewGamma;
+ }
case 1: // Specified as the exponent of gamma function
{
@@ -1210,6 +1212,7 @@ cmsTagTypeSignature DecideCurveType(cmsFloat64Number ICCVersion, const void *Dat
if (ICCVersion < 4.0) return cmsSigCurveType;
if (Curve ->nSegments != 1) return cmsSigCurveType; // Only 1-segment curves can be saved as parametric
if (Curve ->Segments[0].Type < 0) return cmsSigCurveType; // Only non-inverted curves
+ if (Curve ->Segments[0].Type > 5) return cmsSigCurveType; // Only ICC parametric curves
return cmsSigParametricCurveType;
}
@@ -1386,6 +1389,9 @@ void *Type_Measurement_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER*
{
cmsICCMeasurementConditions mc;
+
+ memset(&mc, 0, sizeof(mc));
+
if (!_cmsReadUInt32Number(io, &mc.Observer)) return NULL;
if (!_cmsReadXYZNumber(io, &mc.Backing)) return NULL;
if (!_cmsReadUInt32Number(io, &mc.Geometry)) return NULL;
@@ -1640,7 +1646,6 @@ Byte Position Field Length (bytes) Content Encoded as...
static
cmsBool Read8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut, int nChannels)
{
- cmsStage* mpe;
cmsUInt8Number* Temp = NULL;
int i, j;
cmsToneCurve* Tables[cmsMAXCHANNELS];
@@ -1669,11 +1674,8 @@ cmsBool Read8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut
_cmsFree(ContextID, Temp);
Temp = NULL;
-
- mpe = cmsStageAllocToneCurves(ContextID, nChannels, Tables);
- if (mpe == NULL) goto Error;
-
- cmsPipelineInsertStage(lut, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, nChannels, Tables)))
+ goto Error;
for (i=0; i < nChannels; i++)
cmsFreeToneCurve(Tables[i]);
@@ -1701,21 +1703,30 @@ cmsBool Write8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsUInt32Number
if (Tables) {
- if (Tables ->TheCurves[i]->nEntries != 256) {
- cmsSignalError(ContextID, cmsERROR_RANGE, "LUT8 needs 256 entries on prelinearization");
- return FALSE;
+ // Usual case of identity curves
+ if ((Tables ->TheCurves[i]->nEntries == 2) &&
+ (Tables->TheCurves[i]->Table16[0] == 0) &&
+ (Tables->TheCurves[i]->Table16[1] == 65535)) {
+
+ for (j=0; j < 256; j++) {
+ if (!_cmsWriteUInt8Number(io, (cmsUInt8Number) j)) return FALSE;
+ }
}
-
- }
-
- for (j=0; j < 256; j++) {
-
- if (Tables != NULL)
- val = (cmsUInt8Number) FROM_16_TO_8(Tables->TheCurves[i]->Table16[j]);
else
- val = (cmsUInt8Number) j;
+ if (Tables ->TheCurves[i]->nEntries != 256) {
+ cmsSignalError(ContextID, cmsERROR_RANGE, "LUT8 needs 256 entries on prelinearization");
+ return FALSE;
+ }
+ else
+ for (j=0; j < 256; j++) {
- if (!_cmsWriteUInt8Number(io, val)) return FALSE;
+ if (Tables != NULL)
+ val = (cmsUInt8Number) FROM_16_TO_8(Tables->TheCurves[i]->Table16[j]);
+ else
+ val = (cmsUInt8Number) j;
+
+ if (!_cmsWriteUInt8Number(io, val)) return FALSE;
+ }
}
}
return TRUE;
@@ -1724,7 +1735,7 @@ cmsBool Write8bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsUInt32Number
// Check overflow
static
-size_t uipow(cmsUInt32Number n, cmsUInt32Number a, cmsUInt32Number b)
+cmsUInt32Number uipow(cmsUInt32Number n, cmsUInt32Number a, cmsUInt32Number b)
{
cmsUInt32Number rv = 1, rc;
@@ -1736,13 +1747,13 @@ size_t uipow(cmsUInt32Number n, cmsUInt32Number a, cmsUInt32Number b)
rv *= a;
// Check for overflow
- if (rv > UINT_MAX / a) return (size_t) -1;
+ if (rv > UINT_MAX / a) return (cmsUInt32Number) -1;
}
rc = rv * n;
- if (rv != rc / n) return (size_t) -1;
+ if (rv != rc / n) return (cmsUInt32Number) -1;
return rc;
}
@@ -1757,7 +1768,6 @@ void *Type_LUT8_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cms
cmsUInt8Number InputChannels, OutputChannels, CLUTpoints;
cmsUInt8Number* Temp = NULL;
cmsPipeline* NewLUT = NULL;
- cmsStage *mpemat, *mpeclut;
cmsUInt32Number nTabSize, i;
cmsFloat64Number Matrix[3*3];
@@ -1796,9 +1806,8 @@ void *Type_LUT8_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cms
// Only operates if not identity...
if ((InputChannels == 3) && !_cmsMAT3isIdentity((cmsMAT3*) Matrix)) {
- mpemat = cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL);
- if (mpemat == NULL) goto Error;
- cmsPipelineInsertStage(NewLUT, cmsAT_BEGIN, mpemat);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_BEGIN, cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL)))
+ goto Error;
}
// Get input tables
@@ -1806,13 +1815,10 @@ void *Type_LUT8_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cms
// Get 3D CLUT. Check the overflow....
nTabSize = uipow(OutputChannels, CLUTpoints, InputChannels);
- if (nTabSize == (size_t) -1) goto Error;
+ if (nTabSize == (cmsUInt32Number) -1) goto Error;
if (nTabSize > 0) {
cmsUInt16Number *PtrW, *T;
- cmsUInt32Number Tsize;
-
- Tsize = (cmsUInt32Number) nTabSize * sizeof(cmsUInt16Number);
PtrW = T = (cmsUInt16Number*) _cmsCalloc(self ->ContextID, nTabSize, sizeof(cmsUInt16Number));
if (T == NULL) goto Error;
@@ -1829,10 +1835,8 @@ void *Type_LUT8_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cms
_cmsFree(self ->ContextID, Temp);
Temp = NULL;
-
- mpeclut = cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T);
- if (mpeclut == NULL) goto Error;
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpeclut);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T)))
+ goto Error;
_cmsFree(self ->ContextID, T);
}
@@ -1934,7 +1938,7 @@ cmsBool Type_LUT8_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io,
if (!Write8bitTables(self ->ContextID, io, NewLUT ->InputChannels, PreMPE)) return FALSE;
nTabSize = uipow(NewLUT->OutputChannels, clutPoints, NewLUT ->InputChannels);
- if (nTabSize == (size_t) -1) return FALSE;
+ if (nTabSize == (cmsUInt32Number) -1) return FALSE;
if (nTabSize > 0) {
// The 3D CLUT.
@@ -1983,7 +1987,6 @@ void Type_LUT8_Free(struct _cms_typehandler_struct* self, void* Ptr)
static
cmsBool Read16bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lut, int nChannels, int nEntries)
{
- cmsStage* mpe;
int i;
cmsToneCurve* Tables[cmsMAXCHANNELS];
@@ -2007,10 +2010,8 @@ cmsBool Read16bitTables(cmsContext ContextID, cmsIOHANDLER* io, cmsPipeline* lu
// Add the table (which may certainly be an identity, but this is up to the optimizer, not the reading code)
- mpe = cmsStageAllocToneCurves(ContextID, nChannels, Tables);
- if (mpe == NULL) goto Error;
-
- cmsPipelineInsertStage(lut, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(lut, cmsAT_END, cmsStageAllocToneCurves(ContextID, nChannels, Tables)))
+ goto Error;
for (i=0; i < nChannels; i++)
cmsFreeToneCurve(Tables[i]);
@@ -2031,7 +2032,9 @@ cmsBool Write16bitTables(cmsContext ContextID, cmsIOHANDLER* io, _cmsStageToneCu
int j;
cmsUInt32Number i;
cmsUInt16Number val;
- int nEntries = 256;
+ int nEntries;
+
+ _cmsAssert(Tables != NULL);
nEntries = Tables->TheCurves[0]->nEntries;
@@ -2039,11 +2042,7 @@ cmsBool Write16bitTables(cmsContext ContextID, cmsIOHANDLER* io, _cmsStageToneCu
for (j=0; j < nEntries; j++) {
- if (Tables != NULL)
- val = Tables->TheCurves[i]->Table16[j];
- else
- val = _cmsQuantizeVal(j, nEntries);
-
+ val = Tables->TheCurves[i]->Table16[j];
if (!_cmsWriteUInt16Number(io, val)) return FALSE;
}
}
@@ -2057,7 +2056,6 @@ void *Type_LUT16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cm
{
cmsUInt8Number InputChannels, OutputChannels, CLUTpoints;
cmsPipeline* NewLUT = NULL;
- cmsStage *mpemat, *mpeclut;
cmsUInt32Number nTabSize;
cmsFloat64Number Matrix[3*3];
cmsUInt16Number InputEntries, OutputEntries;
@@ -2094,9 +2092,8 @@ void *Type_LUT16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cm
// Only operates on 3 channels
if ((InputChannels == 3) && !_cmsMAT3isIdentity((cmsMAT3*) Matrix)) {
- mpemat = cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL);
- if (mpemat == NULL) goto Error;
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpemat);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocMatrix(self ->ContextID, 3, 3, Matrix, NULL)))
+ goto Error;
}
if (!_cmsReadUInt16Number(io, &InputEntries)) goto Error;
@@ -2110,7 +2107,7 @@ void *Type_LUT16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cm
// Get 3D CLUT
nTabSize = uipow(OutputChannels, CLUTpoints, InputChannels);
- if (nTabSize == (size_t) -1) goto Error;
+ if (nTabSize == (cmsUInt32Number) -1) goto Error;
if (nTabSize > 0) {
cmsUInt16Number *T;
@@ -2123,13 +2120,10 @@ void *Type_LUT16_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cm
goto Error;
}
- mpeclut = cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T);
- if (mpeclut == NULL) {
- _cmsFree(self ->ContextID, T);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, cmsStageAllocCLut16bit(self ->ContextID, CLUTpoints, InputChannels, OutputChannels, T))) {
+ _cmsFree(self ->ContextID, T);
goto Error;
}
-
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpeclut);
_cmsFree(self ->ContextID, T);
}
@@ -2159,7 +2153,7 @@ cmsBool Type_LUT16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io
_cmsStageToneCurvesData* PreMPE = NULL, *PostMPE = NULL;
_cmsStageMatrixData* MatMPE = NULL;
_cmsStageCLutData* clut = NULL;
- int InputChannels, OutputChannels, clutPoints;
+ int i, InputChannels, OutputChannels, clutPoints;
// Disassemble the LUT into components.
mpe = NewLUT -> Elements;
@@ -2234,13 +2228,13 @@ cmsBool Type_LUT16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io
if (PreMPE != NULL) {
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) PreMPE ->TheCurves[0]->nEntries)) return FALSE;
} else {
- if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
+ if (!_cmsWriteUInt16Number(io, 2)) return FALSE;
}
if (PostMPE != NULL) {
if (!_cmsWriteUInt16Number(io, (cmsUInt16Number) PostMPE ->TheCurves[0]->nEntries)) return FALSE;
} else {
- if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
+ if (!_cmsWriteUInt16Number(io, 2)) return FALSE;
}
@@ -2249,9 +2243,16 @@ cmsBool Type_LUT16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io
if (PreMPE != NULL) {
if (!Write16bitTables(self ->ContextID, io, PreMPE)) return FALSE;
}
+ else {
+ for (i=0; i < InputChannels; i++) {
+
+ if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
+ if (!_cmsWriteUInt16Number(io, 0xffff)) return FALSE;
+ }
+ }
nTabSize = uipow(OutputChannels, clutPoints, InputChannels);
- if (nTabSize == (size_t) -1) return FALSE;
+ if (nTabSize == (cmsUInt32Number) -1) return FALSE;
if (nTabSize > 0) {
// The 3D CLUT.
if (clut != NULL) {
@@ -2263,7 +2264,13 @@ cmsBool Type_LUT16_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io
if (PostMPE != NULL) {
if (!Write16bitTables(self ->ContextID, io, PostMPE)) return FALSE;
}
+ else {
+ for (i=0; i < OutputChannels; i++) {
+ if (!_cmsWriteUInt16Number(io, 0)) return FALSE;
+ if (!_cmsWriteUInt16Number(io, 0xffff)) return FALSE;
+ }
+ }
return TRUE;
@@ -2479,7 +2486,6 @@ void* Type_LUTA2B_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, c
cmsUInt32Number offsetM; // Offset to first "M" curve
cmsUInt32Number offsetC; // Offset to CLUT
cmsUInt32Number offsetA; // Offset to first "A" curve
- cmsStage* mpe;
cmsPipeline* NewLUT = NULL;
@@ -2501,37 +2507,35 @@ void* Type_LUTA2B_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, c
if (NewLUT == NULL) return NULL;
if (offsetA!= 0) {
- mpe = ReadSetOfCurves(self, io, BaseOffset + offsetA, inputChan);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetA, inputChan)))
+ goto Error;
}
if (offsetC != 0) {
- mpe = ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan)))
+ goto Error;
}
if (offsetM != 0) {
- mpe = ReadSetOfCurves(self, io, BaseOffset + offsetM, outputChan);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetM, outputChan)))
+ goto Error;
}
if (offsetMat != 0) {
- mpe = ReadMatrix(self, io, BaseOffset + offsetMat);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadMatrix(self, io, BaseOffset + offsetMat)))
+ goto Error;
}
if (offsetB != 0) {
- mpe = ReadSetOfCurves(self, io, BaseOffset + offsetB, outputChan);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetB, outputChan)))
+ goto Error;
}
*nItems = 1;
return NewLUT;
+Error:
+ cmsPipelineFree(NewLUT);
+ return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
@@ -2798,7 +2802,6 @@ void* Type_LUTB2A_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, c
cmsUInt32Number offsetM; // Offset to first "M" curve
cmsUInt32Number offsetC; // Offset to CLUT
cmsUInt32Number offsetA; // Offset to first "A" curve
- cmsStage* mpe;
cmsPipeline* NewLUT = NULL;
@@ -2821,37 +2824,35 @@ void* Type_LUTB2A_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, c
if (NewLUT == NULL) return NULL;
if (offsetB != 0) {
- mpe = ReadSetOfCurves(self, io, BaseOffset + offsetB, inputChan);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetB, inputChan)))
+ goto Error;
}
if (offsetMat != 0) {
- mpe = ReadMatrix(self, io, BaseOffset + offsetMat);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadMatrix(self, io, BaseOffset + offsetMat)))
+ goto Error;
}
if (offsetM != 0) {
- mpe = ReadSetOfCurves(self, io, BaseOffset + offsetM, inputChan);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetM, inputChan)))
+ goto Error;
}
if (offsetC != 0) {
- mpe = ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadCLUT(self, io, BaseOffset + offsetC, inputChan, outputChan)))
+ goto Error;
}
if (offsetA!= 0) {
- mpe = ReadSetOfCurves(self, io, BaseOffset + offsetA, outputChan);
- if (mpe == NULL) { cmsPipelineFree(NewLUT); return NULL; }
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, ReadSetOfCurves(self, io, BaseOffset + offsetA, outputChan)))
+ goto Error;
}
*nItems = 1;
return NewLUT;
+Error:
+ cmsPipelineFree(NewLUT);
+ return NULL;
cmsUNUSED_PARAMETER(SizeOfTag);
}
@@ -3287,7 +3288,7 @@ void *Type_ProfileSequenceDesc_Read(struct _cms_typehandler_struct* self, cmsIOH
SizeOfTag -= sizeof(cmsUInt32Number);
if (!_cmsReadUInt64Number(io, &sec ->attributes)) goto Error;
- if (SizeOfTag < sizeof(cmsUInt32Number)) goto Error;
+ if (SizeOfTag < sizeof(cmsUInt64Number)) goto Error;
SizeOfTag -= sizeof(cmsUInt64Number);
if (!_cmsReadUInt32Number(io, (cmsUInt32Number *)&sec ->technology)) goto Error;
@@ -4292,6 +4293,9 @@ void *Type_MPEclut_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* io,
if (!_cmsReadUInt16Number(io, &InputChans)) return NULL;
if (!_cmsReadUInt16Number(io, &OutputChans)) return NULL;
+ if (InputChans == 0) goto Error;
+ if (OutputChans == 0) goto Error;
+
if (io ->Read(io, Dimensions8, sizeof(cmsUInt8Number), 16) != 16)
goto Error;
@@ -4381,7 +4385,6 @@ cmsBool ReadMPEElem(struct _cms_typehandler_struct* self,
{
cmsStageSignature ElementSig;
cmsTagTypeHandler* TypeHandler;
- cmsStage *mpe = NULL;
cmsUInt32Number nItems;
cmsPipeline *NewLUT = (cmsPipeline *) Cargo;
@@ -4409,11 +4412,8 @@ cmsBool ReadMPEElem(struct _cms_typehandler_struct* self,
if (TypeHandler ->ReadPtr != NULL) {
// This is a real element which should be read and processed
- mpe = (cmsStage*) TypeHandler ->ReadPtr(self, io, &nItems, SizeOfTag);
- if (mpe == NULL) return FALSE;
-
- // All seems ok, insert element
- cmsPipelineInsertStage(NewLUT, cmsAT_END, mpe);
+ if (!cmsPipelineInsertStage(NewLUT, cmsAT_END, (cmsStage*) TypeHandler ->ReadPtr(self, io, &nItems, SizeOfTag)))
+ return FALSE;
}
return TRUE;
@@ -4479,10 +4479,10 @@ cmsBool Type_MPE_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, v
outputChan = cmsPipelineOutputChannels(Lut);
ElemCount = cmsPipelineStageCount(Lut);
- ElementOffsets = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number *));
+ ElementOffsets = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number));
if (ElementOffsets == NULL) goto Error;
- ElementSizes = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number *));
+ ElementSizes = (cmsUInt32Number *) _cmsCalloc(self ->ContextID, ElemCount, sizeof(cmsUInt32Number));
if (ElementSizes == NULL) goto Error;
// Write the head
@@ -4825,10 +4825,10 @@ typedef struct {
static
cmsBool AllocElem(cmsContext ContextID, _cmsDICelem* e, cmsUInt32Number Count)
{
- e->Offsets = (cmsUInt32Number *) _cmsCalloc(ContextID, Count, sizeof(cmsUInt32Number *));
+ e->Offsets = (cmsUInt32Number *) _cmsCalloc(ContextID, Count, sizeof(cmsUInt32Number));
if (e->Offsets == NULL) return FALSE;
- e->Sizes = (cmsUInt32Number *) _cmsCalloc(ContextID, Count, sizeof(cmsUInt32Number *));
+ e->Sizes = (cmsUInt32Number *) _cmsCalloc(ContextID, Count, sizeof(cmsUInt32Number));
if (e->Sizes == NULL) {
_cmsFree(ContextID, e -> Offsets);
@@ -4844,7 +4844,7 @@ static
void FreeElem(_cmsDICelem* e)
{
if (e ->Offsets != NULL) _cmsFree(e -> ContextID, e -> Offsets);
- if (e ->Sizes != NULL) _cmsFree(e -> ContextID, e ->Sizes);
+ if (e ->Sizes != NULL) _cmsFree(e -> ContextID, e -> Sizes);
e->Offsets = e ->Sizes = NULL;
}
@@ -5084,7 +5084,7 @@ void *Type_Dictionary_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* i
if (!_cmsReadUInt32Number(io, &Count)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
- // Get rec lenghth
+ // Get rec length
if (!_cmsReadUInt32Number(io, &Length)) return NULL;
SizeOfTag -= sizeof(cmsUInt32Number);
@@ -5118,14 +5118,22 @@ void *Type_Dictionary_Read(struct _cms_typehandler_struct* self, cmsIOHANDLER* i
if (!ReadOneMLUC(self, io, &a.DisplayValue, i, &DisplayValueMLU)) goto Error;
}
+ if (NameWCS == NULL || ValueWCS == NULL) {
+
+ cmsSignalError(self->ContextID, cmsERROR_CORRUPTION_DETECTED, "Bad dictionary Name/Value");
+ rc = FALSE;
+ }
+ else {
+
rc = cmsDictAddEntry(hDict, NameWCS, ValueWCS, DisplayNameMLU, DisplayValueMLU);
+ }
if (NameWCS != NULL) _cmsFree(self ->ContextID, NameWCS);
if (ValueWCS != NULL) _cmsFree(self ->ContextID, ValueWCS);
if (DisplayNameMLU != NULL) cmsMLUfree(DisplayNameMLU);
if (DisplayValueMLU != NULL) cmsMLUfree(DisplayValueMLU);
- if (!rc) return FALSE;
+ if (!rc) goto Error;
}
FreeArray(&a);
@@ -5277,14 +5285,14 @@ static _cmsTagTypeLinkedList SupportedTagTypes[] = {
#define DEFAULT_TAG_TYPE_COUNT (sizeof(SupportedTagTypes) / sizeof(_cmsTagTypeLinkedList))
// Both kind of plug-ins share same structure
-cmsBool _cmsRegisterTagTypePlugin(cmsPluginBase* Data)
+cmsBool _cmsRegisterTagTypePlugin(cmsContext id, cmsPluginBase* Data)
{
- return RegisterTypesPlugin(Data, SupportedTagTypes, DEFAULT_TAG_TYPE_COUNT);
+ return RegisterTypesPlugin(id, Data, SupportedTagTypes, DEFAULT_TAG_TYPE_COUNT);
}
-cmsBool _cmsRegisterMultiProcessElementPlugin(cmsPluginBase* Data)
+cmsBool _cmsRegisterMultiProcessElementPlugin(cmsContext id, cmsPluginBase* Data)
{
- return RegisterTypesPlugin(Data, SupportedMPEtypes, DEFAULT_MPE_TYPE_COUNT);
+ return RegisterTypesPlugin(id, Data, SupportedMPEtypes, DEFAULT_MPE_TYPE_COUNT);
}
@@ -5391,7 +5399,9 @@ static _cmsTagLinkedList SupportedTags[] = {
{ cmsSigScreeningTag, { 1, 1, { cmsSigScreeningType}, NULL }, &SupportedTags[59]},
{ cmsSigVcgtTag, { 1, 1, { cmsSigVcgtType}, NULL }, &SupportedTags[60]},
{ cmsSigMetaTag, { 1, 1, { cmsSigDictType}, NULL }, &SupportedTags[61]},
- { cmsSigProfileSequenceIdTag, { 1, 1, { cmsSigProfileSequenceIdType}, NULL}, NULL}
+ { cmsSigProfileSequenceIdTag, { 1, 1, { cmsSigProfileSequenceIdType}, NULL }, &SupportedTags[62]},
+ { cmsSigProfileDescriptionMLTag,{ 1, 1, { cmsSigMultiLocalizedUnicodeType}, NULL}, NULL}
+
};
@@ -5406,7 +5416,7 @@ static _cmsTagLinkedList SupportedTags[] = {
#define DEFAULT_TAG_COUNT (sizeof(SupportedTags) / sizeof(_cmsTagLinkedList))
-cmsBool _cmsRegisterTagPlugin(cmsPluginBase* Data)
+cmsBool _cmsRegisterTagPlugin(cmsContext id, cmsPluginBase* Data)
{
cmsPluginTag* Plugin = (cmsPluginTag*) Data;
_cmsTagLinkedList *pt, *Anterior;
@@ -5430,7 +5440,7 @@ cmsBool _cmsRegisterTagPlugin(cmsPluginBase* Data)
pt = pt ->Next;
}
- pt = (_cmsTagLinkedList*) _cmsPluginMalloc(sizeof(_cmsTagLinkedList));
+ pt = (_cmsTagLinkedList*) _cmsPluginMalloc(id, sizeof(_cmsTagLinkedList));
if (pt == NULL) return FALSE;
pt ->Signature = Plugin ->Signature;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
index ff46a0b3b69..699abcc93ca 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
@@ -208,9 +208,26 @@ cmsHPROFILE CMSEXPORT cmsCreateRGBProfileTHR(cmsContext ContextID,
if (TransferFunction) {
+ // Tries to minimize space. Thanks to Richard Hughes for this nice idea
if (!cmsWriteTag(hICC, cmsSigRedTRCTag, (void*) TransferFunction[0])) goto Error;
- if (!cmsWriteTag(hICC, cmsSigGreenTRCTag, (void*) TransferFunction[1])) goto Error;
- if (!cmsWriteTag(hICC, cmsSigBlueTRCTag, (void*) TransferFunction[2])) goto Error;
+
+ if (TransferFunction[1] == TransferFunction[0]) {
+
+ if (!cmsLinkTag (hICC, cmsSigGreenTRCTag, cmsSigRedTRCTag)) goto Error;
+
+ } else {
+
+ if (!cmsWriteTag(hICC, cmsSigGreenTRCTag, (void*) TransferFunction[1])) goto Error;
+ }
+
+ if (TransferFunction[2] == TransferFunction[0]) {
+
+ if (!cmsLinkTag (hICC, cmsSigBlueTRCTag, cmsSigRedTRCTag)) goto Error;
+
+ } else {
+
+ if (!cmsWriteTag(hICC, cmsSigBlueTRCTag, (void*) TransferFunction[2])) goto Error;
+ }
}
if (Primaries) {
@@ -303,7 +320,6 @@ cmsHPROFILE CMSEXPORT cmsCreateLinearizationDeviceLinkTHR(cmsContext ContextID,
{
cmsHPROFILE hICC;
cmsPipeline* Pipeline;
- cmsStage* Lin;
int nChannels;
hICC = cmsCreateProfilePlaceholder(ContextID);
@@ -327,10 +343,8 @@ cmsHPROFILE CMSEXPORT cmsCreateLinearizationDeviceLinkTHR(cmsContext ContextID,
// Copy tables to Pipeline
- Lin = cmsStageAllocToneCurves(ContextID, nChannels, TransferFunctions);
- if (Lin == NULL) goto Error;
-
- cmsPipelineInsertStage(Pipeline, cmsAT_BEGIN, Lin);
+ if (!cmsPipelineInsertStage(Pipeline, cmsAT_BEGIN, cmsStageAllocToneCurves(ContextID, nChannels, TransferFunctions)))
+ goto Error;
// Create tags
if (!SetTextTags(hICC, L"Linearization built-in")) goto Error;
@@ -344,6 +358,7 @@ cmsHPROFILE CMSEXPORT cmsCreateLinearizationDeviceLinkTHR(cmsContext ContextID,
return hICC;
Error:
+ cmsPipelineFree(Pipeline);
if (hICC)
cmsCloseProfile(hICC);
@@ -451,9 +466,10 @@ cmsHPROFILE CMSEXPORT cmsCreateInkLimitingDeviceLinkTHR(cmsContext ContextID,
if (!cmsStageSampleCLut16bit(CLUT, InkLimitingSampler, (void*) &Limit, 0)) goto Error;
- cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, nChannels));
- cmsPipelineInsertStage(LUT, cmsAT_END, CLUT);
- cmsPipelineInsertStage(LUT, cmsAT_END, _cmsStageAllocIdentityCurves(ContextID, nChannels));
+ if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, nChannels)) ||
+ !cmsPipelineInsertStage(LUT, cmsAT_END, CLUT) ||
+ !cmsPipelineInsertStage(LUT, cmsAT_END, _cmsStageAllocIdentityCurves(ContextID, nChannels)))
+ goto Error;
// Create tags
if (!SetTextTags(hICC, L"ink-limiting built-in")) goto Error;
@@ -504,7 +520,8 @@ cmsHPROFILE CMSEXPORT cmsCreateLab2ProfileTHR(cmsContext ContextID, const cmsCIE
LUT = cmsPipelineAlloc(ContextID, 3, 3);
if (LUT == NULL) goto Error;
- cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCLut(ContextID, 3));
+ if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCLut(ContextID, 3)))
+ goto Error;
if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT)) goto Error;
cmsPipelineFree(LUT);
@@ -550,7 +567,8 @@ cmsHPROFILE CMSEXPORT cmsCreateLab4ProfileTHR(cmsContext ContextID, const cmsCIE
LUT = cmsPipelineAlloc(ContextID, 3, 3);
if (LUT == NULL) goto Error;
- cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, 3));
+ if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, 3)))
+ goto Error;
if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT)) goto Error;
cmsPipelineFree(LUT);
@@ -595,7 +613,8 @@ cmsHPROFILE CMSEXPORT cmsCreateXYZProfileTHR(cmsContext ContextID)
LUT = cmsPipelineAlloc(ContextID, 3, 3);
if (LUT == NULL) goto Error;
- cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, 3));
+ if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, 3)))
+ goto Error;
if (!cmsWriteTag(hProfile, cmsSigAToB0Tag, LUT)) goto Error;
cmsPipelineFree(LUT);
@@ -734,81 +753,83 @@ int bchswSampler(register const cmsUInt16Number In[], register cmsUInt16Number O
// contrast, Saturation and white point displacement
cmsHPROFILE CMSEXPORT cmsCreateBCHSWabstractProfileTHR(cmsContext ContextID,
- int nLUTPoints,
- cmsFloat64Number Bright,
- cmsFloat64Number Contrast,
- cmsFloat64Number Hue,
- cmsFloat64Number Saturation,
- int TempSrc,
- int TempDest)
+ int nLUTPoints,
+ cmsFloat64Number Bright,
+ cmsFloat64Number Contrast,
+ cmsFloat64Number Hue,
+ cmsFloat64Number Saturation,
+ int TempSrc,
+ int TempDest)
{
- cmsHPROFILE hICC;
- cmsPipeline* Pipeline;
- BCHSWADJUSTS bchsw;
- cmsCIExyY WhitePnt;
- cmsStage* CLUT;
- cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
- int i;
+ cmsHPROFILE hICC;
+ cmsPipeline* Pipeline;
+ BCHSWADJUSTS bchsw;
+ cmsCIExyY WhitePnt;
+ cmsStage* CLUT;
+ cmsUInt32Number Dimensions[MAX_INPUT_DIMENSIONS];
+ int i;
+
+ bchsw.Brightness = Bright;
+ bchsw.Contrast = Contrast;
+ bchsw.Hue = Hue;
+ bchsw.Saturation = Saturation;
+
+ cmsWhitePointFromTemp(&WhitePnt, TempSrc );
+ cmsxyY2XYZ(&bchsw.WPsrc, &WhitePnt);
+
+ cmsWhitePointFromTemp(&WhitePnt, TempDest);
+ cmsxyY2XYZ(&bchsw.WPdest, &WhitePnt);
+
+ hICC = cmsCreateProfilePlaceholder(ContextID);
+ if (!hICC) // can't allocate
+ return NULL;
- bchsw.Brightness = Bright;
- bchsw.Contrast = Contrast;
- bchsw.Hue = Hue;
- bchsw.Saturation = Saturation;
+ cmsSetDeviceClass(hICC, cmsSigAbstractClass);
+ cmsSetColorSpace(hICC, cmsSigLabData);
+ cmsSetPCS(hICC, cmsSigLabData);
- cmsWhitePointFromTemp(&WhitePnt, TempSrc );
- cmsxyY2XYZ(&bchsw.WPsrc, &WhitePnt);
+ cmsSetHeaderRenderingIntent(hICC, INTENT_PERCEPTUAL);
- cmsWhitePointFromTemp(&WhitePnt, TempDest);
- cmsxyY2XYZ(&bchsw.WPdest, &WhitePnt);
+ // Creates a Pipeline with 3D grid only
+ Pipeline = cmsPipelineAlloc(ContextID, 3, 3);
+ if (Pipeline == NULL) {
+ cmsCloseProfile(hICC);
+ return NULL;
+ }
- hICC = cmsCreateProfilePlaceholder(ContextID);
- if (!hICC) // can't allocate
- return NULL;
+ for (i=0; i < MAX_INPUT_DIMENSIONS; i++) Dimensions[i] = nLUTPoints;
+ CLUT = cmsStageAllocCLut16bitGranular(ContextID, Dimensions, 3, 3, NULL);
+ if (CLUT == NULL) return NULL;
- cmsSetDeviceClass(hICC, cmsSigAbstractClass);
- cmsSetColorSpace(hICC, cmsSigLabData);
- cmsSetPCS(hICC, cmsSigLabData);
+ if (!cmsStageSampleCLut16bit(CLUT, bchswSampler, (void*) &bchsw, 0)) {
- cmsSetHeaderRenderingIntent(hICC, INTENT_PERCEPTUAL);
+ // Shouldn't reach here
+ goto Error;
+ }
+ if (!cmsPipelineInsertStage(Pipeline, cmsAT_END, CLUT)) {
+ goto Error;
+ }
- // Creates a Pipeline with 3D grid only
- Pipeline = cmsPipelineAlloc(ContextID, 3, 3);
- if (Pipeline == NULL) {
- cmsCloseProfile(hICC);
- return NULL;
- }
+ // Create tags
+ if (!SetTextTags(hICC, L"BCHS built-in")) return NULL;
- for (i=0; i < MAX_INPUT_DIMENSIONS; i++) Dimensions[i] = nLUTPoints;
- CLUT = cmsStageAllocCLut16bitGranular(ContextID, Dimensions, 3, 3, NULL);
- if (CLUT == NULL) return NULL;
+ cmsWriteTag(hICC, cmsSigMediaWhitePointTag, (void*) cmsD50_XYZ());
+ cmsWriteTag(hICC, cmsSigAToB0Tag, (void*) Pipeline);
- if (!cmsStageSampleCLut16bit(CLUT, bchswSampler, (void*) &bchsw, 0)) {
+ // Pipeline is already on virtual profile
+ cmsPipelineFree(Pipeline);
- // Shouldn't reach here
- cmsPipelineFree(Pipeline);
- cmsCloseProfile(hICC);
- return NULL;
- }
+ // Ok, done
+ return hICC;
- cmsPipelineInsertStage(Pipeline, cmsAT_END, CLUT);
-
- // Create tags
-
- if (!SetTextTags(hICC, L"BCHS built-in")) return NULL;
-
- cmsWriteTag(hICC, cmsSigMediaWhitePointTag, (void*) cmsD50_XYZ());
-
- cmsWriteTag(hICC, cmsSigAToB0Tag, (void*) Pipeline);
-
- // Pipeline is already on virtual profile
- cmsPipelineFree(Pipeline);
-
- // Ok, done
- return hICC;
+Error:
+ cmsPipelineFree(Pipeline);
+ cmsCloseProfile(hICC);
+ return NULL;
}
@@ -856,7 +877,8 @@ cmsHPROFILE CMSEXPORT cmsCreateNULLProfileTHR(cmsContext ContextID)
PostLin = cmsStageAllocToneCurves(ContextID, 1, &EmptyTab);
cmsFreeToneCurve(EmptyTab);
- cmsPipelineInsertStage(LUT, cmsAT_END, PostLin);
+ if (!cmsPipelineInsertStage(LUT, cmsAT_END, PostLin))
+ goto Error;
if (!cmsWriteTag(hProfile, cmsSigBToA0Tag, (void*) LUT)) goto Error;
if (!cmsWriteTag(hProfile, cmsSigMediaWhitePointTag, cmsD50_XYZ())) goto Error;
@@ -999,6 +1021,7 @@ static const cmsAllowedLUT AllowedLUTTypes[] = {
{ FALSE, 0, cmsSigLut16Type, 4, { cmsSigMatrixElemType, cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType}},
{ FALSE, 0, cmsSigLut16Type, 3, { cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType}},
+ { FALSE, 0, cmsSigLut16Type, 2, { cmsSigCurveSetElemType, cmsSigCLutElemType}},
{ TRUE , 0, cmsSigLutAtoBType, 1, { cmsSigCurveSetElemType }},
{ TRUE , cmsSigAToB0Tag, cmsSigLutAtoBType, 3, { cmsSigCurveSetElemType, cmsSigMatrixElemType, cmsSigCurveSetElemType } },
{ TRUE , cmsSigAToB0Tag, cmsSigLutAtoBType, 3, { cmsSigCurveSetElemType, cmsSigCLutElemType, cmsSigCurveSetElemType } },
@@ -1059,6 +1082,7 @@ cmsHPROFILE CMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, cmsFloat
cmsContext ContextID = cmsGetTransformContextID(hTransform);
const cmsAllowedLUT* AllowedLUT;
cmsTagSignature DestinationTag;
+ cmsProfileClassSignature deviceClass;
_cmsAssert(hTransform != NULL);
@@ -1080,13 +1104,15 @@ cmsHPROFILE CMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, cmsFloat
// Time to fix the Lab2/Lab4 issue.
if ((xform ->EntryColorSpace == cmsSigLabData) && (Version < 4.0)) {
- cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocLabV2ToV4curves(ContextID));
+ if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocLabV2ToV4curves(ContextID)))
+ goto Error;
}
// On the output side too
if ((xform ->ExitColorSpace) == cmsSigLabData && (Version < 4.0)) {
- cmsPipelineInsertStage(LUT, cmsAT_END, _cmsStageAllocLabV4ToV2(ContextID));
+ if (!cmsPipelineInsertStage(LUT, cmsAT_END, _cmsStageAllocLabV4ToV2(ContextID)))
+ goto Error;
}
@@ -1108,8 +1134,9 @@ cmsHPROFILE CMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, cmsFloat
FrmIn = COLORSPACE_SH(ColorSpaceBitsIn) | CHANNELS_SH(ChansIn)|BYTES_SH(2);
FrmOut = COLORSPACE_SH(ColorSpaceBitsOut) | CHANNELS_SH(ChansOut)|BYTES_SH(2);
+ deviceClass = cmsGetDeviceClass(hProfile);
- if (cmsGetDeviceClass(hProfile) == cmsSigOutputClass)
+ if (deviceClass == cmsSigOutputClass)
DestinationTag = cmsSigBToA0Tag;
else
DestinationTag = cmsSigAToB0Tag;
@@ -1136,10 +1163,12 @@ cmsHPROFILE CMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, cmsFloat
// Put identity curves if needed
if (cmsPipelineGetPtrToFirstStage(LUT) ->Type != cmsSigCurveSetElemType)
- cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, ChansIn));
+ if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, ChansIn)))
+ goto Error;
if (cmsPipelineGetPtrToLastStage(LUT) ->Type != cmsSigCurveSetElemType)
- cmsPipelineInsertStage(LUT, cmsAT_END, _cmsStageAllocIdentityCurves(ContextID, ChansOut));
+ if (!cmsPipelineInsertStage(LUT, cmsAT_END, _cmsStageAllocIdentityCurves(ContextID, ChansOut)))
+ goto Error;
AllowedLUT = FindCombination(LUT, Version >= 4.0, DestinationTag);
}
@@ -1168,10 +1197,22 @@ cmsHPROFILE CMSEXPORT cmsTransform2DeviceLink(cmsHTRANSFORM hTransform, cmsFloat
if (!cmsWriteTag(hProfile, cmsSigColorantTableOutTag, xform->OutputColorant)) goto Error;
}
- if (xform ->Sequence != NULL) {
+ if ((deviceClass == cmsSigLinkClass) && (xform ->Sequence != NULL)) {
if (!_cmsWriteProfileSequence(hProfile, xform ->Sequence)) goto Error;
}
+ // Set the white point
+ if (deviceClass == cmsSigInputClass) {
+ if (!cmsWriteTag(hProfile, cmsSigMediaWhitePointTag, &xform ->EntryWhitePoint)) goto Error;
+ }
+ else {
+ if (!cmsWriteTag(hProfile, cmsSigMediaWhitePointTag, &xform ->ExitWhitePoint)) goto Error;
+ }
+
+
+ // Per 7.2.15 in spec 4.3
+ cmsSetHeaderRenderingIntent(hProfile, xform ->RenderingIntent);
+
cmsPipelineFree(LUT);
return hProfile;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
index 2a626c66b74..71fb7650836 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
@@ -30,7 +30,7 @@
//---------------------------------------------------------------------------------
//
// Little Color Management System
-// Copyright (c) 1998-2010 Marti Maria Saguer
+// Copyright (c) 1998-2012 Marti Maria Saguer
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -76,48 +76,48 @@ const cmsCIExyY* CMSEXPORT cmsD50_xyY(void)
// Obtains WhitePoint from Temperature
cmsBool CMSEXPORT cmsWhitePointFromTemp(cmsCIExyY* WhitePoint, cmsFloat64Number TempK)
{
- cmsFloat64Number x, y;
- cmsFloat64Number T, T2, T3;
- // cmsFloat64Number M1, M2;
+ cmsFloat64Number x, y;
+ cmsFloat64Number T, T2, T3;
+ // cmsFloat64Number M1, M2;
- _cmsAssert(WhitePoint != NULL);
+ _cmsAssert(WhitePoint != NULL);
- T = TempK;
- T2 = T*T; // Square
- T3 = T2*T; // Cube
+ T = TempK;
+ T2 = T*T; // Square
+ T3 = T2*T; // Cube
- // For correlated color temperature (T) between 4000K and 7000K:
+ // For correlated color temperature (T) between 4000K and 7000K:
- if (T >= 4000. && T <= 7000.)
- {
- x = -4.6070*(1E9/T3) + 2.9678*(1E6/T2) + 0.09911*(1E3/T) + 0.244063;
- }
- else
- // or for correlated color temperature (T) between 7000K and 25000K:
+ if (T >= 4000. && T <= 7000.)
+ {
+ x = -4.6070*(1E9/T3) + 2.9678*(1E6/T2) + 0.09911*(1E3/T) + 0.244063;
+ }
+ else
+ // or for correlated color temperature (T) between 7000K and 25000K:
- if (T > 7000.0 && T <= 25000.0)
- {
- x = -2.0064*(1E9/T3) + 1.9018*(1E6/T2) + 0.24748*(1E3/T) + 0.237040;
- }
- else {
- cmsSignalError(0, cmsERROR_RANGE, "cmsWhitePointFromTemp: invalid temp");
- return FALSE;
- }
+ if (T > 7000.0 && T <= 25000.0)
+ {
+ x = -2.0064*(1E9/T3) + 1.9018*(1E6/T2) + 0.24748*(1E3/T) + 0.237040;
+ }
+ else {
+ cmsSignalError(0, cmsERROR_RANGE, "cmsWhitePointFromTemp: invalid temp");
+ return FALSE;
+ }
- // Obtain y(x)
+ // Obtain y(x)
- y = -3.000*(x*x) + 2.870*x - 0.275;
+ y = -3.000*(x*x) + 2.870*x - 0.275;
- // wave factors (not used, but here for futures extensions)
+ // wave factors (not used, but here for futures extensions)
- // M1 = (-1.3515 - 1.7703*x + 5.9114 *y)/(0.0241 + 0.2562*x - 0.7341*y);
- // M2 = (0.0300 - 31.4424*x + 30.0717*y)/(0.0241 + 0.2562*x - 0.7341*y);
+ // M1 = (-1.3515 - 1.7703*x + 5.9114 *y)/(0.0241 + 0.2562*x - 0.7341*y);
+ // M2 = (0.0300 - 31.4424*x + 30.0717*y)/(0.0241 + 0.2562*x - 0.7341*y);
- WhitePoint -> x = x;
- WhitePoint -> y = y;
- WhitePoint -> Y = 1.0;
+ WhitePoint -> x = x;
+ WhitePoint -> y = y;
+ WhitePoint -> Y = 1.0;
- return TRUE;
+ return TRUE;
}
@@ -266,7 +266,7 @@ cmsBool _cmsAdaptationMatrix(cmsMAT3* r, const cmsMAT3* ConeMatrix, const cmsCI
{{ 0.8951, 0.2664, -0.1614 }},
{{ -0.7502, 1.7135, 0.0367 }},
{{ 0.0389, -0.0685, 1.0296 }}
- }};
+ }};
if (ConeMatrix == NULL)
ConeMatrix = &LamRigg;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
index 925a70374d3..879056f41ce 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
@@ -396,7 +396,7 @@ typedef struct _cmsTransformCollection_st {
static _cmsTransformCollection* TransformCollection = NULL;
// Register new ways to transform
-cmsBool _cmsRegisterTransformPlugin(cmsPluginBase* Data)
+cmsBool _cmsRegisterTransformPlugin(cmsContext id, cmsPluginBase* Data)
{
cmsPluginTransform* Plugin = (cmsPluginTransform*) Data;
_cmsTransformCollection* fl;
@@ -412,7 +412,7 @@ cmsBool _cmsRegisterTransformPlugin(cmsPluginBase* Data)
if (Plugin ->Factory == NULL) return FALSE;
- fl = (_cmsTransformCollection*) _cmsPluginMalloc(sizeof(_cmsTransformCollection));
+ fl = (_cmsTransformCollection*) _cmsPluginMalloc(id, sizeof(_cmsTransformCollection));
if (fl == NULL) return FALSE;
// Copy the parameters
@@ -651,6 +651,22 @@ cmsBool IsProperColorSpace(cmsColorSpaceSignature Check, cmsUInt32Number dwForm
// ----------------------------------------------------------------------------------------------------------------
+static
+void SetWhitePoint(cmsCIEXYZ* wtPt, const cmsCIEXYZ* src)
+{
+ if (src == NULL) {
+ wtPt ->X = cmsD50X;
+ wtPt ->Y = cmsD50Y;
+ wtPt ->Z = cmsD50Z;
+ }
+ else {
+ wtPt ->X = src->X;
+ wtPt ->Y = src->Y;
+ wtPt ->Z = src->Z;
+ }
+
+}
+
// New to lcms 2.0 -- have all parameters available.
cmsHTRANSFORM CMSEXPORT cmsCreateExtendedTransform(cmsContext ContextID,
cmsUInt32Number nProfiles, cmsHPROFILE hProfiles[],
@@ -664,7 +680,6 @@ cmsHTRANSFORM CMSEXPORT cmsCreateExtendedTransform(cmsContext ContextID,
cmsUInt32Number dwFlags)
{
_cmsTRANSFORM* xform;
- cmsBool FloatTransform;
cmsColorSpaceSignature EntryColorSpace;
cmsColorSpaceSignature ExitColorSpace;
cmsPipeline* Lut;
@@ -681,9 +696,7 @@ cmsHTRANSFORM CMSEXPORT cmsCreateExtendedTransform(cmsContext ContextID,
if (hGamutProfile == NULL) dwFlags &= ~cmsFLAGS_GAMUTCHECK;
}
- // On floating point transforms, inhibit optimizations
- FloatTransform = (_cmsFormatterIsFloat(InputFormat) && _cmsFormatterIsFloat(OutputFormat));
-
+ // On floating point transforms, inhibit cache
if (_cmsFormatterIsFloat(InputFormat) || _cmsFormatterIsFloat(OutputFormat))
dwFlags |= cmsFLAGS_NOCACHE;
@@ -730,6 +743,10 @@ cmsHTRANSFORM CMSEXPORT cmsCreateExtendedTransform(cmsContext ContextID,
xform ->ExitColorSpace = ExitColorSpace;
xform ->RenderingIntent = Intents[nProfiles-1];
+ // Take white points
+ SetWhitePoint(&xform->EntryWhitePoint, (cmsCIEXYZ*) cmsReadTag(hProfiles[0], cmsSigMediaWhitePointTag));
+ SetWhitePoint(&xform->ExitWhitePoint, (cmsCIEXYZ*) cmsReadTag(hProfiles[nProfiles-1], cmsSigMediaWhitePointTag));
+
// Create a gamut check LUT if requested
if (hGamutProfile != NULL && (dwFlags & cmsFLAGS_GAMUTCHECK))
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
index aee6cbadb96..c6c35b185f6 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
@@ -30,7 +30,7 @@
//---------------------------------------------------------------------------------
//
// Little Color Management System
-// Copyright (c) 1998-2011 Marti Maria Saguer
+// Copyright (c) 1998-2013 Marti Maria Saguer
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
@@ -52,7 +52,7 @@
//
//---------------------------------------------------------------------------------
//
-// Version 2.4
+// Version 2.5
//
#ifndef _lcms2_H
@@ -101,7 +101,7 @@ extern "C" {
#endif
// Version/release
-#define LCMS_VERSION 2040
+#define LCMS_VERSION 2050
// I will give the chance of redefining basic types for compilers that are not fully C99 compliant
#ifndef CMS_BASIC_TYPES_ALREADY_DEFINED
@@ -367,6 +367,7 @@ typedef enum {
cmsSigPreview1Tag = 0x70726531, // 'pre1'
cmsSigPreview2Tag = 0x70726532, // 'pre2'
cmsSigProfileDescriptionTag = 0x64657363, // 'desc'
+ cmsSigProfileDescriptionMLTag = 0x6473636d, // 'dscm'
cmsSigProfileSequenceDescTag = 0x70736571, // 'pseq'
cmsSigProfileSequenceIdTag = 0x70736964, // 'psid'
cmsSigPs2CRD0Tag = 0x70736430, // 'psd0'
@@ -1014,6 +1015,7 @@ CMSAPI long int CMSEXPORT cmsfilelength(FILE* f);
// Plug-In registering ---------------------------------------------------------------------------------------------------
CMSAPI cmsBool CMSEXPORT cmsPlugin(void* Plugin);
+CMSAPI cmsBool CMSEXPORT cmsPluginTHR(cmsContext ContextID, void* Plugin);
CMSAPI void CMSEXPORT cmsUnregisterPlugins(void);
// Error logging ----------------------------------------------------------------------------------------------------------
@@ -1190,7 +1192,7 @@ CMSAPI cmsBool CMSEXPORT cmsPipelineSetSaveAs8bitsFlag(cmsPipeline* lu
// Where to place/locate the stages in the pipeline chain
typedef enum { cmsAT_BEGIN, cmsAT_END } cmsStageLoc;
-CMSAPI void CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe);
+CMSAPI int CMSEXPORT cmsPipelineInsertStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage* mpe);
CMSAPI void CMSEXPORT cmsPipelineUnlinkStage(cmsPipeline* lut, cmsStageLoc loc, cmsStage** mpe);
// This function is quite useful to analyze the structure of a Pipeline and retrieve the Stage elements
@@ -1274,6 +1276,13 @@ CMSAPI cmsBool CMSEXPORT cmsMLUgetTranslation(const cmsMLU* mlu,
const char LanguageCode[3], const char CountryCode[3],
char ObtainedLanguage[3], char ObtainedCountry[3]);
+CMSAPI cmsUInt32Number CMSEXPORT cmsMLUtranslationsCount(const cmsMLU* mlu);
+
+CMSAPI cmsBool CMSEXPORT cmsMLUtranslationsCodes(const cmsMLU* mlu,
+ cmsUInt32Number idx,
+ char LanguageCode[3],
+ char CountryCode[3]);
+
// Undercolorremoval & black generation -------------------------------------------------------------------------------------
typedef struct {
@@ -1424,6 +1433,7 @@ CMSAPI cmsUInt32Number CMSEXPORT cmsGetHeaderRenderingIntent(cmsHPROFILE hProf
CMSAPI void CMSEXPORT cmsSetHeaderFlags(cmsHPROFILE hProfile, cmsUInt32Number Flags);
CMSAPI cmsUInt32Number CMSEXPORT cmsGetHeaderManufacturer(cmsHPROFILE hProfile);
CMSAPI void CMSEXPORT cmsSetHeaderManufacturer(cmsHPROFILE hProfile, cmsUInt32Number manufacturer);
+CMSAPI cmsUInt32Number CMSEXPORT cmsGetHeaderCreator(cmsHPROFILE hProfile);
CMSAPI cmsUInt32Number CMSEXPORT cmsGetHeaderModel(cmsHPROFILE hProfile);
CMSAPI void CMSEXPORT cmsSetHeaderModel(cmsHPROFILE hProfile, cmsUInt32Number model);
CMSAPI void CMSEXPORT cmsSetHeaderAttributes(cmsHPROFILE hProfile, cmsUInt64Number Flags);
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
index 9477aa33cfc..6fbbb95b244 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
@@ -27,7 +27,7 @@
// However, the following notice accompanied the original version of this
// file:
//
-//---------------------------------------------------------------------------------
+
//
// Little Color Management System
// Copyright (c) 1998-2011 Marti Maria Saguer
@@ -196,7 +196,7 @@ cmsINLINE cmsUInt16Number _cmsQuickSaturateWord(cmsFloat64Number d)
// Plug-In registering ---------------------------------------------------------------
// Specialized function for plug-in memory management. No pairing free() since whole pool is freed at once.
-void* _cmsPluginMalloc(cmsUInt32Number size);
+void* _cmsPluginMalloc(cmsContext ContextID, cmsUInt32Number size);
// Memory management
cmsBool _cmsRegisterMemHandlerPlugin(cmsPluginBase* Plugin);
@@ -205,28 +205,28 @@ cmsBool _cmsRegisterMemHandlerPlugin(cmsPluginBase* Plugin);
cmsBool _cmsRegisterInterpPlugin(cmsPluginBase* Plugin);
// Parametric curves
-cmsBool _cmsRegisterParametricCurvesPlugin(cmsPluginBase* Plugin);
+cmsBool _cmsRegisterParametricCurvesPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
// Formatters management
-cmsBool _cmsRegisterFormattersPlugin(cmsPluginBase* Plugin);
+cmsBool _cmsRegisterFormattersPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
// Tag type management
-cmsBool _cmsRegisterTagTypePlugin(cmsPluginBase* Plugin);
+cmsBool _cmsRegisterTagTypePlugin(cmsContext ContextID, cmsPluginBase* Plugin);
// Tag management
-cmsBool _cmsRegisterTagPlugin(cmsPluginBase* Plugin);
+cmsBool _cmsRegisterTagPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
// Intent management
-cmsBool _cmsRegisterRenderingIntentPlugin(cmsPluginBase* Plugin);
+cmsBool _cmsRegisterRenderingIntentPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
// Multi Process elements
-cmsBool _cmsRegisterMultiProcessElementPlugin(cmsPluginBase* Plugin);
+cmsBool _cmsRegisterMultiProcessElementPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
// Optimization
-cmsBool _cmsRegisterOptimizationPlugin(cmsPluginBase* Plugin);
+cmsBool _cmsRegisterOptimizationPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
// Transform
-cmsBool _cmsRegisterTransformPlugin(cmsPluginBase* Plugin);
+cmsBool _cmsRegisterTransformPlugin(cmsContext ContextID, cmsPluginBase* Plugin);
// ---------------------------------------------------------------------------------------------------------
@@ -263,7 +263,7 @@ typedef struct {
cmsUInt16Number Country;
cmsUInt32Number StrW; // Offset to current unicode string
- cmsUInt32Number Len; // Lenght in bytes
+ cmsUInt32Number Len; // Length in bytes
} _cmsMLUentry;
@@ -330,9 +330,11 @@ typedef struct _cms_iccprofile_struct {
cmsColorSpaceSignature ColorSpace;
cmsColorSpaceSignature PCS;
cmsUInt32Number RenderingIntent;
+
cmsUInt32Number flags;
cmsUInt32Number manufacturer, model;
cmsUInt64Number attributes;
+ cmsUInt32Number creator;
cmsProfileID ProfileID;
@@ -585,6 +587,10 @@ typedef struct _cmstransform_struct {
cmsColorSpaceSignature EntryColorSpace;
cmsColorSpaceSignature ExitColorSpace;
+ // White points (informative only)
+ cmsCIEXYZ EntryWhitePoint;
+ cmsCIEXYZ ExitWhitePoint;
+
// Profiles used to create the transform
cmsSEQ* Sequence;
diff --git a/jdk/src/share/native/sun/management/Flag.c b/jdk/src/share/native/sun/management/Flag.c
index 82aaaa77578..7a45e8d62f6 100644
--- a/jdk/src/share/native/sun/management/Flag.c
+++ b/jdk/src/share/native/sun/management/Flag.c
@@ -97,12 +97,12 @@ Java_sun_management_Flag_getFlags
return 0;
}
- if (count == 0) {
+ if (count <= 0) {
JNU_ThrowIllegalArgumentException(env, 0);
return 0;
}
- gsize = count * sizeof(jmmVMGlobal);
+ gsize = (size_t)count * sizeof(jmmVMGlobal);
globals = (jmmVMGlobal*) malloc(gsize);
if (globals == NULL) {
JNU_ThrowOutOfMemoryError(env, 0);
diff --git a/jdk/src/share/native/sun/management/GcInfoBuilder.c b/jdk/src/share/native/sun/management/GcInfoBuilder.c
index f03f0b1e340..672cc6a7782 100644
--- a/jdk/src/share/native/sun/management/GcInfoBuilder.c
+++ b/jdk/src/share/native/sun/management/GcInfoBuilder.c
@@ -59,12 +59,12 @@ JNIEXPORT void JNICALL Java_sun_management_GcInfoBuilder_fillGcAttributeInfo
return;
}
- if (num_attributes == 0) {
+ if (num_attributes <= 0) {
JNU_ThrowIllegalArgumentException(env, "Invalid num_attributes");
return;
}
- ext_att_info = (jmmExtAttributeInfo*) malloc(num_attributes *
+ ext_att_info = (jmmExtAttributeInfo*) malloc((size_t)num_attributes *
sizeof(jmmExtAttributeInfo));
if (ext_att_info == NULL) {
JNU_ThrowOutOfMemoryError(env, 0);
@@ -78,7 +78,7 @@ JNIEXPORT void JNICALL Java_sun_management_GcInfoBuilder_fillGcAttributeInfo
return;
}
- nativeTypes = (jchar*) malloc(num_attributes * sizeof(jchar));
+ nativeTypes = (jchar*) malloc((size_t)num_attributes * sizeof(jchar));
if (nativeTypes == NULL) {
free(ext_att_info);
JNU_ThrowOutOfMemoryError(env, 0);
@@ -188,11 +188,16 @@ JNIEXPORT jobject JNICALL Java_sun_management_GcInfoBuilder_getLastGcInfo0
return 0;
}
+ if (ext_att_count <= 0) {
+ JNU_ThrowIllegalArgumentException(env, "Invalid ext_att_count");
+ return 0;
+ }
+
gc_stat.usage_before_gc = usageBeforeGC;
gc_stat.usage_after_gc = usageAfterGC;
gc_stat.gc_ext_attribute_values_size = ext_att_count;
if (ext_att_count > 0) {
- gc_stat.gc_ext_attribute_values = (jvalue*) malloc(ext_att_count *
+ gc_stat.gc_ext_attribute_values = (jvalue*) malloc((size_t)ext_att_count *
sizeof(jvalue));
if (gc_stat.gc_ext_attribute_values == NULL) {
JNU_ThrowOutOfMemoryError(env, 0);
@@ -212,7 +217,7 @@ JNIEXPORT jobject JNICALL Java_sun_management_GcInfoBuilder_getLastGcInfo0
}
// convert the ext_att_types to native types
- nativeTypes = (jchar*) malloc(ext_att_count * sizeof(jchar));
+ nativeTypes = (jchar*) malloc((size_t)ext_att_count * sizeof(jchar));
if (nativeTypes == NULL) {
if (gc_stat.gc_ext_attribute_values != NULL) {
free(gc_stat.gc_ext_attribute_values);
diff --git a/jdk/src/solaris/classes/java/net/PlainDatagramSocketImpl.java b/jdk/src/solaris/classes/java/net/PlainDatagramSocketImpl.java
index 20bc6fbc394..6a29a9b062c 100644
--- a/jdk/src/solaris/classes/java/net/PlainDatagramSocketImpl.java
+++ b/jdk/src/solaris/classes/java/net/PlainDatagramSocketImpl.java
@@ -25,6 +25,11 @@
package java.net;
import java.io.IOException;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Collections;
+import jdk.net.*;
+import static sun.net.ExtendedOptionsImpl.*;
/*
* On Unix systems we simply delegate to native methods.
@@ -38,6 +43,43 @@ class PlainDatagramSocketImpl extends AbstractPlainDatagramSocketImpl
init();
}
+ protected void setOption(SocketOption name, T value) throws IOException {
+ if (!name.equals(ExtendedSocketOptions.SO_FLOW_SLA)) {
+ super.setOption(name, value);
+ } else {
+ if (isClosed()) {
+ throw new SocketException("Socket closed");
+ }
+ checkSetOptionPermission(name);
+ checkValueType(value, SocketFlow.class);
+ setFlowOption(getFileDescriptor(), (SocketFlow)value);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected T getOption(SocketOption name) throws IOException {
+ if (!name.equals(ExtendedSocketOptions.SO_FLOW_SLA)) {
+ return super.getOption(name);
+ }
+ if (isClosed()) {
+ throw new SocketException("Socket closed");
+ }
+ checkGetOptionPermission(name);
+ SocketFlow flow = SocketFlow.create();
+ getFlowOption(getFileDescriptor(), flow);
+ return (T)flow;
+ }
+
+ protected Set> supportedOptions() {
+ HashSet> options = new HashSet<>(
+ super.supportedOptions());
+
+ if (flowSupported()) {
+ options.add(ExtendedSocketOptions.SO_FLOW_SLA);
+ }
+ return options;
+ }
+
protected synchronized native void bind0(int lport, InetAddress laddr)
throws SocketException;
diff --git a/jdk/src/solaris/classes/java/net/PlainSocketImpl.java b/jdk/src/solaris/classes/java/net/PlainSocketImpl.java
index 4846689a3e2..735f5d3581e 100644
--- a/jdk/src/solaris/classes/java/net/PlainSocketImpl.java
+++ b/jdk/src/solaris/classes/java/net/PlainSocketImpl.java
@@ -26,6 +26,12 @@ package java.net;
import java.io.IOException;
import java.io.FileDescriptor;
+import java.util.Set;
+import java.util.HashSet;
+import java.util.Collections;
+import jdk.net.*;
+
+import static sun.net.ExtendedOptionsImpl.*;
/*
* On Unix systems we simply delegate to native methods.
@@ -51,6 +57,43 @@ class PlainSocketImpl extends AbstractPlainSocketImpl
this.fd = fd;
}
+ protected void setOption(SocketOption name, T value) throws IOException {
+ if (!name.equals(ExtendedSocketOptions.SO_FLOW_SLA)) {
+ super.setOption(name, value);
+ } else {
+ if (isClosedOrPending()) {
+ throw new SocketException("Socket closed");
+ }
+ checkSetOptionPermission(name);
+ checkValueType(value, SocketFlow.class);
+ setFlowOption(getFileDescriptor(), (SocketFlow)value);
+ }
+ }
+
+ @SuppressWarnings("unchecked")
+ protected T getOption(SocketOption name) throws IOException {
+ if (!name.equals(ExtendedSocketOptions.SO_FLOW_SLA)) {
+ return super.getOption(name);
+ }
+ if (isClosedOrPending()) {
+ throw new SocketException("Socket closed");
+ }
+ checkGetOptionPermission(name);
+ SocketFlow flow = SocketFlow.create();
+ getFlowOption(getFileDescriptor(), flow);
+ return (T)flow;
+ }
+
+ protected Set> supportedOptions() {
+ HashSet> options = new HashSet<>(
+ super.supportedOptions());
+
+ if (getSocket() != null && flowSupported()) {
+ options.add(ExtendedSocketOptions.SO_FLOW_SLA);
+ }
+ return options;
+ }
+
native void socketCreate(boolean isServer) throws IOException;
native void socketConnect(InetAddress address, int port, int timeout)
@@ -77,5 +120,4 @@ class PlainSocketImpl extends AbstractPlainSocketImpl
native int socketGetOption(int opt, Object iaContainerObj) throws SocketException;
native void socketSendUrgentData(int data) throws IOException;
-
}
diff --git a/jdk/src/solaris/classes/sun/awt/X11/XClipboard.java b/jdk/src/solaris/classes/sun/awt/X11/XClipboard.java
index e0f47f50284..7068b665ac5 100644
--- a/jdk/src/solaris/classes/sun/awt/X11/XClipboard.java
+++ b/jdk/src/solaris/classes/sun/awt/X11/XClipboard.java
@@ -86,7 +86,7 @@ public final class XClipboard extends SunClipboard implements OwnershipListener
protected synchronized void setContentsNative(Transferable contents) {
SortedMap formatMap =
DataTransferer.getInstance().getFormatsForTransferable
- (contents, DataTransferer.adaptFlavorMap(flavorMap));
+ (contents, DataTransferer.adaptFlavorMap(getDefaultFlavorTable()));
long[] formats = DataTransferer.keysToLongArray(formatMap);
if (!selection.setOwner(contents, formatMap, formats,
@@ -125,7 +125,7 @@ public final class XClipboard extends SunClipboard implements OwnershipListener
private void checkChangeHere(Transferable contents) {
if (areFlavorListenersRegistered()) {
checkChange(DataTransferer.getInstance().
- getFormatsForTransferableAsArray(contents, flavorMap));
+ getFormatsForTransferableAsArray(contents, getDefaultFlavorTable()));
}
}
diff --git a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java
index 86f704ec20e..c10a1d9522c 100644
--- a/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java
+++ b/jdk/src/solaris/classes/sun/awt/X11/XToolkit.java
@@ -50,7 +50,8 @@ import sun.awt.*;
import sun.awt.datatransfer.DataTransferer;
import sun.font.FontConfigManager;
import sun.java2d.SunGraphicsEnvironment;
-import sun.misc.PerformanceLogger;
+import sun.misc.*;
+import sun.misc.ThreadGroupUtils;
import sun.print.PrintJob2D;
import sun.security.action.GetPropertyAction;
import sun.security.action.GetBooleanAction;
@@ -254,33 +255,25 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
} finally {
awtUnlock();
}
- PrivilegedAction a = new PrivilegedAction() {
- public Void run() {
- ThreadGroup mainTG = Thread.currentThread().getThreadGroup();
- ThreadGroup parentTG = mainTG.getParent();
- while (parentTG != null) {
- mainTG = parentTG;
- parentTG = mainTG.getParent();
- }
- Thread shutdownThread = new Thread(mainTG, "XToolkt-Shutdown-Thread") {
- public void run() {
- XSystemTrayPeer peer = XSystemTrayPeer.getPeerInstance();
- if (peer != null) {
- peer.dispose();
- }
- if (xs != null) {
- ((XAWTXSettings)xs).dispose();
- }
- freeXKB();
- if (log.isLoggable(PlatformLogger.Level.FINE)) {
- dumpPeers();
- }
+ PrivilegedAction a = () -> {
+ Thread shutdownThread = new Thread(ThreadGroupUtils.getRootThreadGroup(), "XToolkt-Shutdown-Thread") {
+ public void run() {
+ XSystemTrayPeer peer = XSystemTrayPeer.getPeerInstance();
+ if (peer != null) {
+ peer.dispose();
}
- };
- shutdownThread.setContextClassLoader(null);
- Runtime.getRuntime().addShutdownHook(shutdownThread);
- return null;
- }
+ if (xs != null) {
+ ((XAWTXSettings)xs).dispose();
+ }
+ freeXKB();
+ if (log.isLoggable(PlatformLogger.Level.FINE)) {
+ dumpPeers();
+ }
+ }
+ };
+ shutdownThread.setContextClassLoader(null);
+ Runtime.getRuntime().addShutdownHook(shutdownThread);
+ return null;
};
AccessController.doPrivileged(a);
}
@@ -322,21 +315,13 @@ public final class XToolkit extends UNIXToolkit implements Runnable {
init();
XWM.init();
- PrivilegedAction action = new PrivilegedAction() {
- public Thread run() {
- ThreadGroup currentTG = Thread.currentThread().getThreadGroup();
- ThreadGroup parentTG = currentTG.getParent();
- while (parentTG != null) {
- currentTG = parentTG;
- parentTG = currentTG.getParent();
- }
- Thread thread = new Thread(currentTG, XToolkit.this, "AWT-XAWT");
- thread.setPriority(Thread.NORM_PRIORITY + 1);
- thread.setDaemon(true);
- return thread;
- }
- };
- toolkitThread = AccessController.doPrivileged(action);
+ toolkitThread = AccessController.doPrivileged((PrivilegedAction) () -> {
+ Thread thread = new Thread(ThreadGroupUtils.getRootThreadGroup(), XToolkit.this, "AWT-XAWT");
+ thread.setContextClassLoader(null);
+ thread.setPriority(Thread.NORM_PRIORITY + 1);
+ thread.setDaemon(true);
+ return thread;
+ });
toolkitThread.start();
}
}
diff --git a/jdk/src/solaris/classes/sun/awt/X11GraphicsDevice.java b/jdk/src/solaris/classes/sun/awt/X11GraphicsDevice.java
index a1f71b97590..d69a4a0bce0 100644
--- a/jdk/src/solaris/classes/sun/awt/X11GraphicsDevice.java
+++ b/jdk/src/solaris/classes/sun/awt/X11GraphicsDevice.java
@@ -42,6 +42,8 @@ import sun.java2d.opengl.GLXGraphicsConfig;
import sun.java2d.xr.XRGraphicsConfig;
import sun.java2d.loops.SurfaceType;
+import sun.misc.ThreadGroupUtils;
+
/**
* This is an implementation of a GraphicsDevice object for a single
* X11 screen.
@@ -423,28 +425,19 @@ public class X11GraphicsDevice
// is already in the original DisplayMode at that time, this
// hook will have no effect)
shutdownHookRegistered = true;
- PrivilegedAction a = new PrivilegedAction() {
- public Void run() {
- ThreadGroup mainTG = Thread.currentThread().getThreadGroup();
- ThreadGroup parentTG = mainTG.getParent();
- while (parentTG != null) {
- mainTG = parentTG;
- parentTG = mainTG.getParent();
+ PrivilegedAction a = () -> {
+ ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
+ Runnable r = () -> {
+ Window old = getFullScreenWindow();
+ if (old != null) {
+ exitFullScreenExclusive(old);
+ setDisplayMode(origDisplayMode);
}
- Runnable r = new Runnable() {
- public void run() {
- Window old = getFullScreenWindow();
- if (old != null) {
- exitFullScreenExclusive(old);
- setDisplayMode(origDisplayMode);
- }
- }
- };
- Thread t = new Thread(mainTG, r,"Display-Change-Shutdown-Thread-"+screen);
- t.setContextClassLoader(null);
- Runtime.getRuntime().addShutdownHook(t);
- return null;
- }
+ };
+ Thread t = new Thread(rootTG, r,"Display-Change-Shutdown-Thread-"+screen);
+ t.setContextClassLoader(null);
+ Runtime.getRuntime().addShutdownHook(t);
+ return null;
};
AccessController.doPrivileged(a);
}
diff --git a/jdk/src/solaris/lib/content-types.properties b/jdk/src/solaris/classes/sun/net/www/content-types.properties
similarity index 100%
rename from jdk/src/solaris/lib/content-types.properties
rename to jdk/src/solaris/classes/sun/net/www/content-types.properties
diff --git a/jdk/src/solaris/classes/sun/nio/fs/LinuxNativeDispatcher.java b/jdk/src/solaris/classes/sun/nio/fs/LinuxNativeDispatcher.java
index 0186870688a..e8d8dc8d6e2 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/LinuxNativeDispatcher.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/LinuxNativeDispatcher.java
@@ -77,7 +77,7 @@ class LinuxNativeDispatcher extends UnixNativeDispatcher {
}
private static native int fgetxattr0(int filedes, long nameAddress,
- long valueAdddress, int valueLen) throws UnixException;
+ long valueAddress, int valueLen) throws UnixException;
/**
* fsetxattr(int filedes, const char *name, const void *value, size_t size, int flags);
@@ -94,7 +94,7 @@ class LinuxNativeDispatcher extends UnixNativeDispatcher {
}
private static native void fsetxattr0(int filedes, long nameAddress,
- long valueAdddress, int valueLen) throws UnixException;
+ long valueAddress, int valueLen) throws UnixException;
/**
* fremovexattr(int filedes, const char *name);
diff --git a/jdk/src/solaris/classes/sun/nio/fs/MagicFileTypeDetector.java b/jdk/src/solaris/classes/sun/nio/fs/MagicFileTypeDetector.java
index 11bc3a529d7..801bd626724 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/MagicFileTypeDetector.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/MagicFileTypeDetector.java
@@ -36,7 +36,7 @@ import java.security.PrivilegedAction;
class MagicFileTypeDetector extends AbstractFileTypeDetector {
- private static final String UNKNOW_MIME_TYPE = "application/octet-stream";
+ private static final String UNKNOWN_MIME_TYPE = "application/octet-stream";
// true if libmagic is available and successfully loaded
private final boolean libmagicAvailable;
@@ -57,7 +57,7 @@ class MagicFileTypeDetector extends AbstractFileTypeDetector {
try {
byte[] type = probe0(buffer.address());
String mimeType = (type == null) ? null : new String(type);
- return UNKNOW_MIME_TYPE.equals(mimeType) ? null : mimeType;
+ return UNKNOWN_MIME_TYPE.equals(mimeType) ? null : mimeType;
} finally {
buffer.release();
}
diff --git a/jdk/src/solaris/classes/sun/nio/fs/SolarisAclFileAttributeView.java b/jdk/src/solaris/classes/sun/nio/fs/SolarisAclFileAttributeView.java
index 6d72cd14487..f3ba7b3e6f0 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/SolarisAclFileAttributeView.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/SolarisAclFileAttributeView.java
@@ -290,7 +290,7 @@ class SolarisAclFileAttributeView
return acl;
}
- // Retrns true if NFSv4 ACLs not enabled on file system
+ // Returns true if NFSv4 ACLs not enabled on file system
private static boolean isAclsEnabled(int fd) {
try {
long enabled = fpathconf(fd, _PC_ACL_ENABLED);
diff --git a/jdk/src/solaris/classes/sun/nio/fs/SolarisWatchService.java b/jdk/src/solaris/classes/sun/nio/fs/SolarisWatchService.java
index e68ceab1036..0c1165ff5f4 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/SolarisWatchService.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/SolarisWatchService.java
@@ -627,14 +627,14 @@ class SolarisWatchService
/**
* Update watch key's events. If ENTRY_MODIFY changes to be enabled
- * then register each file in the direcory; If ENTRY_MODIFY changed to
+ * then register each file in the directory; If ENTRY_MODIFY changed to
* be disabled then unregister each file.
*/
void updateEvents(SolarisWatchKey key, Set extends WatchEvent.Kind>> events)
throws UnixException
{
- // update events, rembering if ENTRY_MODIFY was previously
+ // update events, remembering if ENTRY_MODIFY was previously
// enabled or disabled.
boolean oldModifyEnabled = key.events()
.contains(StandardWatchEventKinds.ENTRY_MODIFY);
diff --git a/jdk/src/solaris/classes/sun/nio/fs/UnixDirectoryStream.java b/jdk/src/solaris/classes/sun/nio/fs/UnixDirectoryStream.java
index 60f958203df..44d61b74b7f 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/UnixDirectoryStream.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/UnixDirectoryStream.java
@@ -48,7 +48,7 @@ class UnixDirectoryStream
// filter (may be null)
private final DirectoryStream.Filter super Path> filter;
- // used to coorindate closing of directory stream
+ // used to coordinate closing of directory stream
private final ReentrantReadWriteLock streamLock =
new ReentrantReadWriteLock(true);
diff --git a/jdk/src/solaris/classes/sun/nio/fs/UnixFileAttributeViews.java b/jdk/src/solaris/classes/sun/nio/fs/UnixFileAttributeViews.java
index 4d719d3aace..89d94aa02a8 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/UnixFileAttributeViews.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/UnixFileAttributeViews.java
@@ -133,7 +133,7 @@ class UnixFileAttributeViews {
private static final String OWNER_NAME = "owner";
private static final String GROUP_NAME = "group";
- // the names of the posix attributes (incudes basic)
+ // the names of the posix attributes (includes basic)
static final Set posixAttributeNames =
Util.newSet(basicAttributeNames, PERMISSIONS_NAME, OWNER_NAME, GROUP_NAME);
diff --git a/jdk/src/solaris/classes/sun/nio/fs/UnixFileSystem.java b/jdk/src/solaris/classes/sun/nio/fs/UnixFileSystem.java
index c902acea980..2dad464cb11 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/UnixFileSystem.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/UnixFileSystem.java
@@ -339,7 +339,7 @@ abstract class UnixFileSystem
};
}
- // Override if the platform has different path match requrement, such as
+ // Override if the platform has different path match requirement, such as
// case insensitive or Unicode canonical equal on MacOSX
Pattern compilePathMatchPattern(String expr) {
return Pattern.compile(expr);
diff --git a/jdk/src/solaris/demo/jni/Poller/Poller.c b/jdk/src/solaris/demo/jni/Poller/Poller.c
index 6a51212d962..5c627ac57ca 100644
--- a/jdk/src/solaris/demo/jni/Poller/Poller.c
+++ b/jdk/src/solaris/demo/jni/Poller/Poller.c
@@ -318,7 +318,7 @@ JNIEXPORT void JNICALL Java_Poller_nativeDestroyPoller
ioevent_t *ioeh;
- if (handle < 0 || handle > MAX_HANDLES)
+ if (handle < 0 || handle >= MAX_HANDLES)
{
STATE_EXCEPTION("DestroyPoller - handle out of range");
return;
@@ -366,7 +366,7 @@ JNIEXPORT jint JNICALL Java_Poller_nativeAddFd
int retval;
ioevent_t *ioeh;
- if (handle < 0 || handle > MAX_HANDLES)
+ if (handle < 0 || handle >= MAX_HANDLES)
return STATE_EXCEPTION("AddFd - handle out of range");
ioeh = &IOE_handles[handle];
@@ -459,7 +459,7 @@ jint addfd(JNIEnv *env, ioevent_t *ioeh, jint fd, jshort events)
return fd;
}
-/*
+/*
* Class: Poller
* Method: nativeRemoveFd
* Signature: (II)I
@@ -469,7 +469,7 @@ JNIEXPORT jint JNICALL Java_Poller_nativeRemoveFd
{
ioevent_t *ioeh;
- if (handle < 0 || handle > MAX_HANDLES)
+ if (handle < 0 || handle >= MAX_HANDLES)
return STATE_EXCEPTION("RemoveFd - handle out of range");
ioeh = &IOE_handles[handle];
@@ -576,7 +576,7 @@ JNIEXPORT jint JNICALL Java_Poller_nativeIsMember
int i;
ioevent_t *ioeh;
- if (handle < 0 || handle > MAX_HANDLES)
+ if (handle < 0 || handle >= MAX_HANDLES)
return STATE_EXCEPTION("IsMember - handle out of range");
ioeh = &IOE_handles[handle];
@@ -629,7 +629,7 @@ JNIEXPORT jint JNICALL Java_Poller_nativeWait
ioevent_t *ioeh;
jboolean isCopy1,isCopy2;
- if (handle < 0 || handle > MAX_HANDLES)
+ if (handle < 0 || handle >= MAX_HANDLES)
return STATE_EXCEPTION("nativeWait - handle out of range");
ioeh = &IOE_handles[handle];
diff --git a/jdk/src/solaris/native/com/sun/media/sound/PLATFORM_API_SolarisOS_Utils.c b/jdk/src/solaris/native/com/sun/media/sound/PLATFORM_API_SolarisOS_Utils.c
index 8b9601f51cf..f5da85aa163 100644
--- a/jdk/src/solaris/native/com/sun/media/sound/PLATFORM_API_SolarisOS_Utils.c
+++ b/jdk/src/solaris/native/com/sun/media/sound/PLATFORM_API_SolarisOS_Utils.c
@@ -76,7 +76,7 @@ int addAudioDevice(char* path, AudioDevicePath* adPath, int* count) {
adPath[*count].st_ino = statBuf.st_ino;
adPath[*count].st_dev = statBuf.st_dev;
strncpy(adPath[*count].path, path, MAX_NAME_LENGTH);
- adPath[*count].path[MAX_NAME_LENGTH] = 0;
+ adPath[*count].path[MAX_NAME_LENGTH - 1] = 0;
(*count)++;
TRACE1("Added audio device %s\n", path);
}
diff --git a/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c b/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c
new file mode 100644
index 00000000000..086ac9f9dc6
--- /dev/null
+++ b/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c
@@ -0,0 +1,337 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include
+#include
+
+#include "net_util.h"
+#include "jdk_net_SocketFlow.h"
+
+static jclass sf_status_class; /* Status enum type */
+
+static jfieldID sf_status;
+static jfieldID sf_priority;
+static jfieldID sf_bandwidth;
+
+static jfieldID sf_fd_fdID; /* FileDescriptor.fd */
+
+/* References to the literal enum values */
+
+static jobject sfs_NOSTATUS;
+static jobject sfs_OK;
+static jobject sfs_NOPERMISSION;
+static jobject sfs_NOTCONNECTED;
+static jobject sfs_NOTSUPPORTED;
+static jobject sfs_ALREADYCREATED;
+static jobject sfs_INPROGRESS;
+static jobject sfs_OTHER;
+
+static jobject getEnumField(JNIEnv *env, char *name);
+static void setStatus(JNIEnv *env, jobject obj, int errval);
+
+/* OS specific code is implemented in these three functions */
+
+static jboolean flowSupported0() ;
+
+/*
+ * Class: sun_net_ExtendedOptionsImpl
+ * Method: init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_sun_net_ExtendedOptionsImpl_init
+ (JNIEnv *env, jclass UNUSED)
+{
+ static int initialized = 0;
+ jclass c;
+
+ /* Global class references */
+
+ if (initialized) {
+ return;
+ }
+
+ c = (*env)->FindClass(env, "jdk/net/SocketFlow$Status");
+ CHECK_NULL(c);
+ sf_status_class = (*env)->NewGlobalRef(env, c);
+ CHECK_NULL(sf_status_class);
+
+ /* int "fd" field of java.io.FileDescriptor */
+
+ c = (*env)->FindClass(env, "java/io/FileDescriptor");
+ CHECK_NULL(c);
+ sf_fd_fdID = (*env)->GetFieldID(env, c, "fd", "I");
+ CHECK_NULL(sf_fd_fdID);
+
+
+ /* SocketFlow fields */
+
+ c = (*env)->FindClass(env, "jdk/net/SocketFlow");
+
+ /* status */
+
+ sf_status = (*env)->GetFieldID(env, c, "status",
+ "Ljdk/net/SocketFlow$Status;");
+ CHECK_NULL(sf_status);
+
+ /* priority */
+
+ sf_priority = (*env)->GetFieldID(env, c, "priority", "I");
+ CHECK_NULL(sf_priority);
+
+ /* bandwidth */
+
+ sf_bandwidth = (*env)->GetFieldID(env, c, "bandwidth", "J");
+ CHECK_NULL(sf_bandwidth);
+
+ /* Initialize the static enum values */
+
+ sfs_NOSTATUS = getEnumField(env, "NO_STATUS");
+ CHECK_NULL(sfs_NOSTATUS);
+ sfs_OK = getEnumField(env, "OK");
+ CHECK_NULL(sfs_OK);
+ sfs_NOPERMISSION = getEnumField(env, "NO_PERMISSION");
+ CHECK_NULL(sfs_NOPERMISSION);
+ sfs_NOTCONNECTED = getEnumField(env, "NOT_CONNECTED");
+ CHECK_NULL(sfs_NOTCONNECTED);
+ sfs_NOTSUPPORTED = getEnumField(env, "NOT_SUPPORTED");
+ CHECK_NULL(sfs_NOTSUPPORTED);
+ sfs_ALREADYCREATED = getEnumField(env, "ALREADY_CREATED");
+ CHECK_NULL(sfs_ALREADYCREATED);
+ sfs_INPROGRESS = getEnumField(env, "IN_PROGRESS");
+ CHECK_NULL(sfs_INPROGRESS);
+ sfs_OTHER = getEnumField(env, "OTHER");
+ CHECK_NULL(sfs_OTHER);
+ initialized = JNI_TRUE;
+}
+
+static jobject getEnumField(JNIEnv *env, char *name)
+{
+ jobject f;
+ jfieldID fID = (*env)->GetStaticFieldID(env, sf_status_class, name,
+ "Ljdk/net/SocketFlow$Status;");
+ CHECK_NULL_RETURN(fID, NULL);
+
+ f = (*env)->GetStaticObjectField(env, sf_status_class, fID);
+ CHECK_NULL_RETURN(f, NULL);
+ f = (*env)->NewGlobalRef(env, f);
+ CHECK_NULL_RETURN(f, NULL);
+ return f;
+}
+
+/*
+ * Retrieve the int file-descriptor from a public socket type object.
+ * Gets impl, then the FileDescriptor from the impl, and then the fd
+ * from that.
+ */
+static int getFD(JNIEnv *env, jobject fileDesc) {
+ return (*env)->GetIntField(env, fileDesc, sf_fd_fdID);
+}
+
+/**
+ * Sets the status field of a SocketFlow to one of the
+ * canned enum values
+ */
+static void setStatus (JNIEnv *env, jobject obj, int errval)
+{
+ switch (errval) {
+ case 0: /* OK */
+ (*env)->SetObjectField(env, obj, sf_status, sfs_OK);
+ break;
+ case EPERM:
+ (*env)->SetObjectField(env, obj, sf_status, sfs_NOPERMISSION);
+ break;
+ case ENOTCONN:
+ (*env)->SetObjectField(env, obj, sf_status, sfs_NOTCONNECTED);
+ break;
+ case EOPNOTSUPP:
+ (*env)->SetObjectField(env, obj, sf_status, sfs_NOTSUPPORTED);
+ break;
+ case EALREADY:
+ (*env)->SetObjectField(env, obj, sf_status, sfs_ALREADYCREATED);
+ break;
+ case EINPROGRESS:
+ (*env)->SetObjectField(env, obj, sf_status, sfs_INPROGRESS);
+ break;
+ default:
+ (*env)->SetObjectField(env, obj, sf_status, sfs_OTHER);
+ break;
+ }
+}
+
+#ifdef __solaris__
+
+/*
+ * Class: sun_net_ExtendedOptionsImpl
+ * Method: setFlowOption
+ * Signature: (Ljava/io/FileDescriptor;Ljdk/net/SocketFlow;)V
+ */
+JNIEXPORT void JNICALL Java_sun_net_ExtendedOptionsImpl_setFlowOption
+ (JNIEnv *env, jclass UNUSED, jobject fileDesc, jobject flow)
+{
+ int fd = getFD(env, fileDesc);
+
+ if (fd < 0) {
+ NET_ERROR(env, JNU_JAVANETPKG "SocketException", "socket closed");
+ return;
+ } else {
+ sock_flow_props_t props;
+ jlong bandwidth;
+ int rv;
+
+ jint priority = (*env)->GetIntField(env, flow, sf_priority);
+ memset(&props, 0, sizeof(props));
+ props.sfp_version = SOCK_FLOW_PROP_VERSION1;
+
+ if (priority != jdk_net_SocketFlow_UNSET) {
+ props.sfp_mask |= SFP_PRIORITY;
+ props.sfp_priority = priority;
+ }
+ bandwidth = (*env)->GetLongField(env, flow, sf_bandwidth);
+ if (bandwidth > -1) {
+ props.sfp_mask |= SFP_MAXBW;
+ props.sfp_maxbw = (uint64_t) bandwidth;
+ }
+ rv = setsockopt(fd, SOL_SOCKET, SO_FLOW_SLA, &props, sizeof(props));
+ if (rv < 0) {
+ if (errno == ENOPROTOOPT) {
+ JNU_ThrowByName(env, "java/lang/UnsupportedOperationException",
+ "unsupported socket option");
+ } else {
+ NET_ERROR(env, JNU_JAVANETPKG "SocketException",
+ "set option SO_FLOW_SLA failed");
+ }
+ return;
+ }
+ setStatus(env, flow, props.sfp_status);
+ }
+}
+
+/*
+ * Class: sun_net_ExtendedOptionsImpl
+ * Method: getFlowOption
+ * Signature: (Ljava/io/FileDescriptor;Ljdk/net/SocketFlow;)V
+ */
+JNIEXPORT void JNICALL Java_sun_net_ExtendedOptionsImpl_getFlowOption
+ (JNIEnv *env, jclass UNUSED, jobject fileDesc, jobject flow)
+{
+ int fd = getFD(env, fileDesc);
+
+ if (fd < 0) {
+ NET_ERROR(env, JNU_JAVANETPKG "SocketException", "socket closed");
+ return;
+ } else {
+ sock_flow_props_t props;
+ int status;
+ socklen_t sz = sizeof(props);
+
+ int rv = getsockopt(fd, SOL_SOCKET, SO_FLOW_SLA, &props, &sz);
+ if (rv < 0) {
+ if (errno == ENOPROTOOPT) {
+ JNU_ThrowByName(env, "java/lang/UnsupportedOperationException",
+ "unsupported socket option");
+ } else {
+ NET_ERROR(env, JNU_JAVANETPKG "SocketException",
+ "set option SO_FLOW_SLA failed");
+ }
+ return;
+ }
+ /* first check status to see if flow exists */
+ status = props.sfp_status;
+ setStatus(env, flow, status);
+ if (status == 0) { /* OK */
+ /* can set the other fields now */
+ if (props.sfp_mask & SFP_PRIORITY) {
+ (*env)->SetIntField(env, flow, sf_priority, props.sfp_priority);
+ }
+ if (props.sfp_mask & SFP_MAXBW) {
+ (*env)->SetLongField(env, flow, sf_bandwidth,
+ (jlong)props.sfp_maxbw);
+ }
+ }
+ }
+}
+
+static jboolean flowsupported;
+static jboolean flowsupported_set = JNI_FALSE;
+
+static jboolean flowSupported0()
+{
+ /* Do a simple dummy call, and try to figure out from that */
+ sock_flow_props_t props;
+ int rv, s;
+ if (flowsupported_set) {
+ return flowsupported;
+ }
+ s = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP);
+ if (s < 0) {
+ flowsupported = JNI_FALSE;
+ flowsupported_set = JNI_TRUE;
+ return JNI_FALSE;
+ }
+ memset(&props, 0, sizeof(props));
+ props.sfp_version = SOCK_FLOW_PROP_VERSION1;
+ props.sfp_mask |= SFP_PRIORITY;
+ props.sfp_priority = SFP_PRIO_NORMAL;
+ rv = setsockopt(s, SOL_SOCKET, SO_FLOW_SLA, &props, sizeof(props));
+ if (rv != 0 && errno == ENOPROTOOPT) {
+ rv = JNI_FALSE;
+ } else {
+ rv = JNI_TRUE;
+ }
+ close(s);
+ flowsupported = rv;
+ flowsupported_set = JNI_TRUE;
+ return flowsupported;
+}
+
+#else /* __solaris__ */
+
+/* Non Solaris. Functionality is not supported. So, throw UnsupportedOpExc */
+
+JNIEXPORT void JNICALL Java_sun_net_ExtendedOptionsImpl_setFlowOption
+ (JNIEnv *env, jclass UNUSED, jobject fileDesc, jobject flow)
+{
+ JNU_ThrowByName(env, "java/lang/UnsupportedOperationException",
+ "unsupported socket option");
+}
+
+JNIEXPORT void JNICALL Java_sun_net_ExtendedOptionsImpl_getFlowOption
+ (JNIEnv *env, jclass UNUSED, jobject fileDesc, jobject flow)
+{
+ JNU_ThrowByName(env, "java/lang/UnsupportedOperationException",
+ "unsupported socket option");
+}
+
+static jboolean flowSupported0() {
+ return JNI_FALSE;
+}
+
+#endif /* __solaris__ */
+
+JNIEXPORT jboolean JNICALL Java_sun_net_ExtendedOptionsImpl_flowSupported
+ (JNIEnv *env, jclass UNUSED)
+{
+ return flowSupported0();
+}
diff --git a/jdk/src/solaris/native/java/net/net_util_md.h b/jdk/src/solaris/native/java/net/net_util_md.h
index e7150da6018..31ed3f808eb 100644
--- a/jdk/src/solaris/native/java/net/net_util_md.h
+++ b/jdk/src/solaris/native/java/net/net_util_md.h
@@ -107,6 +107,47 @@ int getDefaultIPv6Interface(struct in6_addr *target_addr);
#ifdef __solaris__
int net_getParam(char *driver, char *param);
+
+#ifndef SO_FLOW_SLA
+#define SO_FLOW_SLA 0x1018
+
+#if _LONG_LONG_ALIGNMENT == 8 && _LONG_LONG_ALIGNMENT_32 == 4
+#pragma pack(4)
#endif
+/*
+ * Used with the setsockopt(SO_FLOW_SLA, ...) call to set
+ * per socket service level properties.
+ * When the application uses per-socket API, we will enforce the properties
+ * on both outbound and inbound packets.
+ *
+ * For now, only priority and maxbw are supported in SOCK_FLOW_PROP_VERSION1.
+ */
+typedef struct sock_flow_props_s {
+ int sfp_version;
+ uint32_t sfp_mask;
+ int sfp_priority; /* flow priority */
+ uint64_t sfp_maxbw; /* bandwidth limit in bps */
+ int sfp_status; /* flow create status for getsockopt */
+} sock_flow_props_t;
+
+#define SOCK_FLOW_PROP_VERSION1 1
+
+/* bit mask values for sfp_mask */
+#define SFP_MAXBW 0x00000001 /* Flow Bandwidth Limit */
+#define SFP_PRIORITY 0x00000008 /* Flow priority */
+
+/* possible values for sfp_priority */
+#define SFP_PRIO_NORMAL 1
+#define SFP_PRIO_HIGH 2
+
+#if _LONG_LONG_ALIGNMENT == 8 && _LONG_LONG_ALIGNMENT_32 == 4
+#pragma pack()
+#endif /* _LONG_LONG_ALIGNMENT */
+
+#endif /* SO_FLOW_SLA */
+#endif /* __solaris__ */
+
+JNIEXPORT jboolean JNICALL NET_IsFlowSupported();
+
#endif /* NET_UTILS_MD_H */
diff --git a/jdk/src/solaris/native/java/util/TimeZone_md.c b/jdk/src/solaris/native/java/util/TimeZone_md.c
index e1af8f92556..c90fcee25ba 100644
--- a/jdk/src/solaris/native/java/util/TimeZone_md.c
+++ b/jdk/src/solaris/native/java/util/TimeZone_md.c
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -56,6 +56,9 @@ static const char *ETC_TIMEZONE_FILE = "/etc/timezone";
static const char *ZONEINFO_DIR = "/usr/share/zoneinfo";
static const char *DEFAULT_ZONEINFO_FILE = "/etc/localtime";
#else
+#ifdef _AIX
+static const char *ETC_ENVIRONMENT_FILE = "/etc/environment";
+#endif
static const char *SYS_INIT_FILE = "/etc/default/init";
static const char *ZONEINFO_DIR = "/usr/share/lib/zoneinfo";
static const char *DEFAULT_ZONEINFO_FILE = "/usr/share/lib/zoneinfo/localtime";
@@ -619,8 +622,29 @@ getSolarisDefaultZoneID() {
static char *
getPlatformTimeZoneID()
{
- return NULL;
+ FILE *fp;
+ char *tz = NULL;
+ char *tz_key = "TZ=";
+ char line[256];
+ size_t tz_key_len = strlen(tz_key);
+
+ if ((fp = fopen(ETC_ENVIRONMENT_FILE, "r")) != NULL) {
+ while (fgets(line, sizeof(line), fp) != NULL) {
+ char *p = strchr(line, '\n');
+ if (p != NULL) {
+ *p = '\0';
+ }
+ if (0 == strncmp(line, tz_key, tz_key_len)) {
+ tz = strdup(line + tz_key_len);
+ break;
+ }
+ }
+ (void) fclose(fp);
+ }
+
+ return tz;
}
+static char *mapPlatformToJavaTimezone(const char *java_home_dir, const char *tz);
#endif
/*
@@ -678,9 +702,19 @@ findJavaTZ_md(const char *java_home_dir, const char *country)
if (freetz != NULL) {
free((void *) freetz);
}
+
+#ifdef _AIX
+ freetz = mapPlatformToJavaTimezone(java_home_dir, javatz);
+ if (javatz != NULL) {
+ free((void *) javatz);
+ }
+ javatz = freetz;
+#endif
}
+
return javatz;
}
+
/**
* Returns a GMT-offset-based zone ID. (e.g., "GMT-08:00")
*/
@@ -747,3 +781,101 @@ getGMTOffsetID()
return strdup(buf);
}
#endif /* MACOSX */
+
+#ifdef _AIX
+static char *
+mapPlatformToJavaTimezone(const char *java_home_dir, const char *tz) {
+ FILE *tzmapf;
+ char mapfilename[PATH_MAX+1];
+ char line[256];
+ int linecount = 0;
+ char temp[100], *temp_tz;
+ char *javatz = NULL;
+ char *str_tmp = NULL;
+ size_t temp_tz_len = 0;
+
+ /* On AIX, the TZ environment variable may end with a comma
+ * followed by modifier fields. These are ignored here.
+ */
+ strncpy(temp, tz, 100);
+ temp_tz = strtok_r(temp, ",", &str_tmp);
+
+ if(temp_tz == NULL)
+ goto tzerr;
+
+ temp_tz_len = strlen(temp_tz);
+
+ if (strlen(java_home_dir) >= (PATH_MAX - 15)) {
+ jio_fprintf(stderr, "java.home longer than maximum path length \n");
+ goto tzerr;
+ }
+
+ strncpy(mapfilename, java_home_dir, PATH_MAX);
+ strcat(mapfilename, "/lib/tzmappings");
+
+ if ((tzmapf = fopen(mapfilename, "r")) == NULL) {
+ jio_fprintf(stderr, "can't open %s\n", mapfilename);
+ goto tzerr;
+ }
+
+ while (fgets(line, sizeof(line), tzmapf) != NULL) {
+ char *p = line;
+ char *sol = line;
+ char *java;
+ int result;
+
+ linecount++;
+ /*
+ * Skip comments and blank lines
+ */
+ if (*p == '#' || *p == '\n') {
+ continue;
+ }
+
+ /*
+ * Get the first field, platform zone ID
+ */
+ while (*p != '\0' && *p != '\t') {
+ p++;
+ }
+ if (*p == '\0') {
+ /* mapping table is broken! */
+ jio_fprintf(stderr, "tzmappings: Illegal format at near line %d.\n", linecount);
+ break;
+ }
+
+ *p++ = '\0';
+ if ((result = strncmp(temp_tz, sol, temp_tz_len)) == 0) {
+ /*
+ * If this is the current platform zone ID,
+ * take the Java time zone ID (2nd field).
+ */
+ java = p;
+ while (*p != '\0' && *p != '\n') {
+ p++;
+ }
+
+ if (*p == '\0') {
+ /* mapping table is broken! */
+ jio_fprintf(stderr, "tzmappings: Illegal format at line %d.\n", linecount);
+ break;
+ }
+
+ *p = '\0';
+ javatz = strdup(java);
+ break;
+ } else if (result < 0) {
+ break;
+ }
+ }
+ (void) fclose(tzmapf);
+
+tzerr:
+ if (javatz == NULL) {
+ return getGMTOffsetID();
+ }
+
+ return javatz;
+}
+#endif
+
diff --git a/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java b/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java
index dbc4129618b..c6b7351699e 100644
--- a/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java
+++ b/jdk/src/windows/classes/sun/awt/shell/Win32ShellFolderManager2.java
@@ -39,6 +39,7 @@ import java.util.concurrent.*;
import static sun.awt.shell.Win32ShellFolder2.*;
import sun.awt.OSInfo;
+import sun.misc.ThreadGroupUtils;
// NOTE: This class supersedes Win32ShellFolderManager, which was removed
// from distribution after version 1.4.2.
@@ -503,23 +504,16 @@ public class Win32ShellFolderManager2 extends ShellFolderManager {
}
}
};
- comThread =
- AccessController.doPrivileged(
- new PrivilegedAction() {
- public Thread run() {
+ comThread = AccessController.doPrivileged((PrivilegedAction) () -> {
/* The thread must be a member of a thread group
* which will not get GCed before VM exit.
* Make its parent the top-level thread group.
*/
- ThreadGroup tg = Thread.currentThread().getThreadGroup();
- for (ThreadGroup tgn = tg;
- tgn != null;
- tg = tgn, tgn = tg.getParent());
- Thread thread = new Thread(tg, comRun, "Swing-Shell");
+ ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
+ Thread thread = new Thread(rootTG, comRun, "Swing-Shell");
thread.setDaemon(true);
return thread;
}
- }
);
return comThread;
}
diff --git a/jdk/src/windows/classes/sun/awt/windows/WClipboard.java b/jdk/src/windows/classes/sun/awt/windows/WClipboard.java
index 19383691b5c..d51ed941f38 100644
--- a/jdk/src/windows/classes/sun/awt/windows/WClipboard.java
+++ b/jdk/src/windows/classes/sun/awt/windows/WClipboard.java
@@ -62,7 +62,6 @@ final class WClipboard extends SunClipboard {
@Override
protected void setContentsNative(Transferable contents) {
-
// Don't use delayed Clipboard rendering for the Transferable's data.
// If we did that, we would call Transferable.getTransferData on
// the Toolkit thread, which is a security hole.
@@ -71,7 +70,7 @@ final class WClipboard extends SunClipboard {
// translated. Then, for each format, translate the data and post
// it to the Clipboard.
Map formatMap = WDataTransferer.getInstance().
- getFormatsForTransferable(contents, flavorMap);
+ getFormatsForTransferable(contents, getDefaultFlavorTable());
openClipboard(this);
diff --git a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java
index 6086cd45eba..71af30e5190 100644
--- a/jdk/src/windows/classes/sun/awt/windows/WToolkit.java
+++ b/jdk/src/windows/classes/sun/awt/windows/WToolkit.java
@@ -40,6 +40,7 @@ import sun.awt.AWTAutoShutdown;
import sun.awt.AWTPermissions;
import sun.awt.LightweightFrame;
import sun.awt.SunToolkit;
+import sun.misc.ThreadGroupUtils;
import sun.awt.Win32GraphicsDevice;
import sun.awt.Win32GraphicsEnvironment;
import sun.awt.datatransfer.DataTransferer;
@@ -224,7 +225,7 @@ public final class WToolkit extends SunToolkit implements Runnable {
private static native void postDispose();
- private static native boolean startToolkitThread(Runnable thread);
+ private static native boolean startToolkitThread(Runnable thread, ThreadGroup rootThreadGroup);
public WToolkit() {
// Startup toolkit threads
@@ -241,8 +242,11 @@ public final class WToolkit extends SunToolkit implements Runnable {
*/
AWTAutoShutdown.notifyToolkitThreadBusy();
- if (!startToolkitThread(this)) {
- Thread toolkitThread = new Thread(this, "AWT-Windows");
+ // Find a root TG and attach Appkit thread to it
+ ThreadGroup rootTG = AccessController.doPrivileged(
+ (PrivilegedAction) ThreadGroupUtils::getRootThreadGroup);
+ if (!startToolkitThread(this, rootTG)) {
+ Thread toolkitThread = new Thread(rootTG, this, "AWT-Windows");
toolkitThread.setDaemon(true);
toolkitThread.start();
}
@@ -268,32 +272,21 @@ public final class WToolkit extends SunToolkit implements Runnable {
}
private final void registerShutdownHook() {
- AccessController.doPrivileged(new PrivilegedAction() {
- @Override
- public Void run() {
- ThreadGroup currentTG =
- Thread.currentThread().getThreadGroup();
- ThreadGroup parentTG = currentTG.getParent();
- while (parentTG != null) {
- currentTG = parentTG;
- parentTG = currentTG.getParent();
- }
- Thread shutdown = new Thread(currentTG, new Runnable() {
- @Override
- public void run() {
- shutdown();
- }
- });
- shutdown.setContextClassLoader(null);
- Runtime.getRuntime().addShutdownHook(shutdown);
- return null;
- }
- });
+ AccessController.doPrivileged((PrivilegedAction) () -> {
+ Thread shutdown = new Thread(ThreadGroupUtils.getRootThreadGroup(), this::shutdown);
+ shutdown.setContextClassLoader(null);
+ Runtime.getRuntime().addShutdownHook(shutdown);
+ return null;
+ });
}
@Override
public void run() {
- Thread.currentThread().setPriority(Thread.NORM_PRIORITY+1);
+ AccessController.doPrivileged((PrivilegedAction) () -> {
+ Thread.currentThread().setContextClassLoader(null);
+ return null;
+ });
+ Thread.currentThread().setPriority(Thread.NORM_PRIORITY + 1);
boolean startPump = init();
if (startPump) {
diff --git a/jdk/src/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java b/jdk/src/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java
index 57233f66edf..bc9e98eb85c 100644
--- a/jdk/src/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java
+++ b/jdk/src/windows/classes/sun/java2d/d3d/D3DScreenUpdateManager.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,9 @@ import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.HashMap;
-import sun.awt.SunToolkit;
+
import sun.awt.AWTAccessor;
+import sun.misc.ThreadGroupUtils;
import sun.awt.Win32GraphicsConfig;
import sun.awt.windows.WComponentPeer;
import sun.java2d.InvalidPipeException;
@@ -92,21 +93,12 @@ public class D3DScreenUpdateManager extends ScreenUpdateManager
public D3DScreenUpdateManager() {
done = false;
AccessController.doPrivileged(
- new PrivilegedAction() {
- public Object run() {
- ThreadGroup currentTG =
- Thread.currentThread().getThreadGroup();
- ThreadGroup parentTG = currentTG.getParent();
- while (parentTG != null) {
- currentTG = parentTG;
- parentTG = currentTG.getParent();
- }
- Thread shutdown = new Thread(currentTG, new Runnable() {
- public void run() {
- done = true;
- wakeUpUpdateThread();
- }
- });
+ (PrivilegedAction) () -> {
+ ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
+ Thread shutdown = new Thread(rootTG, () -> {
+ done = true;
+ wakeUpUpdateThread();
+ });
shutdown.setContextClassLoader(null);
try {
Runtime.getRuntime().addShutdownHook(shutdown);
@@ -115,7 +107,6 @@ public class D3DScreenUpdateManager extends ScreenUpdateManager
}
return null;
}
- }
);
}
@@ -354,21 +345,17 @@ public class D3DScreenUpdateManager extends ScreenUpdateManager
*/
private synchronized void startUpdateThread() {
if (screenUpdater == null) {
- screenUpdater = (Thread)java.security.AccessController.doPrivileged(
- new java.security.PrivilegedAction() {
- public Object run() {
- ThreadGroup tg =
- Thread.currentThread().getThreadGroup();
- for (ThreadGroup tgn = tg;
- tgn != null; tg = tgn, tgn = tg.getParent());
- Thread t = new Thread(tg, D3DScreenUpdateManager.this,
- "D3D Screen Updater");
+ screenUpdater = AccessController.doPrivileged(
+ (PrivilegedAction) () -> {
+ ThreadGroup rootTG = ThreadGroupUtils.getRootThreadGroup();
+ Thread t = new Thread(rootTG,
+ D3DScreenUpdateManager.this,
+ "D3D Screen Updater");
// REMIND: should it be higher?
t.setPriority(Thread.NORM_PRIORITY + 2);
t.setDaemon(true);
return t;
- }
- });
+ });
screenUpdater.start();
} else {
wakeUpUpdateThread();
diff --git a/jdk/src/windows/lib/content-types.properties b/jdk/src/windows/classes/sun/net/www/content-types.properties
similarity index 100%
rename from jdk/src/windows/lib/content-types.properties
rename to jdk/src/windows/classes/sun/net/www/content-types.properties
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsAclFileAttributeView.java b/jdk/src/windows/classes/sun/nio/fs/WindowsAclFileAttributeView.java
index ee8eb3698c2..57ab16dab12 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsAclFileAttributeView.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsAclFileAttributeView.java
@@ -61,7 +61,7 @@ class WindowsAclFileAttributeView
this.followLinks = followLinks;
}
- // permision check
+ // permission check
private void checkAccess(WindowsPath file,
boolean checkRead,
boolean checkWrite)
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsConstants.java b/jdk/src/windows/classes/sun/nio/fs/WindowsConstants.java
index f691ad59725..d644a4b1ec3 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsConstants.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsConstants.java
@@ -94,7 +94,7 @@ class WindowsConstants {
public static final int ERROR_NOT_READY = 21;
public static final int ERROR_SHARING_VIOLATION = 32;
public static final int ERROR_FILE_EXISTS = 80;
- public static final int ERROR_INVALID_PARAMATER = 87;
+ public static final int ERROR_INVALID_PARAMETER = 87;
public static final int ERROR_DISK_FULL = 112;
public static final int ERROR_INSUFFICIENT_BUFFER = 122;
public static final int ERROR_INVALID_LEVEL = 124;
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsFileAttributeViews.java b/jdk/src/windows/classes/sun/nio/fs/WindowsFileAttributeViews.java
index 737bbd73e98..6632afc2b00 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsFileAttributeViews.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsFileAttributeViews.java
@@ -98,9 +98,9 @@ class WindowsFileAttributeViews {
lastAccessTime,
lastWriteTime);
} catch (WindowsException x) {
- // If ERROR_INVALID_PARAMATER is returned and the volume is
+ // If ERROR_INVALID_PARAMETER is returned and the volume is
// FAT then adjust to the FAT epoch and retry.
- if (followLinks && x.lastError() == ERROR_INVALID_PARAMATER) {
+ if (followLinks && x.lastError() == ERROR_INVALID_PARAMETER) {
try {
if (WindowsFileStore.create(file).type().equals("FAT")) {
SetFileTime(handle,
@@ -157,7 +157,7 @@ class WindowsFileAttributeViews {
private static final String HIDDEN_NAME = "hidden";
private static final String ATTRIBUTES_NAME = "attributes";
- // the names of the DOS attribtues (includes basic)
+ // the names of the DOS attributes (includes basic)
static final Set dosAttributeNames =
Util.newSet(basicAttributeNames,
READONLY_NAME, ARCHIVE_NAME, SYSTEM_NAME, HIDDEN_NAME, ATTRIBUTES_NAME);
@@ -223,7 +223,7 @@ class WindowsFileAttributeViews {
{
file.checkWrite();
- // GetFileAttribtues & SetFileAttributes do not follow links so when
+ // GetFileAttributes & SetFileAttributes do not follow links so when
// following links we need the final target
String path = WindowsLinkSupport.getFinalPath(file, followLinks);
try {
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java b/jdk/src/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java
index bd5f890d3ab..e86c385a622 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsFileSystemProvider.java
@@ -384,7 +384,7 @@ public class WindowsFileSystemProvider
file.getPathForExceptionMessage(), null,
"Permissions does not allow requested access");
- // for write access we neeed to check if the DOS readonly attribute
+ // for write access we need to check if the DOS readonly attribute
// and if the volume is read-only
if (w) {
try {
@@ -553,7 +553,7 @@ public class WindowsFileSystemProvider
}
/*
- * Windows treates symbolic links to directories differently than it
+ * Windows treats symbolic links to directories differently than it
* does to other file types. For that reason we need to check if the
* target is a directory (or a directory junction).
*/
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsNativeDispatcher.java b/jdk/src/windows/classes/sun/nio/fs/WindowsNativeDispatcher.java
index a380c3d3393..d20d12fb053 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsNativeDispatcher.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsNativeDispatcher.java
@@ -917,7 +917,7 @@ class WindowsNativeDispatcher {
}
}
private static native void CreateHardLink0(long newFileBuffer,
- long existingFiletBuffer) throws WindowsException;
+ long existingFileBuffer) throws WindowsException;
/**
* GetFullPathName(
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsPath.java b/jdk/src/windows/classes/sun/nio/fs/WindowsPath.java
index 4ccaf5dbb12..e0a6e5be15a 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsPath.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsPath.java
@@ -133,7 +133,7 @@ class WindowsPath extends AbstractPath {
/**
* Special implementation with attached/cached attributes (used to quicken
- * file tree traveral)
+ * file tree traversal)
*/
private static class WindowsPathWithAttributes
extends WindowsPath implements BasicFileAttributesHolder
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsSecurity.java b/jdk/src/windows/classes/sun/nio/fs/WindowsSecurity.java
index 1ceb570f1de..7e8af3e426b 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsSecurity.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsSecurity.java
@@ -129,11 +129,11 @@ class WindowsSecurity {
int genericRead, int genericWrite, int genericExecute, int genericAll)
throws WindowsException
{
- int privilegies = TOKEN_QUERY;
- long hToken = OpenThreadToken(GetCurrentThread(), privilegies, false);
+ int privileges = TOKEN_QUERY;
+ long hToken = OpenThreadToken(GetCurrentThread(), privileges, false);
if (hToken == 0L && processTokenWithDuplicateAccess != 0L)
hToken = DuplicateTokenEx(processTokenWithDuplicateAccess,
- privilegies);
+ privileges);
boolean hasRight = false;
if (hToken != 0L) {
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsUserDefinedFileAttributeView.java b/jdk/src/windows/classes/sun/nio/fs/WindowsUserDefinedFileAttributeView.java
index 45f5d064459..64ef12a9855 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsUserDefinedFileAttributeView.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsUserDefinedFileAttributeView.java
@@ -200,7 +200,7 @@ class WindowsUserDefinedFileAttributeView
public List list() throws IOException {
if (System.getSecurityManager() != null)
checkAccess(file.getPathForPermissionCheck(), true, false);
- // use stream APIs on Windwos Server 2003 and newer
+ // use stream APIs on Windows Server 2003 and newer
if (file.getFileSystem().supportsStreamEnumeration()) {
return listUsingStreamEnumeration();
} else {
diff --git a/jdk/src/windows/classes/sun/nio/fs/WindowsWatchService.java b/jdk/src/windows/classes/sun/nio/fs/WindowsWatchService.java
index 4ad10243f02..6677c874348 100644
--- a/jdk/src/windows/classes/sun/nio/fs/WindowsWatchService.java
+++ b/jdk/src/windows/classes/sun/nio/fs/WindowsWatchService.java
@@ -556,7 +556,7 @@ class WindowsWatchService
// ReadDirectoryChangesW failed
criticalError = true;
} else {
- // ERROR_MORE_DATA is a warning about incomplite
+ // ERROR_MORE_DATA is a warning about incomplete
// data transfer over TCP/UDP stack. For the case
// [messageSize] is zero in the most of cases.
diff --git a/jdk/src/windows/classes/sun/print/Win32PrintService.java b/jdk/src/windows/classes/sun/print/Win32PrintService.java
index b8b4dfda1b5..6ddbdba969f 100644
--- a/jdk/src/windows/classes/sun/print/Win32PrintService.java
+++ b/jdk/src/windows/classes/sun/print/Win32PrintService.java
@@ -1585,7 +1585,7 @@ public class Win32PrintService implements PrintService, AttributeUpdater,
if (flavor != null && !isDocFlavorSupported(flavor)) {
throw new IllegalArgumentException("flavor " + flavor +
- "is not supported");
+ " is not supported");
}
if (attributes == null) {
diff --git a/jdk/src/windows/native/java/net/ExtendedOptionsImpl.c b/jdk/src/windows/native/java/net/ExtendedOptionsImpl.c
new file mode 100644
index 00000000000..2bd955cd13e
--- /dev/null
+++ b/jdk/src/windows/native/java/net/ExtendedOptionsImpl.c
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include
+#include
+
+#include "net_util.h"
+
+/*
+ * Class: sun_net_ExtendedOptionsImpl
+ * Method: init
+ * Signature: ()V
+ */
+JNIEXPORT void JNICALL Java_sun_net_ExtendedOptionsImpl_init
+ (JNIEnv *env, jclass UNUSED)
+{
+}
+
+/* Non Solaris. Functionality is not supported. So, throw UnsupportedOpExc */
+
+JNIEXPORT void JNICALL Java_sun_net_ExtendedOptionsImpl_setFlowOption
+ (JNIEnv *env, jclass UNUSED, jobject fileDesc, jobject flow)
+{
+ JNU_ThrowByName(env, "java/lang/UnsupportedOperationException",
+ "unsupported socket option");
+}
+
+JNIEXPORT void JNICALL Java_sun_net_ExtendedOptionsImpl_getFlowOption
+ (JNIEnv *env, jclass UNUSED, jobject fileDesc, jobject flow)
+{
+ JNU_ThrowByName(env, "java/lang/UnsupportedOperationException",
+ "unsupported socket option");
+}
+
+static jboolean flowSupported0() {
+ return JNI_FALSE;
+}
+
+JNIEXPORT jboolean JNICALL Java_sun_net_ExtendedOptionsImpl_flowSupported
+ (JNIEnv *env, jclass UNUSED)
+{
+ return JNI_FALSE;
+}
diff --git a/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp b/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp
index 2ef0f0c7981..dcb4ea71f8d 100644
--- a/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Toolkit.cpp
@@ -351,6 +351,7 @@ struct ToolkitThreadProc_Data {
HANDLE hCompleted;
jobject thread;
+ jobject threadGroup;
};
void ToolkitThreadProc(void *param)
@@ -363,7 +364,7 @@ void ToolkitThreadProc(void *param)
JavaVMAttachArgs attachArgs;
attachArgs.version = JNI_VERSION_1_2;
attachArgs.name = "AWT-Windows";
- attachArgs.group = NULL;
+ attachArgs.group = data->threadGroup;
jint res = jvm->AttachCurrentThreadAsDaemon((void **)&env, &attachArgs);
if (res < 0) {
@@ -402,17 +403,18 @@ void ToolkitThreadProc(void *param)
/*
* Class: sun_awt_windows_WToolkit
* Method: startToolkitThread
- * Signature: (Ljava/lang/Runnable;)Z
+ * Signature: (Ljava/lang/Runnable;Ljava/lang/ThreadGroup)Z
*/
JNIEXPORT jboolean JNICALL
-Java_sun_awt_windows_WToolkit_startToolkitThread(JNIEnv *env, jclass cls, jobject thread)
+Java_sun_awt_windows_WToolkit_startToolkitThread(JNIEnv *env, jclass cls, jobject thread, jobject threadGroup)
{
AwtToolkit& tk = AwtToolkit::GetInstance();
ToolkitThreadProc_Data data;
data.result = false;
data.thread = env->NewGlobalRef(thread);
- if (data.thread == NULL) {
+ data.threadGroup = env->NewGlobalRef(threadGroup);
+ if (data.thread == NULL || data.threadGroup == NULL) {
return JNI_FALSE;
}
data.hCompleted = ::CreateEvent(NULL, FALSE, FALSE, NULL);
@@ -430,6 +432,7 @@ Java_sun_awt_windows_WToolkit_startToolkitThread(JNIEnv *env, jclass cls, jobjec
::CloseHandle(data.hCompleted);
env->DeleteGlobalRef(data.thread);
+ env->DeleteGlobalRef(data.threadGroup);
return result ? JNI_TRUE : JNI_FALSE;
}
diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt
index 2b18741c05b..21058464087 100644
--- a/jdk/test/ProblemList.txt
+++ b/jdk/test/ProblemList.txt
@@ -1,6 +1,6 @@
###########################################################################
#
-# Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
@@ -120,9 +120,6 @@
# jdk_lang
-# 8029415
-java/lang/reflect/Method/invoke/TestPrivateInterfaceMethodReflect.java generic-all
-
############################################################################
# jdk_management
@@ -151,9 +148,6 @@ demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java generic-all
# jdk_net
-# Filed 7052625
-com/sun/net/httpserver/bugs/6725892/Test.java generic-all
-
# 7148829
sun/net/InetAddress/nameservice/simple/CacheTest.java generic-all
sun/net/InetAddress/nameservice/simple/DefaultCaching.java generic-all
diff --git a/jdk/test/TEST.groups b/jdk/test/TEST.groups
index 12b1ba79322..5ea0c43ea87 100644
--- a/jdk/test/TEST.groups
+++ b/jdk/test/TEST.groups
@@ -102,7 +102,8 @@ jdk_nio = \
jdk_net = \
java/net \
com/sun/net/httpserver \
- sun/net
+ sun/net \
+ jdk/net
jdk_time = \
java/time
@@ -193,7 +194,7 @@ jdk_other = \
com/sun/jndi \
com/sun/corba \
lib/testlibrary \
- demo/zipfs \
+ jdk/nio/zipfs \
sample
#
@@ -284,7 +285,7 @@ jdk_stable = \
javax/accessibility \
com/sun/java/swing \
sun/pisces \
- com/sun/awt
+ com/sun/awt
###############################################################################
@@ -294,7 +295,7 @@ jdk_stable = \
# - compact1, compact2, compact3, full JRE, JDK
#
# In addition they support testing of the minimal VM on compact1 and compact2.
-# Essentially this defines groups based around the specified API's and VM
+# Essentially this defines groups based around the specified API's and VM
# services available in the runtime.
#
# The groups are defined hierarchically in two forms:
@@ -506,7 +507,7 @@ compact2 = \
-:needs_jdk
# Tests that require compact2 API's and a full VM
-#
+#
needs_full_vm_compact2 =
# Minimal VM on Compact 2 adds in some compact2 tests
@@ -590,7 +591,7 @@ needs_compact2 = \
javax/crypto/Cipher/CipherStreamClose.java \
sun/misc/URLClassPath/ClassnameCharTest.java \
sun/net/www/protocol/https/HttpsURLConnection/HttpsCreateSockTest.java \
- sun/net/www/protocol/https/HttpsURLConnection/HttpsSocketFacTest.java
+ sun/net/www/protocol/https/HttpsURLConnection/HttpsSocketFacTest.java
# Compact 1 adds full VM tests
#
diff --git a/jdk/test/com/sun/jarsigner/DefaultMethod.java b/jdk/test/com/sun/jarsigner/DefaultMethod.java
new file mode 100644
index 00000000000..fba92813c59
--- /dev/null
+++ b/jdk/test/com/sun/jarsigner/DefaultMethod.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8039358
+ * @summary com.sun.jarsigner.ContentSignerParameters.getTSAPolicyID() should be default
+ * @compile DefaultMethod.java
+ */
+
+import com.sun.jarsigner.ContentSignerParameters;
+
+import java.net.URI;
+import java.security.cert.X509Certificate;
+import java.util.zip.ZipFile;
+
+public class DefaultMethod implements ContentSignerParameters {
+
+ @Override
+ public String[] getCommandLine() {
+ return new String[0];
+ }
+
+ @Override
+ public URI getTimestampingAuthority() {
+ return null;
+ }
+
+ @Override
+ public X509Certificate getTimestampingAuthorityCertificate() {
+ return null;
+ }
+
+ @Override
+ public byte[] getSignature() {
+ return new byte[0];
+ }
+
+ @Override
+ public String getSignatureAlgorithm() {
+ return null;
+ }
+
+ @Override
+ public X509Certificate[] getSignerCertificateChain() {
+ return new X509Certificate[0];
+ }
+
+ @Override
+ public byte[] getContent() {
+ return new byte[0];
+ }
+
+ @Override
+ public ZipFile getSource() {
+ return null;
+ }
+}
diff --git a/jdk/test/com/sun/jdi/ShellScaffold.sh b/jdk/test/com/sun/jdi/ShellScaffold.sh
index 16c41eae056..193aabcb907 100644
--- a/jdk/test/com/sun/jdi/ShellScaffold.sh
+++ b/jdk/test/com/sun/jdi/ShellScaffold.sh
@@ -199,30 +199,26 @@ findPid()
return 1
fi
- if [ -z "$isWin98" ] ; then
- if [ "$osname" = SunOS ] ; then
- # Solaris and OpenSolaris use pgrep and not ps in psCmd
- findPidCmd="$psCmd"
- elif [ "$osname" = AIX ] ; then
- findPidCmd="$psCmd"
- else
+ case "$osname" in
+ SunOS | AIX)
+ $psCmd | $grep '^ *'"$1 " > $devnull 2>&1
+ res=$?
+ ;;
+ Windows* | CYGWIN*)
+ # Don't use ps on cygwin since it sometimes misses
+ # some processes (!).
+ tasklist /NH | $grep " $1 " > $devnull 2>&1
+ res=$?
+ ;;
+ *)
# Never use plain 'ps', which requires a "controlling terminal"
# and will fail with a "ps: no controlling terminal" error.
# Running under 'rsh' will cause this ps error.
- # cygwin ps puts an I in column 1 for some reason.
- findPidCmd="$psCmd -e"
- fi
- $findPidCmd | $grep '^I* *'"$1 " > $devnull 2>&1
- return $?
- fi
-
- # mks 6.2a on win98 has $! getting a negative
- # number and in ps, it shows up as 0x...
- # Thus, we can't search in ps output for
- # PIDs gotten via $!
- # We don't know if it is running or not - assume it is.
- # We don't really care about win98 anymore.
- return 0
+ $psCmd -e | $grep '^ *'"$1 " > $devnull 2>&1
+ res=$?
+ ;;
+ esac
+ return $res
}
setup()
@@ -252,16 +248,10 @@ setup()
ulimitCmd=
osname=`uname -s`
- isWin98=
isCygwin=
case "$osname" in
Windows* | CYGWIN*)
devnull=NUL
- if [ "$osname" = Windows_98 -o "$osname" = Windows_ME ]; then
- isWin98=1
- debuggeeKeyword='we_cant_kill_debuggees_on_win98'
- jdbKeyword='jdb\.exe'
- fi
case "$osname" in
CYGWIN*)
isCygwin=1
@@ -772,7 +762,7 @@ waitForJdbMsg()
sleep ${sleep_seconds}
findPid $topPid
if [ $? != 0 ] ; then
- # Top process is dead. We better die too
+ echo "--Top process ($topPid) is dead. We better die too" >&2
dojstack
exit 1
fi
@@ -977,19 +967,12 @@ waitForFinish()
break
fi
- if [ ! -z "$isWin98" ] ; then
- $psCmd | $grep -i 'JDB\.EXE' >$devnull 2>&1
- if [ $? != 0 ] ; then
- break
- fi
- fi
-
# (Don't use jdbFailIfPresent here since it is not safe
# to call from different processes)
- $grep -s 'Input stream closed' $jdbOutFile > $devnull 2>&1
- if [ $? = 0 ] ; then
+ $grep -s 'Input stream closed' $jdbOutFile > $devnull 2>&1
+ if [ $? = 0 ] ; then
dofail "jdb input stream closed prematurely"
- fi
+ fi
# If a failure has occured, quit
if [ -r "$failFile" ] ; then
diff --git a/jdk/test/com/sun/jndi/ldap/Base64Test.java b/jdk/test/com/sun/jndi/ldap/Base64Test.java
new file mode 100644
index 00000000000..a5547af8ca5
--- /dev/null
+++ b/jdk/test/com/sun/jndi/ldap/Base64Test.java
@@ -0,0 +1,214 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8035807
+ * @summary Confirm that old and new Base64 encodings are compatible.
+ */
+
+import java.io.*;
+import java.util.*;
+import javax.naming.*;
+import javax.naming.directory.*;
+
+import sun.misc.BASE64Decoder;
+
+/*
+ * RFC 2713 specifies an encoding for Java objects stored in an LDAP directory.
+ * Section 3.6 specifies how a binary-valued JNDI RefAddr object is encoded
+ * in the value of a javaReferenceAttribute LDAP attribute: first the RefAddr
+ * object is serialized and then it is encoded using Base64.
+ *
+ * Since JDK 9, the JNDI/LDAP provider uses the public Base64 encoder which
+ * adheres strictly to the MIME encoding rules. The encoder inserts '\r\n'
+ * as the line separator at intervals of 76 characters. Previously the
+ * JNDI/LDAP provider used a private Base64 encoder which inserted '\n'
+ * as the line separator. It is a compatible change.
+ *
+ * This test demonstrates that there is no compatability problem when
+ * encoding and decoding using either Base64 coder:
+ *
+ * encode with s.m.BASE64Encoder, decode with s.m.BASE64Decoder => OK
+ * encode with s.m.BASE64Encoder, decode with j.u.Base64.Decoder => OK
+ * encode with j.u.Base64.Encoder, decode with s.m.BASE64Decoder => OK
+ * encode with j.u.Base64.Encoder, decode with j.u.Base64.Decoder => OK
+ *
+ *
+ * NOTE: The two Base64 encodings used in this test were captured from
+ * LDAP protocol exchanges during attempts by the JNDI/LDAP provider
+ * to store a JNDI Reference test object.
+ */
+
+public class Base64Test {
+ /*
+ * The old Base64 encoding uses '\n' as the line separator at 76 character
+ * intervals:
+ *
+ * 0000: 72 4F 30 41 42 58 4E 79 41 42 70 71 59 58 5A 68 rO0ABXNyABpqYXZh
+ * 0010: 65 43 35 75 59 57 31 70 62 6D 63 75 51 6D 6C 75 eC5uYW1pbmcuQmlu
+ * 0020: 59 58 4A 35 55 6D 56 6D 51 57 52 6B 63 74 43 61 YXJ5UmVmQWRkctCa
+ * 0030: 6B 37 4C 65 73 34 68 48 41 67 41 42 57 77 41 44 k7Les4hHAgABWwAD
+ * 0040: 59 6E 56 6D 64 41 41 43 57 30 4A 34 0A 63 67 41 YnVmdAACW0J4.cgA <
+ * 0050: 55 61 6D 46 32 59 58 67 75 62 6D 46 74 61 57 35 UamF2YXgubmFtaW5
+ * 0060: 6E 4C 6C 4A 6C 5A 6B 46 6B 5A 48 4C 72 6F 41 65 nLlJlZkFkZHLroAe
+ * 0070: 61 41 6A 69 76 53 67 49 41 41 55 77 41 43 47 46 aAjivSgIAAUwACGF
+ * 0080: 6B 5A 48 4A 55 65 58 42 6C 64 41 41 53 54 47 70 kZHJUeXBldAASTGp
+ * 0090: 68 64 6D 45 76 62 47 46 75 0A 5A 79 39 54 64 48 hdmEvbGFu.Zy9TdH <
+ * 00A0: 4A 70 62 6D 63 37 65 48 42 30 41 41 52 30 5A 58 Jpbmc7eHB0AAR0ZX
+ * 00B0: 4E 30 64 58 49 41 41 6C 74 43 72 50 4D 58 2B 41 N0dXIAAltCrPMX+A
+ * 00C0: 59 49 56 4F 41 43 41 41 42 34 63 41 41 41 41 49 YIVOACAAB4cAAAAI
+ * 00D0: 41 41 41 51 49 44 42 41 55 47 42 77 67 4A 43 67 AAAQIDBAUGBwgJCg
+ * 00E0: 73 4D 44 51 34 50 0A 45 42 45 53 45 78 51 56 46 sMDQ4P.EBESExQVF <
+ * 00F0: 68 63 59 47 52 6F 62 48 42 30 65 48 79 41 68 49 hcYGRobHB0eHyAhI
+ * 0100: 69 4D 6B 4A 53 59 6E 4B 43 6B 71 4B 79 77 74 4C iMkJSYnKCkqKywtL
+ * 0110: 69 38 77 4D 54 49 7A 4E 44 55 32 4E 7A 67 35 4F i8wMTIzNDU2Nzg5O
+ * 0120: 6A 73 38 50 54 34 2F 51 45 46 43 51 30 52 46 52 js8PT4/QEFCQ0RFR
+ * 0130: 6B 64 49 0A 53 55 70 4C 54 45 31 4F 54 31 42 52 kdI.SUpLTE1OT1BR <
+ * 0140: 55 6C 4E 55 56 56 5A 58 57 46 6C 61 57 31 78 64 UlNUVVZXWFlaW1xd
+ * 0150: 58 6C 39 67 59 57 4A 6A 5A 47 56 6D 5A 32 68 70 Xl9gYWJjZGVmZ2hp
+ * 0160: 61 6D 74 73 62 57 35 76 63 48 46 79 63 33 52 31 amtsbW5vcHFyc3R1
+ * 0170: 64 6E 64 34 65 58 70 37 66 48 31 2B 66 77 3D 3D dnd4eXp7fH1+fw==
+ * 0180: 0A <
+ */
+ private static final String OLD_ENCODING = "rO0ABXNyABpqYXZheC5uYW1pbmcuQmluYXJ5UmVmQWRkctCak7Les4hHAgABWwADYnVmdAACW0J4\ncgAUamF2YXgubmFtaW5nLlJlZkFkZHLroAeaAjivSgIAAUwACGFkZHJUeXBldAASTGphdmEvbGFu\nZy9TdHJpbmc7eHB0AAR0ZXN0dXIAAltCrPMX+AYIVOACAAB4cAAAAIAAAQIDBAUGBwgJCgsMDQ4P\nEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdI\nSUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+fw==\n";
+
+ /*
+ * The new Base64 encoding uses '\r\n' as the line separator at 76 character
+ * intervals:
+ *
+ * 0000: 72 4F 30 41 42 58 4E 79 41 42 70 71 59 58 5A 68 rO0ABXNyABpqYXZh
+ * 0010: 65 43 35 75 59 57 31 70 62 6D 63 75 51 6D 6C 75 eC5uYW1pbmcuQmlu
+ * 0020: 59 58 4A 35 55 6D 56 6D 51 57 52 6B 63 74 43 61 YXJ5UmVmQWRkctCa
+ * 0030: 6B 37 4C 65 73 34 68 48 41 67 41 42 57 77 41 44 k7Les4hHAgABWwAD
+ * 0040: 59 6E 56 6D 64 41 41 43 57 30 4A 34 0D 0A 63 67 YnVmdAACW0J4..cg <
+ * 0050: 41 55 61 6D 46 32 59 58 67 75 62 6D 46 74 61 57 AUamF2YXgubmFtaW
+ * 0060: 35 6E 4C 6C 4A 6C 5A 6B 46 6B 5A 48 4C 72 6F 41 5nLlJlZkFkZHLroA
+ * 0070: 65 61 41 6A 69 76 53 67 49 41 41 55 77 41 43 47 eaAjivSgIAAUwACG
+ * 0080: 46 6B 5A 48 4A 55 65 58 42 6C 64 41 41 53 54 47 FkZHJUeXBldAASTG
+ * 0090: 70 68 64 6D 45 76 62 47 46 75 0D 0A 5A 79 39 54 phdmEvbGFu..Zy9T <
+ * 00A0: 64 48 4A 70 62 6D 63 37 65 48 42 30 41 41 52 30 dHJpbmc7eHB0AAR0
+ * 00B0: 5A 58 4E 30 64 58 49 41 41 6C 74 43 72 50 4D 58 ZXN0dXIAAltCrPMX
+ * 00C0: 2B 41 59 49 56 4F 41 43 41 41 42 34 63 41 41 41 +AYIVOACAAB4cAAA
+ * 00D0: 41 49 41 41 41 51 49 44 42 41 55 47 42 77 67 4A AIAAAQIDBAUGBwgJ
+ * 00E0: 43 67 73 4D 44 51 34 50 0D 0A 45 42 45 53 45 78 CgsMDQ4P..EBESEx <
+ * 00F0: 51 56 46 68 63 59 47 52 6F 62 48 42 30 65 48 79 QVFhcYGRobHB0eHy
+ * 0100: 41 68 49 69 4D 6B 4A 53 59 6E 4B 43 6B 71 4B 79 AhIiMkJSYnKCkqKy
+ * 0110: 77 74 4C 69 38 77 4D 54 49 7A 4E 44 55 32 4E 7A wtLi8wMTIzNDU2Nz
+ * 0120: 67 35 4F 6A 73 38 50 54 34 2F 51 45 46 43 51 30 g5Ojs8PT4/QEFCQ0
+ * 0130: 52 46 52 6B 64 49 0D 0A 53 55 70 4C 54 45 31 4F RFRkdI..SUpLTE1O <
+ * 0140: 54 31 42 52 55 6C 4E 55 56 56 5A 58 57 46 6C 61 T1BRUlNUVVZXWFla
+ * 0150: 57 31 78 64 58 6C 39 67 59 57 4A 6A 5A 47 56 6D W1xdXl9gYWJjZGVm
+ * 0160: 5A 32 68 70 61 6D 74 73 62 57 35 76 63 48 46 79 Z2hpamtsbW5vcHFy
+ * 0170: 63 33 52 31 64 6E 64 34 65 58 70 37 66 48 31 2B c3R1dnd4eXp7fH1+
+ * 0180: 66 77 3D 3D
+ */
+ private static final String NEW_ENCODING = "rO0ABXNyABpqYXZheC5uYW1pbmcuQmluYXJ5UmVmQWRkctCak7Les4hHAgABWwADYnVmdAACW0J4\r\ncgAUamF2YXgubmFtaW5nLlJlZkFkZHLroAeaAjivSgIAAUwACGFkZHJUeXBldAASTGphdmEvbGFu\r\nZy9TdHJpbmc7eHB0AAR0ZXN0dXIAAltCrPMX+AYIVOACAAB4cAAAAIAAAQIDBAUGBwgJCgsMDQ4P\r\nEBESExQVFhcYGRobHB0eHyAhIiMkJSYnKCkqKywtLi8wMTIzNDU2Nzg5Ojs8PT4/QEFCQ0RFRkdI\r\nSUpLTE1OT1BRUlNUVVZXWFlaW1xdXl9gYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXp7fH1+fw==";
+
+ /*
+ * Binary-valued JNDI RefAddr test object
+ */
+ private static final RefAddr BINARY_REF_ADDR =
+ new BinaryRefAddr("test", new byte[] {
+ 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B,
+ 0x0C, 0x0D, 0x0E, 0x0F, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
+ 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, 0x20, 0x21, 0x22, 0x23,
+ 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F,
+ 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3A, 0x3B,
+ 0x3C, 0x3D, 0x3E, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
+ 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x4F, 0x50, 0x51, 0x52, 0x53,
+ 0x54, 0x55, 0x56, 0x57, 0x58, 0x59, 0x5A, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F,
+ 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x6A, 0x6B,
+ 0x6C, 0x6D, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
+ 0x78, 0x79, 0x7A, 0x7B, 0x7C, 0x7D, 0x7E, 0x7F
+ });
+
+ public static void main(String[] args) throws Exception {
+
+ System.out.println("\nOriginal RefAddr object:\n" + BINARY_REF_ADDR);
+ System.out.println("Old Base64 encoded serialized RefAddr object:\n" +
+ OLD_ENCODING);
+ System.out.println("Decode using old Base64 decoder...");
+ deserialize(new BASE64Decoder().decodeBuffer(OLD_ENCODING));
+
+ System.out.println("----");
+
+ System.out.println("\nOriginal RefAddr object:\n" + BINARY_REF_ADDR);
+ System.out.println("Old Base64 encoded serialized RefAddr object:\n" +
+ OLD_ENCODING);
+ System.out.println("Decode using new Base64 decoder...");
+ deserialize(new BASE64Decoder().decodeBuffer(OLD_ENCODING));
+
+ System.out.println("----");
+
+ System.out.println("\nOriginal RefAddr object:\n" + BINARY_REF_ADDR);
+ System.out.println("New Base64 encoded serialized RefAddr object:\n" +
+ NEW_ENCODING + "\n");
+ System.out.println("Decode using old Base64 decoder...");
+ deserialize(new BASE64Decoder().decodeBuffer(OLD_ENCODING));
+
+ System.out.println("----");
+
+ System.out.println("\nOriginal RefAddr object:\n" + BINARY_REF_ADDR);
+ System.out.println("New Base64 encoded serialized RefAddr object:\n" +
+ NEW_ENCODING + "\n");
+ System.out.println("Decode using new Base64 decoder...");
+ deserialize(Base64.getMimeDecoder().decode(NEW_ENCODING));
+
+ System.out.println("----");
+ }
+
+ /*
+ * Deserialize the decoded Base64 bytes to recover the BinaryRefAddr object.
+ */
+ private static void deserialize(byte[] bytes) throws Exception {
+
+ //System.out.println("\nSerialized RefAddr object: ");
+ //System.out.println(new sun.misc.HexDumpEncoder().encode(bytes));
+
+ ObjectInputStream objectStream =
+ new ObjectInputStream(new ByteArrayInputStream(bytes));
+ Object object = objectStream.readObject();
+ if (!BINARY_REF_ADDR.equals(object)) {
+ throw new Exception("Recovered object does not match the original");
+ }
+ System.out.println("Recovered RefAddr object:\n" + object);
+ }
+
+ /*
+ * Dumps the encoding of a JNDI Reference object during an attempt to store
+ * in an LDAP directory.
+ */
+ private static void storeObjectInLDAP() {
+ Hashtable env = new Hashtable();
+ env.put(Context.REFERRAL, "follow"); // omit an LDAP control
+ env.put("java.naming.ldap.version", "3"); // omit LDAP bind operation
+ env.put("com.sun.jndi.ldap.trace.ber", System.err); // dump protocol
+ try {
+ DirContext ctx = new InitialDirContext(env);
+ Reference reference = new Reference("test", BINARY_REF_ADDR);
+ ctx.bind("ldap://ldap.example.com/cn=test", reference);
+ } catch (NamingException ignore) {
+ }
+ }
+}
diff --git a/jdk/test/com/sun/nio/sctp/SctpChannel/SocketOptionTests.java b/jdk/test/com/sun/nio/sctp/SctpChannel/SocketOptionTests.java
index df1cbcc5550..af0aed0435d 100644
--- a/jdk/test/com/sun/nio/sctp/SctpChannel/SocketOptionTests.java
+++ b/jdk/test/com/sun/nio/sctp/SctpChannel/SocketOptionTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,13 +39,13 @@ import com.sun.nio.sctp.SctpChannel;
import com.sun.nio.sctp.SctpServerChannel;
import com.sun.nio.sctp.SctpSocketOption;
import java.security.AccessController;
-import sun.security.action.GetPropertyAction;
+import java.security.PrivilegedAction;
import static com.sun.nio.sctp.SctpStandardSocketOptions.*;
import static java.lang.System.out;
public class SocketOptionTests {
final String osName = AccessController.doPrivileged(
- new GetPropertyAction("os.name"));
+ (PrivilegedAction)() -> System.getProperty("os.name"));
void checkOption(SctpChannel sc, SctpSocketOption name,
T expectedValue) throws IOException {
diff --git a/jdk/test/com/sun/nio/sctp/SctpMultiChannel/SocketOptionTests.java b/jdk/test/com/sun/nio/sctp/SctpMultiChannel/SocketOptionTests.java
index 8f7c6fcb8b6..250bf4c4d0a 100644
--- a/jdk/test/com/sun/nio/sctp/SctpMultiChannel/SocketOptionTests.java
+++ b/jdk/test/com/sun/nio/sctp/SctpMultiChannel/SocketOptionTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -47,13 +47,13 @@ import com.sun.nio.sctp.SctpMultiChannel;
import com.sun.nio.sctp.SctpServerChannel;
import com.sun.nio.sctp.SctpSocketOption;
import java.security.AccessController;
-import sun.security.action.GetPropertyAction;
+import java.security.PrivilegedAction;
import static com.sun.nio.sctp.SctpStandardSocketOptions.*;
import static java.lang.System.out;
public class SocketOptionTests {
final String osName = AccessController.doPrivileged(
- new GetPropertyAction("os.name"));
+ (PrivilegedAction)() -> System.getProperty("os.name"));
void checkOption(SctpMultiChannel smc, SctpSocketOption name,
T expectedValue) throws IOException {
diff --git a/jdk/test/demo/zipfs/basic.sh b/jdk/test/demo/zipfs/basic.sh
deleted file mode 100644
index 842f0e65389..00000000000
--- a/jdk/test/demo/zipfs/basic.sh
+++ /dev/null
@@ -1,74 +0,0 @@
-#
-# Copyright (c) 2009, 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.
-#
-# @test
-# @bug 6990846 7009092 7009085 7015391 7014948 7005986 7017840 7007596
-# 7157656 8002390 7012868 7012856 8015728
-# @summary Test ZipFileSystem demo
-# @build Basic PathOps ZipFSTester
-# @run shell basic.sh
-
-if [ -z "${TESTJAVA}" ]; then
- echo "Test must be run with jtreg"
- exit 0
-fi
-
-ZIPFS="${TESTJAVA}/demo/nio/zipfs/zipfs.jar"
-if [ ! -r "${ZIPFS}" ]; then
- echo "${ZIPFS} not found"
- exit 0
-fi
-
-OS=`uname -s`
-case "$OS" in
- Windows_* | CYGWIN* )
- CLASSPATH="${TESTCLASSES};${ZIPFS}"
- ;;
- * )
- CLASSPATH="${TESTCLASSES}:${ZIPFS}"
- ;;
-esac
-export CLASSPATH
-
-failures=0
-
-go() {
- echo ""
- ${TESTJAVA}/bin/java ${TESTVMOPTS} $1 $2 $3 2>&1
- if [ $? != 0 ]; then failures=`expr $failures + 1`; fi
-}
-
-# Run the tests
-
-go Basic "${ZIPFS}"
-go PathOps "${ZIPFS}"
-go ZipFSTester "${ZIPFS}"
-
-#
-# Results
-#
-
-if [ $failures -gt 0 ];
-then echo "$failures tests failed";
-else echo "All tests passed";
-fi
-exit $failures
diff --git a/jdk/test/java/awt/Toolkit/LoadAWTCrashTest/LoadAWTCrashTest.java b/jdk/test/java/awt/Toolkit/LoadAWTCrashTest/LoadAWTCrashTest.java
new file mode 100644
index 00000000000..27ca3f4051c
--- /dev/null
+++ b/jdk/test/java/awt/Toolkit/LoadAWTCrashTest/LoadAWTCrashTest.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ @test
+ @bug 8031477
+ @summary Crash while awt starting
+ @author Petr Pchelko
+ @run main/othervm LoadAWTCrashTest
+*/
+
+public class LoadAWTCrashTest {
+ public static void main(String[] args) {
+ System.loadLibrary("awt");
+ // If the bug is present JVM would crash or deadlock
+ }
+}
diff --git a/jdk/test/java/awt/font/TextLayout/TestAATMorxFont.java b/jdk/test/java/awt/font/TextLayout/TestAATMorxFont.java
new file mode 100644
index 00000000000..7cee2f8532f
--- /dev/null
+++ b/jdk/test/java/awt/font/TextLayout/TestAATMorxFont.java
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/* @test
+ * @summary verify rendering of MORX fonts on OS X.
+ * @bug 8031462
+ */
+
+import javax.swing.*;
+import javax.swing.border.LineBorder;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+
+public class TestAATMorxFont extends JComponent {
+ public static void main(String[] args) {
+ String osName = System.getProperty("os.name");
+ System.out.println("OS is " + osName);
+ osName = osName.toLowerCase();
+ if (!osName.startsWith("mac")) {
+ return;
+ }
+ SwingUtilities.invokeLater(new Runnable() {
+ public void run() {
+ JFrame frame = new JFrame("Test Morx");
+ frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
+ TestAATMorxFont panel = new TestAATMorxFont();
+ frame.add(panel);
+ frame.pack();
+ frame.setVisible(true);
+ }
+ });
+ }
+
+ public Dimension getPreferredSize() {
+ return new Dimension(1200, 400);
+ }
+
+ public void paintComponent(Graphics g) {
+ Graphics2D g2d = (Graphics2D)g;
+ g2d.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+ RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+ int y = 50;
+ g.setFont(new Font("Gujarati MT", Font.PLAIN, 40));
+ System.out.println(g.getFont());
+ g.drawString("\u0A95\u0ACD \u0A95\u0A95\u0A95 \u0A95\u0ACD\u0A95\u0ACD\u0A95", 20, y);
+ y += 50;
+ g.setFont(new Font("Tamil Sangam MN", Font.PLAIN, 40));
+ System.out.println(g.getFont());
+ g.drawString("\u0b95\u0bCD \u0b95\u0b95\u0b95 \u0b95\u0bCD\u0b95\u0bCD\u0b95", 20, y);
+ y += 50;
+ g.setFont(new Font("Telugu Sangam MN", Font.PLAIN, 40));
+ System.out.println(g.getFont());
+ g.drawString("\u0c15\u0c4D \u0c15\u0c15\u0c15 \u0c15\u0c4D\u0c15\u0c4D\u0c15", 20, y);
+ y += 50;
+ g.setFont(new Font("Devanagari Sangam MN", Font.PLAIN, 40));
+ System.out.println(g.getFont());
+ g.drawString("\u0915\u0940 \u0915\u0947 \u0915\u0942", 20, y);
+ y += 50;
+ g.drawString("\u0907\u0930\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915", 20, y);
+ y += 50;
+ g.drawString("\u0930\u093F\u0935\u094D\u092F\u0942 \u0915\u0947 \u092C\u093E\u0926 \u0935\u093F\u0915\u093E\u0938 \u0913\u0932\u0902\u092A\u093F\u0915 \u0938\u0947 \u092C\u093E\u0939\u0930 (\u0926\u0947\u0935\u0928\u093E\u0917\u0930\u0940) (\u0939\u093F\u0928\u094D\u0926\u0940) \u0907\u0930\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915\u094D\u0915", 20, y);
+
+ }
+}
+
diff --git a/jdk/test/java/io/Serializable/unresolvableObjectStreamClass/UnresolvableObjectStreamClass.java b/jdk/test/java/io/Serializable/unresolvableObjectStreamClass/UnresolvableObjectStreamClass.java
new file mode 100644
index 00000000000..4010b1a76fa
--- /dev/null
+++ b/jdk/test/java/io/Serializable/unresolvableObjectStreamClass/UnresolvableObjectStreamClass.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test
+ * @bug 8039396
+ * @run main UnresolvableObjectStreamClass serialize
+ * @clean MySerializable
+ * @run main UnresolvableObjectStreamClass deserialize
+ *
+ * @summary NPE when writing a class descriptor object to a custom
+ * ObjectOutputStream
+ */
+
+import java.io.*;
+
+public class UnresolvableObjectStreamClass {
+ public static void main(String[] args) throws Throwable {
+ if (args.length > 0 && args[0].equals("serialize")) {
+ try (FileOutputStream fos = new FileOutputStream("temp1.ser");
+ ObjectOutputStream oos = new ObjectOutputStream(fos)) {
+ ObjectStreamClass osc =
+ ObjectStreamClass.lookup(MySerializable.class);
+ oos.writeObject(osc);
+ }
+ } else if (args.length > 0 && args[0].equals("deserialize")) {
+ try (FileInputStream fis = new FileInputStream("temp1.ser");
+ ObjectInputStream ois = new ObjectInputStream(fis);
+ FileOutputStream fos = new FileOutputStream("temp2.ser");
+ ObjectOutputStream oos = new ObjectOutputStream(fos) {
+ /*must be subclassed*/}) {
+ ObjectStreamClass osc = (ObjectStreamClass)ois.readObject();
+ // serialize it again
+ try {
+ oos.writeObject(osc);
+ } catch (NullPointerException e) {
+ throw new RuntimeException("Failed to write" +
+ " unresolvable ObjectStreamClass", e);
+ }
+ }
+ } else {
+ throw new RuntimeException("The command line option must be" +
+ " one of: serialize or deserialize");
+ }
+ }
+}
+
+class MySerializable implements Serializable {
+}
diff --git a/jdk/test/java/lang/StringCoding/Enormous.java b/jdk/test/java/lang/StringCoding/Enormous.java
index 5f5066c681f..d05e5a349d1 100644
--- a/jdk/test/java/lang/StringCoding/Enormous.java
+++ b/jdk/test/java/lang/StringCoding/Enormous.java
@@ -34,6 +34,6 @@ public class Enormous {
new String(bytes,"ASCII");
// Another manifestation of this bug, reported in bug 6192102.
- new sun.misc.BASE64Encoder().encode(bytes);
+ java.util.Base64.getEncoder().encodeToString(bytes);
}
}
diff --git a/jdk/test/java/lang/annotation/AnnotationType/AnnotationTypeRuntimeAssumptionTest.java b/jdk/test/java/lang/annotation/AnnotationType/AnnotationTypeRuntimeAssumptionTest.java
index 2d79c61bc3c..32589256c59 100644
--- a/jdk/test/java/lang/annotation/AnnotationType/AnnotationTypeRuntimeAssumptionTest.java
+++ b/jdk/test/java/lang/annotation/AnnotationType/AnnotationTypeRuntimeAssumptionTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,15 +25,18 @@
* @test
* @summary Test consistent parsing of ex-RUNTIME annotations that
* were changed and separately compiled to have CLASS retention
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.IOUtils
+ * @run main AnnotationTypeRuntimeAssumptionTest
*/
-import sun.misc.IOUtils;
-
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
+import jdk.testlibrary.IOUtils;
+
import static java.lang.annotation.RetentionPolicy.CLASS;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
@@ -137,7 +140,7 @@ public class AnnotationTypeRuntimeAssumptionTest {
String altPath = altName.replace('.', '/').concat(".class");
try (InputStream is = getResourceAsStream(altPath)) {
if (is != null) {
- byte[] bytes = IOUtils.readFully(is, -1, true);
+ byte[] bytes = IOUtils.readFully(is);
// patch class bytes to contain original name
for (int i = 0; i < bytes.length - 2; i++) {
if (bytes[i] == '_' &&
@@ -160,7 +163,7 @@ public class AnnotationTypeRuntimeAssumptionTest {
String path = name.replace('.', '/').concat(".class");
try (InputStream is = getResourceAsStream(path)) {
if (is != null) {
- byte[] bytes = IOUtils.readFully(is, -1, true);
+ byte[] bytes = IOUtils.readFully(is);
return defineClass(name, bytes, 0, bytes.length);
}
else {
diff --git a/jdk/test/java/lang/invoke/lambda/LambdaClassLoaderSerialization.java b/jdk/test/java/lang/invoke/lambda/LambdaClassLoaderSerialization.java
index 9d38102b14a..6c97e3407cb 100644
--- a/jdk/test/java/lang/invoke/lambda/LambdaClassLoaderSerialization.java
+++ b/jdk/test/java/lang/invoke/lambda/LambdaClassLoaderSerialization.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -22,11 +22,14 @@
*/
/*
-@test
-@bug 8004970
-@summary Lambda serialization in the presence of class loaders
-@author Peter Levart
-*/
+ * @test
+ * @bug 8004970
+ * @summary Lambda serialization in the presence of class loaders
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.IOUtils
+ * @run main LambdaClassLoaderSerialization
+ * @author Peter Levart
+ */
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -37,6 +40,8 @@ import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Arrays;
+import jdk.testlibrary.IOUtils;
+
public class LambdaClassLoaderSerialization {
public interface SerializableRunnable extends Runnable, Serializable {}
@@ -125,7 +130,7 @@ public class LambdaClassLoaderSerialization {
String path = name.replace('.', '/').concat(".class");
try (InputStream is = getResourceAsStream(path)) {
if (is != null) {
- byte[] bytes = readFully(is);
+ byte[] bytes = IOUtils.readFully(is);
return defineClass(name, bytes, 0, bytes.length);
} else {
throw new ClassNotFoundException(name);
@@ -135,30 +140,5 @@ public class LambdaClassLoaderSerialization {
throw new ClassNotFoundException(name, e);
}
}
-
- static byte[] readFully(InputStream is) throws IOException {
- byte[] output = {};
- int pos = 0;
- while (true) {
- int bytesToRead;
- if (pos >= output.length) { // Only expand when there's no room
- bytesToRead = output.length + 1024;
- if (output.length < pos + bytesToRead) {
- output = Arrays.copyOf(output, pos + bytesToRead);
- }
- } else {
- bytesToRead = output.length - pos;
- }
- int cc = is.read(output, pos, bytesToRead);
- if (cc < 0) {
- if (output.length != pos) {
- output = Arrays.copyOf(output, pos);
- }
- break;
- }
- pos += cc;
- }
- return output;
- }
}
}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java
index 42ae7d05ab1..1309e9c3949 100644
--- a/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java
+++ b/jdk/test/java/lang/management/MemoryMXBean/CollectionUsageThreshold.java
@@ -30,11 +30,9 @@
*
* @author Mandy Chung
*
- * @build CollectionUsageThreshold MemoryUtil
- * @run main/othervm/timeout=300 -XX:+PrintGCDetails -XX:+UseSerialGC CollectionUsageThreshold
- * @run main/othervm/timeout=300 -XX:+PrintGCDetails -XX:+UseParallelGC CollectionUsageThreshold
- * @run main/othervm/timeout=300 -XX:+PrintGCDetails -XX:+UseG1GC CollectionUsageThreshold
- * @run main/othervm/timeout=300 -XX:+PrintGCDetails -XX:+UseConcMarkSweepGC CollectionUsageThreshold
+ * @library /lib/testlibrary/
+ * @build CollectionUsageThreshold MemoryUtil RunUtil
+ * @run main/timeout=300 CollectionUsageThreshold
*/
import java.util.*;
@@ -61,6 +59,20 @@ public class CollectionUsageThreshold {
// finishes checking the low memory notification result
private static final CyclicBarrier barrier = new CyclicBarrier(2);
+ /**
+ * Run the test multiple times with different GC versions.
+ * First with default command line specified by the framework.
+ * Then with GC versions specified by the test.
+ */
+ public static void main(String a[]) throws Throwable {
+ final String main = "CollectionUsageThreshold$TestMain";
+ RunUtil.runTestKeepGcOpts(main);
+ RunUtil.runTestClearGcOpts(main, "-XX:+UseSerialGC");
+ RunUtil.runTestClearGcOpts(main, "-XX:+UseParallelGC");
+ RunUtil.runTestClearGcOpts(main, "-XX:+UseG1GC");
+ RunUtil.runTestClearGcOpts(main, "-XX:+UseConcMarkSweepGC");
+ }
+
static class PoolRecord {
private final MemoryPoolMXBean pool;
private final AtomicInteger listenerInvoked = new AtomicInteger(0);
@@ -110,88 +122,90 @@ public class CollectionUsageThreshold {
}
}
- public static void main(String args[]) throws Exception {
- if (args.length > 0 && args[0].equals("trace")) {
- trace = true;
- }
+ private static class TestMain {
+ public static void main(String args[]) throws Exception {
+ if (args.length > 0 && args[0].equals("trace")) {
+ trace = true;
+ }
- List pools = getMemoryPoolMXBeans();
- List managers = getMemoryManagerMXBeans();
+ List pools = getMemoryPoolMXBeans();
+ List managers = getMemoryManagerMXBeans();
- if (trace) {
- MemoryUtil.printMemoryPools(pools);
- MemoryUtil.printMemoryManagers(managers);
- }
+ if (trace) {
+ MemoryUtil.printMemoryPools(pools);
+ MemoryUtil.printMemoryManagers(managers);
+ }
- // Find the Old generation which supports low memory detection
- for (MemoryPoolMXBean p : pools) {
- if (p.isUsageThresholdSupported() && p.isCollectionUsageThresholdSupported()) {
- if (p.getName().toLowerCase().contains("perm")) {
- // if we have a "perm gen" pool increase the number of expected
- // memory pools by one.
- numMemoryPools++;
- }
- PoolRecord pr = new PoolRecord(p);
- result.put(p.getName(), pr);
- if (result.size() == numMemoryPools) {
- break;
+ // Find the Old generation which supports low memory detection
+ for (MemoryPoolMXBean p : pools) {
+ if (p.isUsageThresholdSupported() && p.isCollectionUsageThresholdSupported()) {
+ if (p.getName().toLowerCase().contains("perm")) {
+ // if we have a "perm gen" pool increase the number of expected
+ // memory pools by one.
+ numMemoryPools++;
+ }
+ PoolRecord pr = new PoolRecord(p);
+ result.put(p.getName(), pr);
+ if (result.size() == numMemoryPools) {
+ break;
+ }
}
}
- }
- if (result.size() != numMemoryPools) {
- throw new RuntimeException("Unexpected number of selected pools");
- }
-
- try {
- // This test creates a checker thread responsible for checking
- // the low memory notifications. It blocks until a permit
- // from the signals semaphore is available.
- Checker checker = new Checker("Checker thread");
- checker.setDaemon(true);
- checker.start();
-
- for (PoolRecord pr : result.values()) {
- pr.getPool().setCollectionUsageThreshold(THRESHOLD);
- System.out.println("Collection usage threshold of " +
- pr.getPool().getName() + " set to " + THRESHOLD);
+ if (result.size() != numMemoryPools) {
+ throw new RuntimeException("Unexpected number of selected pools");
}
- SensorListener listener = new SensorListener();
- NotificationEmitter emitter = (NotificationEmitter) mm;
- emitter.addNotificationListener(listener, null, null);
+ try {
+ // This test creates a checker thread responsible for checking
+ // the low memory notifications. It blocks until a permit
+ // from the signals semaphore is available.
+ Checker checker = new Checker("Checker thread");
+ checker.setDaemon(true);
+ checker.start();
- // The main thread invokes GC to trigger the VM to perform
- // low memory detection and then waits until the checker thread
- // finishes its work to check for a low-memory notification.
- //
- // At GC time, VM will issue low-memory notification and invoke
- // the listener which will release a permit to the signals semaphore.
- // When the checker thread acquires the permit and finishes
- // checking the low-memory notification, it will also call
- // barrier.await() to signal the main thread to resume its work.
- for (int i = 0; i < NUM_GCS; i++) {
- invokeGC();
- barrier.await();
- }
- } finally {
- // restore the default
- for (PoolRecord pr : result.values()) {
- pr.getPool().setCollectionUsageThreshold(0);
+ for (PoolRecord pr : result.values()) {
+ pr.getPool().setCollectionUsageThreshold(THRESHOLD);
+ System.out.println("Collection usage threshold of " +
+ pr.getPool().getName() + " set to " + THRESHOLD);
+ }
+
+ SensorListener listener = new SensorListener();
+ NotificationEmitter emitter = (NotificationEmitter) mm;
+ emitter.addNotificationListener(listener, null, null);
+
+ // The main thread invokes GC to trigger the VM to perform
+ // low memory detection and then waits until the checker thread
+ // finishes its work to check for a low-memory notification.
+ //
+ // At GC time, VM will issue low-memory notification and invoke
+ // the listener which will release a permit to the signals semaphore.
+ // When the checker thread acquires the permit and finishes
+ // checking the low-memory notification, it will also call
+ // barrier.await() to signal the main thread to resume its work.
+ for (int i = 0; i < NUM_GCS; i++) {
+ invokeGC();
+ barrier.await();
+ }
+ } finally {
+ // restore the default
+ for (PoolRecord pr : result.values()) {
+ pr.getPool().setCollectionUsageThreshold(0);
+ }
}
+ System.out.println(RunUtil.successMessage);
}
- System.out.println("Test passed.");
- }
- private static void invokeGC() {
- System.out.println("Calling System.gc()");
- numGCs++;
- mm.gc();
+ private static void invokeGC() {
+ System.out.println("Calling System.gc()");
+ numGCs++;
+ mm.gc();
- if (trace) {
- for (PoolRecord pr : result.values()) {
- System.out.println("Usage after GC for: " + pr.getPool().getName());
- MemoryUtil.printMemoryUsage(pr.getPool().getUsage());
+ if (trace) {
+ for (PoolRecord pr : result.values()) {
+ System.out.println("Usage after GC for: " + pr.getPool().getName());
+ MemoryUtil.printMemoryUsage(pr.getPool().getUsage());
+ }
}
}
}
diff --git a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java
index fedb3aa655d..379b1293060 100644
--- a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java
@@ -30,11 +30,9 @@
*
* @author Mandy Chung
*
- * @build LowMemoryTest MemoryUtil
- * @run main/othervm/timeout=600 LowMemoryTest
- * @run main/othervm/timeout=600 -XX:+UseConcMarkSweepGC LowMemoryTest
- * @run main/othervm/timeout=600 -XX:+UseParallelGC LowMemoryTest
- * @run main/othervm/timeout=600 -XX:+UseSerialGC LowMemoryTest
+ * @library /lib/testlibrary/
+ * @build LowMemoryTest MemoryUtil RunUtil
+ * @run main/timeout=600 LowMemoryTest
*/
import java.lang.management.*;
@@ -54,6 +52,20 @@ public class LowMemoryTest {
private static final int NUM_CHUNKS = 2;
private static long chunkSize;
+ /**
+ * Run the test multiple times with different GC versions.
+ * First with default command line specified by the framework.
+ * Then with GC versions specified by the test.
+ */
+ public static void main(String a[]) throws Throwable {
+ final String main = "LowMemoryTest$TestMain";
+ RunUtil.runTestKeepGcOpts(main);
+ RunUtil.runTestClearGcOpts(main, "-XX:+UseSerialGC");
+ RunUtil.runTestClearGcOpts(main, "-XX:+UseParallelGC");
+ RunUtil.runTestClearGcOpts(main, "-XX:+UseG1GC");
+ RunUtil.runTestClearGcOpts(main, "-XX:+UseConcMarkSweepGC");
+ }
+
private static volatile boolean listenerInvoked = false;
static class SensorListener implements NotificationListener {
@Override
@@ -107,77 +119,80 @@ public class LowMemoryTest {
}
private static long newThreshold;
- public static void main(String args[]) throws Exception {
- if (args.length > 0 && args[0].equals("trace")) {
- trace = true;
- }
- // Find the Old generation which supports low memory detection
- ListIterator iter = pools.listIterator();
- while (iter.hasNext()) {
- MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
- if (p.getType() == MemoryType.HEAP &&
- p.isUsageThresholdSupported()) {
- mpool = p;
- if (trace) {
- System.out.println("Selected memory pool for low memory " +
- "detection.");
- MemoryUtil.printMemoryPool(mpool);
- }
- break;
+ private static class TestMain {
+ public static void main(String args[]) throws Exception {
+ if (args.length > 0 && args[0].equals("trace")) {
+ trace = true;
}
- }
- TestListener listener = new TestListener();
- SensorListener l2 = new SensorListener();
- NotificationEmitter emitter = (NotificationEmitter) mm;
- emitter.addNotificationListener(listener, null, null);
- emitter.addNotificationListener(l2, null, null);
+ // Find the Old generation which supports low memory detection
+ ListIterator iter = pools.listIterator();
+ while (iter.hasNext()) {
+ MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
+ if (p.getType() == MemoryType.HEAP &&
+ p.isUsageThresholdSupported()) {
+ mpool = p;
+ if (trace) {
+ System.out.println("Selected memory pool for low memory " +
+ "detection.");
+ MemoryUtil.printMemoryPool(mpool);
+ }
+ break;
+ }
+ }
- Thread allocator = new AllocatorThread();
- Thread sweeper = new SweeperThread();
+ TestListener listener = new TestListener();
+ SensorListener l2 = new SensorListener();
+ NotificationEmitter emitter = (NotificationEmitter) mm;
+ emitter.addNotificationListener(listener, null, null);
+ emitter.addNotificationListener(l2, null, null);
- // Now set threshold
- MemoryUsage mu = mpool.getUsage();
- chunkSize = (mu.getMax() - mu.getUsed()) / 20;
- newThreshold = mu.getUsed() + (chunkSize * NUM_CHUNKS);
+ Thread allocator = new AllocatorThread();
+ Thread sweeper = new SweeperThread();
- System.out.println("Setting threshold for " + mpool.getName() +
- " from " + mpool.getUsageThreshold() + " to " + newThreshold +
- ". Current used = " + mu.getUsed());
- mpool.setUsageThreshold(newThreshold);
+ // Now set threshold
+ MemoryUsage mu = mpool.getUsage();
+ chunkSize = (mu.getMax() - mu.getUsed()) / 20;
+ newThreshold = mu.getUsed() + (chunkSize * NUM_CHUNKS);
- if (mpool.getUsageThreshold() != newThreshold) {
- throw new RuntimeException("TEST FAILED: " +
+ System.out.println("Setting threshold for " + mpool.getName() +
+ " from " + mpool.getUsageThreshold() + " to " + newThreshold +
+ ". Current used = " + mu.getUsed());
+ mpool.setUsageThreshold(newThreshold);
+
+ if (mpool.getUsageThreshold() != newThreshold) {
+ throw new RuntimeException("TEST FAILED: " +
"Threshold for Memory pool " + mpool.getName() +
"is " + mpool.getUsageThreshold() + " but expected to be" +
newThreshold);
- }
+ }
- allocator.start();
- // Force Allocator start first
- phaser.arriveAndAwaitAdvance();
- sweeper.start();
-
-
- try {
- allocator.join();
- // Wait until AllocatorThread's done
+ allocator.start();
+ // Force Allocator start first
phaser.arriveAndAwaitAdvance();
- sweeper.join();
- } catch (InterruptedException e) {
- System.out.println("Unexpected exception:" + e);
- testFailed = true;
+ sweeper.start();
+
+
+ try {
+ allocator.join();
+ // Wait until AllocatorThread's done
+ phaser.arriveAndAwaitAdvance();
+ sweeper.join();
+ } catch (InterruptedException e) {
+ System.out.println("Unexpected exception:" + e);
+ testFailed = true;
+ }
+
+ listener.checkResult();
+
+ if (testFailed)
+ throw new RuntimeException("TEST FAILED.");
+
+ System.out.println(RunUtil.successMessage);
+
}
-
- listener.checkResult();
-
- if (testFailed)
- throw new RuntimeException("TEST FAILED.");
-
- System.out.println("Test passed.");
-
}
private static void goSleep(long ms) {
diff --git a/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java b/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java
index 312db6bb313..f15fd2b007d 100644
--- a/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java
+++ b/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java
@@ -32,11 +32,9 @@
* @summary Basic Test for MemoryPool.resetPeakUsage()
* @author Mandy Chung
*
- * @build ResetPeakMemoryUsage MemoryUtil
- * @run main/othervm -XX:+PrintGCDetails -XX:+UseSerialGC -Xms256m -XX:MarkSweepAlwaysCompactCount=1 -Xmn8m ResetPeakMemoryUsage
- * @run main/othervm -XX:+PrintGCDetails -XX:+UseConcMarkSweepGC -Xms256m -Xmn8m ResetPeakMemoryUsage
- * @run main/othervm -XX:+PrintGCDetails -XX:+UseParallelGC -Xms256m -Xmn8m ResetPeakMemoryUsage
- * @run main/othervm -XX:+PrintGCDetails -XX:+UseG1GC -Xms256m -Xmn8m -XX:G1HeapRegionSize=1m ResetPeakMemoryUsage
+ * @library /lib/testlibrary/
+ * @build ResetPeakMemoryUsage MemoryUtil RunUtil
+ * @run main ResetPeakMemoryUsage
*/
import java.lang.management.*;
@@ -47,24 +45,42 @@ public class ResetPeakMemoryUsage {
// make public so that it can't be optimized away easily
public static Object[] obj;
- public static void main(String[] argv) {
- List pools = ManagementFactory.getMemoryPoolMXBeans();
- ListIterator iter = pools.listIterator();
- boolean found = false;
- while (iter.hasNext()) {
- MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
- // only check heap pools that support usage threshold
- // this is typically only the old generation space
- // since the other spaces are expected to get filled up
- if (p.getType() == MemoryType.HEAP &&
- p.isUsageThresholdSupported())
- {
- found = true;
- testPool(p);
+ /**
+ * Run the test multiple times with different GC versions.
+ * First with default command line specified by the framework.
+ * Then with all GC versions specified by the test.
+ */
+ public static void main(String a[]) throws Throwable {
+ final String main = "ResetPeakMemoryUsage$TestMain";
+ final String ms = "-Xms256m";
+ final String mn = "-Xmn8m";
+ RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseConcMarkSweepGC");
+ RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseParallelGC");
+ RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseG1GC", "-XX:G1HeapRegionSize=1m");
+ RunUtil.runTestClearGcOpts(main, ms, mn, "-XX:+UseSerialGC",
+ "-XX:MarkSweepAlwaysCompactCount=1");
+ }
+
+ private static class TestMain {
+ public static void main(String[] argv) {
+ List pools = ManagementFactory.getMemoryPoolMXBeans();
+ ListIterator iter = pools.listIterator();
+ boolean found = false;
+ while (iter.hasNext()) {
+ MemoryPoolMXBean p = (MemoryPoolMXBean) iter.next();
+ // only check heap pools that support usage threshold
+ // this is typically only the old generation space
+ // since the other spaces are expected to get filled up
+ if (p.getType() == MemoryType.HEAP &&
+ p.isUsageThresholdSupported())
+ {
+ found = true;
+ testPool(p);
+ }
+ }
+ if (!found) {
+ throw new RuntimeException("No heap pool found");
}
- }
- if (!found) {
- throw new RuntimeException("No heap pool found");
}
}
@@ -142,7 +158,7 @@ public class ResetPeakMemoryUsage {
formatSize("previous peak", peak2.getUsed()));
}
- System.out.println("Test passed.");
+ System.out.println(RunUtil.successMessage);
}
private static String INDENT = " ";
diff --git a/jdk/test/java/lang/management/MemoryMXBean/RunUtil.java b/jdk/test/java/lang/management/MemoryMXBean/RunUtil.java
new file mode 100644
index 00000000000..5f9d07c1a00
--- /dev/null
+++ b/jdk/test/java/lang/management/MemoryMXBean/RunUtil.java
@@ -0,0 +1,84 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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.
+ */
+
+/**
+ * Utility class for launching a test in a separate JVM.
+ */
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Arrays;
+import jdk.testlibrary.OutputAnalyzer;
+import jdk.testlibrary.Utils;
+import jdk.testlibrary.ProcessTools;
+import jdk.testlibrary.JDKToolFinder;
+
+public class RunUtil {
+
+ // Used to mark that the test has passed successfully.
+ public static final String successMessage = "Test passed.";
+
+ public static void runTestClearGcOpts(String main, String... testOpts) throws Throwable {
+ runTest(main, true, testOpts);
+ }
+
+ public static void runTestKeepGcOpts(String main, String... testOpts) throws Throwable {
+ runTest(main, false, testOpts);
+ }
+
+ /**
+ * Runs a test in a separate JVM.
+ * command line like:
+ * {test_jdk}/bin/java {defaultopts} -cp {test.class.path} {testopts} main
+ *
+ * {defaultopts} are the default java options set by the framework.
+ * Default GC options in {defaultopts} may be removed.
+ * This is used when the test specifies its own GC options.
+ *
+ * @param main Name of the main class.
+ * @param clearGcOpts true if the default GC options should be removed.
+ * @param testOpts java options specified by the test.
+ */
+ private static void runTest(String main, boolean clearGcOpts, String... testOpts)
+ throws Throwable {
+ List opts = new ArrayList<>();
+ opts.add(JDKToolFinder.getJDKTool("java"));
+ opts.addAll(Arrays.asList(Utils.getTestJavaOpts()));
+ opts.add("-cp");
+ opts.add(System.getProperty("test.class.path", "test.class.path"));
+ opts.add("-XX:+PrintGCDetails");
+
+ if (clearGcOpts) {
+ opts = Utils.removeGcOpts(opts);
+ }
+ opts.addAll(Arrays.asList(testOpts));
+ opts.add(main);
+
+ OutputAnalyzer output = ProcessTools.executeProcess(opts.toArray(new String[0]));
+ output.shouldHaveExitValue(0);
+ if (output.getStdout().indexOf(successMessage) < 0) {
+ throw new Exception("output missing '" + successMessage + "'");
+ }
+ }
+
+}
diff --git a/jdk/test/java/lang/ref/EarlyTimeout.java b/jdk/test/java/lang/ref/EarlyTimeout.java
index cbbc269ad90..d1037257107 100644
--- a/jdk/test/java/lang/ref/EarlyTimeout.java
+++ b/jdk/test/java/lang/ref/EarlyTimeout.java
@@ -33,6 +33,7 @@ import java.lang.ref.Reference;
import java.lang.ref.ReferenceQueue;
import java.lang.ref.WeakReference;
import java.util.concurrent.CountDownLatch;
+import static java.util.concurrent.TimeUnit.NANOSECONDS;
/**
* In order to demonstrate the issue we make several threads (two appears to be sufficient)
@@ -93,9 +94,9 @@ public class EarlyTimeout extends Thread {
public void run() {
try {
startedSignal.countDown();
- long start = System.currentTimeMillis();
+ long start = System.nanoTime();
reference = queue.remove(TIMEOUT);
- actual = System.currentTimeMillis() - start;
+ actual = NANOSECONDS.toMillis(System.nanoTime() - start);
} catch (InterruptedException ex) {
throw new RuntimeException(ex);
}
diff --git a/jdk/test/java/lang/reflect/Method/InterfaceStatic/StaticInterfaceMethodInWayOfDefault.java b/jdk/test/java/lang/reflect/Method/InterfaceStatic/StaticInterfaceMethodInWayOfDefault.java
index ffb384f20a7..4ad93eb3447 100644
--- a/jdk/test/java/lang/reflect/Method/InterfaceStatic/StaticInterfaceMethodInWayOfDefault.java
+++ b/jdk/test/java/lang/reflect/Method/InterfaceStatic/StaticInterfaceMethodInWayOfDefault.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,9 @@
* @summary Test that a static method on an interface doesn't hide a default
* method with the same name and signature in a separate compilation
* scenario.
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.IOUtils
+ * @run main StaticInterfaceMethodInWayOfDefault
*/
import java.io.IOException;
@@ -35,7 +38,7 @@ import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.concurrent.Callable;
-import sun.misc.IOUtils;
+import jdk.testlibrary.IOUtils;
public class StaticInterfaceMethodInWayOfDefault {
public interface A_v1 {
@@ -144,7 +147,7 @@ public class StaticInterfaceMethodInWayOfDefault {
String altPath = altName.replace('.', '/').concat(".class");
try (InputStream is = getResourceAsStream(altPath)) {
if (is != null) {
- byte[] bytes = IOUtils.readFully(is, -1, true);
+ byte[] bytes = IOUtils.readFully(is);
// patch class bytes to contain original name
for (int i = 0; i < bytes.length - 2; i++) {
if (bytes[i] == '_' &&
@@ -167,7 +170,7 @@ public class StaticInterfaceMethodInWayOfDefault {
String path = name.replace('.', '/').concat(".class");
try (InputStream is = getResourceAsStream(path)) {
if (is != null) {
- byte[] bytes = IOUtils.readFully(is, -1, true);
+ byte[] bytes = IOUtils.readFully(is);
return defineClass(name, bytes, 0, bytes.length);
}
else {
diff --git a/jdk/test/java/math/BigInteger/BitLengthOverflow.java b/jdk/test/java/math/BigInteger/BitLengthOverflow.java
index 04f11b21625..ccbc3e9ef46 100644
--- a/jdk/test/java/math/BigInteger/BitLengthOverflow.java
+++ b/jdk/test/java/math/BigInteger/BitLengthOverflow.java
@@ -22,7 +22,7 @@
*/
/*
- * @ test
+ * @test
* @bug 6910473
* @summary Test that bitLength() is not negative
* @author Dmitry Nadezhin
@@ -32,18 +32,15 @@ import java.math.BigInteger;
public class BitLengthOverflow {
public static void main(String[] args) {
-
try {
BigInteger x = BigInteger.ONE.shiftLeft(Integer.MAX_VALUE); // x = pow(2,Integer.MAX_VALUE)
- if (x.bitLength() != (1L << 31))
+ if (x.bitLength() != (1L << 31)) {
throw new RuntimeException("Incorrect bitLength() " + x.bitLength());
+ }
System.out.println("Surprisingly passed with correct bitLength() " + x.bitLength());
} catch (ArithmeticException e) {
// expected
System.out.println("Overflow is reported by ArithmeticException, as expected");
- } catch (OutOfMemoryError e) {
- // possible
- System.out.println("OutOfMemoryError");
}
}
}
diff --git a/jdk/test/java/math/BigInteger/DivisionOverflow.java b/jdk/test/java/math/BigInteger/DivisionOverflow.java
index 075ecab7836..7f35d07adca 100644
--- a/jdk/test/java/math/BigInteger/DivisionOverflow.java
+++ b/jdk/test/java/math/BigInteger/DivisionOverflow.java
@@ -22,9 +22,10 @@
*/
/*
- * @ test
+ * @test
* @bug 8022780
* @summary Test division of large values
+ * @run main/othervm -Xshare:off DivisionOverflow
* @author Dmitry Nadezhin
*/
import java.math.BigInteger;
@@ -38,14 +39,17 @@ public class DivisionOverflow {
BigInteger[] qr = a.divideAndRemainder(b);
BigInteger q = qr[0];
BigInteger r = qr[1];
- if (!r.equals(BigInteger.ZERO))
- throw new RuntimeException("Incorrect singum() of remainder " + r.signum());
- if (q.bitLength() != 2147482079)
+ if (!r.equals(BigInteger.ZERO)) {
+ throw new RuntimeException("Incorrect signum() of remainder " + r.signum());
+ }
+ if (q.bitLength() != 2147482079) {
throw new RuntimeException("Incorrect bitLength() of quotient " + q.bitLength());
+ }
System.out.println("Division of large values passed without overflow.");
} catch (OutOfMemoryError e) {
// possible
- System.out.println("OutOfMemoryError");
+ System.err.println("DivisionOverflow skipped: OutOfMemoryError");
+ System.err.println("Run jtreg with -javaoption:-Xmx8g");
}
}
}
diff --git a/jdk/test/java/math/BigInteger/DoubleValueOverflow.java b/jdk/test/java/math/BigInteger/DoubleValueOverflow.java
index 443d6aecda7..bef5fbaac26 100644
--- a/jdk/test/java/math/BigInteger/DoubleValueOverflow.java
+++ b/jdk/test/java/math/BigInteger/DoubleValueOverflow.java
@@ -22,7 +22,7 @@
*/
/*
- * @ test
+ * @test
* @bug 8021203
* @summary Test that doubleValue() doesn't overflow
* @author Dmitry Nadezhin
@@ -32,18 +32,15 @@ import java.math.BigInteger;
public class DoubleValueOverflow {
public static void main(String[] args) {
-
try {
BigInteger x = BigInteger.valueOf(2).shiftLeft(Integer.MAX_VALUE); // x = pow(2,pow(2,31))
- if (x.doubleValue() != Double.POSITIVE_INFINITY)
+ if (x.doubleValue() != Double.POSITIVE_INFINITY) {
throw new RuntimeException("Incorrect doubleValue() " + x.doubleValue());
+ }
System.out.println("Passed with correct result");
} catch (ArithmeticException e) {
// expected
System.out.println("Overflow is reported by ArithmeticException, as expected");
- } catch (OutOfMemoryError e) {
- // possible
- System.out.println("OutOfMemoryError");
}
}
}
diff --git a/jdk/test/java/math/BigInteger/StringConstructorOverflow.java b/jdk/test/java/math/BigInteger/StringConstructorOverflow.java
index ac362d01831..121b4c43d27 100644
--- a/jdk/test/java/math/BigInteger/StringConstructorOverflow.java
+++ b/jdk/test/java/math/BigInteger/StringConstructorOverflow.java
@@ -22,9 +22,11 @@
*/
/*
- * @ test
+ * @test
+ * @ignore This test has huge memory requirements
* @bug 8021204
* @summary Test constructor BigInteger(String val, int radix) on very long string
+ * @run main/othervm -Xshare:off -Xmx8g StringConstructorOverflow
* @author Dmitry Nadezhin
*/
import java.math.BigInteger;
@@ -45,15 +47,16 @@ public class StringConstructorOverflow {
public static void main(String[] args) {
try {
BigInteger bi = new BigInteger(makeLongHexString(), 16);
- if (bi.compareTo(BigInteger.ONE) <= 0)
+ if (bi.compareTo(BigInteger.ONE) <= 0) {
throw new RuntimeException("Incorrect result " + bi.toString());
+ }
} catch (ArithmeticException e) {
// expected
System.out.println("Overflow is reported by ArithmeticException, as expected");
} catch (OutOfMemoryError e) {
// possible
- System.out.println("OutOfMemoryError");
- System.out.println("Run jtreg with -javaoption:-Xmx8g");
+ System.err.println("StringConstructorOverflow skipped: OutOfMemoryError");
+ System.err.println("Run jtreg with -javaoption:-Xmx8g");
}
}
}
diff --git a/jdk/test/java/math/BigInteger/SymmetricRangeTests.java b/jdk/test/java/math/BigInteger/SymmetricRangeTests.java
index abded05d10a..b944a95d32f 100644
--- a/jdk/test/java/math/BigInteger/SymmetricRangeTests.java
+++ b/jdk/test/java/math/BigInteger/SymmetricRangeTests.java
@@ -22,8 +22,8 @@
*/
/*
- * This test is intentionally ignored because of huge memory requirements
- * @ test
+ * @test
+ * @ignore This test has huge memory requirements
* @run main/timeout=180/othervm -Xmx8g SymmetricRangeTests
* @bug 6910473 8021204 8021203 9005933
* @summary Test range of BigInteger values
diff --git a/jdk/test/java/net/Inet4Address/textToNumericFormat.java b/jdk/test/java/net/Inet4Address/textToNumericFormat.java
index 8a74ba507b4..3fbb3fba1b5 100644
--- a/jdk/test/java/net/Inet4Address/textToNumericFormat.java
+++ b/jdk/test/java/net/Inet4Address/textToNumericFormat.java
@@ -34,19 +34,25 @@ import java.util.*;
public class textToNumericFormat {
public static void main(String[] args) throws UnknownHostException {
- List goodList = new ArrayList();
- List badList = new ArrayList();
+ List goodList = new ArrayList<>();
+ List badList = new ArrayList<>();
String goodAddrs[] = {
"224.0.1.0",
"238.255.255.255",
- "239.255.255.255" };
+ "239.255.255.255",
+ "239.255.65535",
+ "239.16777215",
+ "4294967295" };
String badAddrs[] = {
"238.255.255.2550",
"256.255.255.255",
"238.255.2550.255",
"238.2550.255.255",
- "2380.255.255.255"};
+ "2380.255.255.255",
+ "239.255.65536",
+ "239.16777216",
+ "4294967296" };
for (int i=0; i option, Object testValue) {
+ this.option = option;
+ this.testValue = testValue;
+ }
+ static Test create (SocketOption> option, Object testValue) {
+ return new Test(option, testValue);
+ }
+ Object option;
+ Object testValue;
+ };
+
+ // The tests set the option using the new API, read back the set value
+ // which could be diferent, and then use the legacy get API to check
+ // these values are the same
+
+ static Test[] socketTests = new Test[] {
+ Test.create(StandardSocketOptions.SO_KEEPALIVE, Boolean.TRUE),
+ Test.create(StandardSocketOptions.SO_SNDBUF, Integer.valueOf(10 * 100)),
+ Test.create(StandardSocketOptions.SO_RCVBUF, Integer.valueOf(8 * 100)),
+ Test.create(StandardSocketOptions.SO_REUSEADDR, Boolean.FALSE),
+ Test.create(StandardSocketOptions.SO_LINGER, Integer.valueOf(80)),
+ Test.create(StandardSocketOptions.IP_TOS, Integer.valueOf(100))
+ };
+
+ static Test[] serverSocketTests = new Test[] {
+ Test.create(StandardSocketOptions.SO_RCVBUF, Integer.valueOf(8 * 100)),
+ Test.create(StandardSocketOptions.SO_REUSEADDR, Boolean.FALSE)
+ };
+
+ static Test[] dgSocketTests = new Test[] {
+ Test.create(StandardSocketOptions.SO_SNDBUF, Integer.valueOf(10 * 100)),
+ Test.create(StandardSocketOptions.SO_RCVBUF, Integer.valueOf(8 * 100)),
+ Test.create(StandardSocketOptions.SO_REUSEADDR, Boolean.FALSE),
+ Test.create(StandardSocketOptions.IP_TOS, Integer.valueOf(100))
+ };
+
+ static Test[] mcSocketTests = new Test[] {
+ Test.create(StandardSocketOptions.IP_MULTICAST_IF, getNetworkInterface()),
+ Test.create(StandardSocketOptions.IP_MULTICAST_TTL, Integer.valueOf(10)),
+ Test.create(StandardSocketOptions.IP_MULTICAST_LOOP, Boolean.TRUE)
+ };
+
+ static NetworkInterface getNetworkInterface() {
+ try {
+ Enumeration nifs = NetworkInterface.getNetworkInterfaces();
+ if (nifs.hasMoreElements()) {
+ return (NetworkInterface)nifs.nextElement();
+ }
+ } catch (Exception e) {
+ }
+ return null;
+ }
+
+ static void doSocketTests() throws Exception {
+ try (
+ ServerSocket srv = new ServerSocket(0);
+ Socket c = new Socket("127.0.0.1", srv.getLocalPort());
+ Socket s = srv.accept();
+ ) {
+ for (int i=0; i type, Object s, Object option)
+
+ throws Exception
+ {
+ if (type.equals(Socket.class)) {
+ Socket socket = (Socket)s;
+
+ if (option.equals(StandardSocketOptions.SO_KEEPALIVE)) {
+ return Boolean.valueOf(socket.getKeepAlive());
+ } else if (option.equals(StandardSocketOptions.SO_SNDBUF)) {
+ return Integer.valueOf(socket.getSendBufferSize());
+ } else if (option.equals(StandardSocketOptions.SO_RCVBUF)) {
+ return Integer.valueOf(socket.getReceiveBufferSize());
+ } else if (option.equals(StandardSocketOptions.SO_REUSEADDR)) {
+ return Boolean.valueOf(socket.getReuseAddress());
+ } else if (option.equals(StandardSocketOptions.SO_LINGER)) {
+ return Integer.valueOf(socket.getSoLinger());
+ } else if (option.equals(StandardSocketOptions.IP_TOS)) {
+ return Integer.valueOf(socket.getTrafficClass());
+ } else if (option.equals(StandardSocketOptions.TCP_NODELAY)) {
+ return Boolean.valueOf(socket.getTcpNoDelay());
+ } else {
+ throw new RuntimeException("unexecpted socket option");
+ }
+ } else if (type.equals(ServerSocket.class)) {
+ ServerSocket socket = (ServerSocket)s;
+ if (option.equals(StandardSocketOptions.SO_RCVBUF)) {
+ return Integer.valueOf(socket.getReceiveBufferSize());
+ } else if (option.equals(StandardSocketOptions.SO_REUSEADDR)) {
+ return Boolean.valueOf(socket.getReuseAddress());
+ } else {
+ throw new RuntimeException("unexecpted socket option");
+ }
+ } else if (type.equals(DatagramSocket.class)) {
+ DatagramSocket socket = (DatagramSocket)s;
+
+ if (option.equals(StandardSocketOptions.SO_SNDBUF)) {
+ return Integer.valueOf(socket.getSendBufferSize());
+ } else if (option.equals(StandardSocketOptions.SO_RCVBUF)) {
+ return Integer.valueOf(socket.getReceiveBufferSize());
+ } else if (option.equals(StandardSocketOptions.SO_REUSEADDR)) {
+ return Boolean.valueOf(socket.getReuseAddress());
+ } else if (option.equals(StandardSocketOptions.IP_TOS)) {
+ return Integer.valueOf(socket.getTrafficClass());
+ } else {
+ throw new RuntimeException("unexecpted socket option");
+ }
+
+ } else if (type.equals(MulticastSocket.class)) {
+ MulticastSocket socket = (MulticastSocket)s;
+
+ if (option.equals(StandardSocketOptions.SO_SNDBUF)) {
+ return Integer.valueOf(socket.getSendBufferSize());
+ } else if (option.equals(StandardSocketOptions.SO_RCVBUF)) {
+ return Integer.valueOf(socket.getReceiveBufferSize());
+ } else if (option.equals(StandardSocketOptions.SO_REUSEADDR)) {
+ return Boolean.valueOf(socket.getReuseAddress());
+ } else if (option.equals(StandardSocketOptions.IP_TOS)) {
+ return Integer.valueOf(socket.getTrafficClass());
+ } else if (option.equals(StandardSocketOptions.IP_MULTICAST_IF)) {
+ return socket.getNetworkInterface();
+ } else if (option.equals(StandardSocketOptions.IP_MULTICAST_TTL)) {
+ return Integer.valueOf(socket.getTimeToLive());
+ } else if (option.equals(StandardSocketOptions.IP_MULTICAST_LOOP)) {
+ return Boolean.valueOf(socket.getLoopbackMode());
+ } else {
+ throw new RuntimeException("unexecpted socket option");
+ }
+ }
+ throw new RuntimeException("unexecpted socket type");
+ }
+
+ public static void main(String args[]) throws Exception {
+ doSocketTests();
+ doServerSocketTests();
+ doDgSocketTests();
+ doMcSocketTests();
+ }
+}
diff --git a/jdk/test/java/net/URLPermission/nstest/lookup.sh b/jdk/test/java/net/URLPermission/nstest/lookup.sh
index 9aa3ccbf527..1c7e3cfcb2f 100644
--- a/jdk/test/java/net/URLPermission/nstest/lookup.sh
+++ b/jdk/test/java/net/URLPermission/nstest/lookup.sh
@@ -26,6 +26,7 @@
# @library /lib/testlibrary
# @compile -XDignore.symbol.file=true SimpleNameService.java
# LookupTest.java SimpleNameServiceDescriptor.java
+# @build jdk.testlibrary.Utils
# @run shell/timeout=50 lookup.sh
#
diff --git a/jdk/test/java/nio/charset/Charset/NIOCharsetAvailabilityTest.java b/jdk/test/java/nio/charset/Charset/NIOCharsetAvailabilityTest.java
index 78913f2f46a..1e505712cda 100644
--- a/jdk/test/java/nio/charset/Charset/NIOCharsetAvailabilityTest.java
+++ b/jdk/test/java/nio/charset/Charset/NIOCharsetAvailabilityTest.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,6 +36,8 @@ import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.charset.Charset;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
@@ -89,12 +91,10 @@ public class NIOCharsetAvailabilityTest {
private static void addCharsets(Set charsets, final String packageName)
throws Exception {
- String classPath =
- (String) java.security.AccessController.doPrivileged(
- new sun.security.action.GetPropertyAction("sun.boot.class.path"));
- String s =
- (String) java.security.AccessController.doPrivileged(
- new sun.security.action.GetPropertyAction("java.class.path"));
+ String classPath = AccessController.doPrivileged(
+ (PrivilegedAction)() -> System.getProperty("sun.boot.class.path"));
+ String s = AccessController.doPrivileged(
+ (PrivilegedAction)() -> System.getProperty("java.class.path"));
// Search combined system and application class path
if (s != null && s.length() != 0) {
diff --git a/jdk/test/java/security/Provider/NewInstance.java b/jdk/test/java/security/Provider/NewInstance.java
new file mode 100644
index 00000000000..ad69f468925
--- /dev/null
+++ b/jdk/test/java/security/Provider/NewInstance.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8039853
+ * @summary Provider.Service.newInstance() does not work with current
+ JDK JGSS Mechanisms
+ */
+
+import java.security.*;
+import java.util.*;
+
+public class NewInstance {
+
+ public static void main(String[] args) throws Exception {
+ for (Provider p : Security.getProviders()) {
+ System.out.println("---------");
+ System.out.println(p.getName() + ":" + p.getInfo());
+ if (p.getName().equals("SunPCSC")) {
+ System.out.println("A smartcard might not be installed. Skip test.");
+ continue;
+ }
+ Set set = p.getServices();
+ Iterator i = set.iterator();
+
+ while (i.hasNext()) {
+ Provider.Service s = i.next();
+ System.out.println(s.getType() + "." + s.getAlgorithm());
+ try {
+ s.newInstance(null);
+ } catch (NoSuchAlgorithmException e) {
+ System.out.println(" check");
+ Throwable t = e.getCause();
+ if (!(t instanceof InvalidAlgorithmParameterException)) {
+ // Some engines require certain parameters to be
+ // present on creation. Calling newInstance(null) will
+ // trigger this exception and it's OK.
+ throw e;
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/jdk/test/java/sql/TEST.properties b/jdk/test/java/sql/TEST.properties
new file mode 100644
index 00000000000..295505b905a
--- /dev/null
+++ b/jdk/test/java/sql/TEST.properties
@@ -0,0 +1,3 @@
+# JDBC unit tests uses TestNG
+TestNG.dirs = .
+
diff --git a/jdk/test/java/sql/test/sql/BatchUpdateExceptionTests.java b/jdk/test/java/sql/test/sql/BatchUpdateExceptionTests.java
new file mode 100644
index 00000000000..2b1111b7526
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/BatchUpdateExceptionTests.java
@@ -0,0 +1,326 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.io.ByteArrayInputStream;
+import java.io.File;
+import java.io.ObjectInputStream;
+import java.sql.BatchUpdateException;
+import java.sql.SQLException;
+import java.util.Arrays;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.SerializedBatchUpdateException;
+import util.BaseTest;
+
+public class BatchUpdateExceptionTests extends BaseTest {
+
+ private final int[] uc = {1, 2, 3};
+ private final long[] luc = {1, 2, 3};
+
+ private final String testSrcDir = System.getProperty("test.src", ".")
+ + File.separatorChar;
+
+ /**
+ * Create BatchUpdateException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ BatchUpdateException be = new BatchUpdateException(null,
+ null, errorCode, (int[]) null, null);
+ assertTrue(be.getMessage() == null && be.getSQLState() == null
+ && be.getUpdateCounts() == null && be.getCause() == null
+ && be.getLargeUpdateCounts() == null
+ && be.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create BatchUpdateException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ BatchUpdateException ex = new BatchUpdateException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && ex.getUpdateCounts() == null
+ && ex.getLargeUpdateCounts() == null);
+ }
+
+ /**
+ * Create BatchUpdateException with null Throwable
+ */
+ @Test
+ public void test2() {
+ BatchUpdateException ex = new BatchUpdateException((Throwable) null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && ex.getUpdateCounts() == null
+ && ex.getLargeUpdateCounts() == null);
+ }
+
+ /**
+ * Create BatchUpdateException with message and update counts
+ */
+ @Test
+ public void test3() {
+
+ BatchUpdateException ex = new BatchUpdateException(reason, uc);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && Arrays.equals(ex.getUpdateCounts(), uc)
+ && Arrays.equals(ex.getLargeUpdateCounts(), luc)
+ );
+ }
+
+ /**
+ * Create BatchUpdateException with update counts
+ */
+ @Test
+ public void test4() {
+ BatchUpdateException ex = new BatchUpdateException(uc);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && Arrays.equals(ex.getUpdateCounts(), uc)
+ && Arrays.equals(ex.getLargeUpdateCounts(), luc)
+ );
+ }
+
+ /**
+ * Create BatchUpdateException with Throwable and update counts
+ */
+ @Test
+ public void test5() {
+ BatchUpdateException ex = new BatchUpdateException(uc, t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0
+ && Arrays.equals(ex.getUpdateCounts(), uc)
+ && Arrays.equals(ex.getLargeUpdateCounts(), luc)
+ );
+ }
+
+ /**
+ * Create BatchUpdateException with message, Throwable, and update counts
+ */
+ @Test
+ public void test6() {
+ BatchUpdateException ex = new BatchUpdateException(reason, uc, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0
+ && Arrays.equals(ex.getUpdateCounts(), uc)
+ && Arrays.equals(ex.getLargeUpdateCounts(), luc)
+ );
+ }
+
+ /**
+ * Create BatchUpdateException with message, SQLState, Throwable, and update
+ * counts
+ */
+ @Test
+ public void test7() {
+ BatchUpdateException ex = new BatchUpdateException(reason, state, uc, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0
+ && Arrays.equals(ex.getUpdateCounts(), uc)
+ && Arrays.equals(ex.getLargeUpdateCounts(), luc)
+ );
+ }
+
+ /**
+ * Create BatchUpdateException with message, SQLState, errorCode code
+ * Throwable, and update counts
+ */
+ @Test
+ public void test8() {
+ BatchUpdateException ex = new BatchUpdateException(reason, state, errorCode,
+ uc, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode
+ && Arrays.equals(ex.getUpdateCounts(), uc)
+ && Arrays.equals(ex.getLargeUpdateCounts(), luc)
+ );
+ }
+
+ /**
+ * Create BatchUpdateException with message, SQLState, errorCode code
+ * Throwable, and long [] update counts
+ */
+ @Test
+ public void test9() {
+ BatchUpdateException ex = new BatchUpdateException(reason, state, errorCode,
+ luc, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode
+ && Arrays.equals(ex.getUpdateCounts(), uc)
+ && Arrays.equals(ex.getLargeUpdateCounts(), luc)
+ );
+ }
+
+ /**
+ * Validate that a copy of the update counts array is made
+ */
+ @Test
+ public void test10() {
+ int[] uc1 = {1, 2};
+ BatchUpdateException ex = new BatchUpdateException(uc1);
+ assertTrue(Arrays.equals(ex.getUpdateCounts(), uc1));
+ uc1[0] = 6689;
+ assertFalse(Arrays.equals(ex.getUpdateCounts(), uc1));
+ }
+
+ /**
+ * Validate that if null is specified for the update count, it is returned
+ * as null
+ */
+ @Test
+ public void test11() {
+ BatchUpdateException ex = new BatchUpdateException((int[]) null);
+ assertTrue(ex.getMessage() == null && ex.getSQLState() == null
+ && ex.getErrorCode() == 0 && ex.getUpdateCounts() == null
+ && ex.getLargeUpdateCounts() == null);
+ }
+
+ /**
+ * Serialize a BatchUpdateException and make sure you can read it back
+ * properly
+ */
+ @Test
+ public void test12() throws Exception {
+ BatchUpdateException be = new BatchUpdateException(reason, state, errorCode,
+ uc, t);
+ BatchUpdateException bue
+ = createSerializedException(be);
+ assertTrue(reason.equals(bue.getMessage())
+ && bue.getSQLState().equals(state)
+ && cause.equals(bue.getCause().toString())
+ && bue.getErrorCode() == errorCode
+ && Arrays.equals(bue.getLargeUpdateCounts(), luc)
+ && Arrays.equals(bue.getUpdateCounts(), uc));
+ }
+
+
+
+ /**
+ * De-Serialize a BatchUpdateException from JDBC 4.0 and make sure you can
+ * read it back properly
+ */
+ @Test
+ public void test13() throws Exception {
+ String reason1 = "This was the error msg";
+ String state1 = "user defined sqlState";
+ String cause1 = "java.lang.Throwable: throw 1";
+ int errorCode1 = 99999;
+ Throwable t = new Throwable("throw 1");
+ int[] uc1 = {1, 2, 21};
+ long[] luc1 = {1, 2, 21};
+
+ ObjectInputStream ois = new ObjectInputStream(
+ new ByteArrayInputStream(SerializedBatchUpdateException.DATA));
+ BatchUpdateException bue = (BatchUpdateException) ois.readObject();
+ assertTrue(reason1.equals(bue.getMessage())
+ && bue.getSQLState().equals(state1)
+ && bue.getErrorCode() == errorCode1
+ && cause1.equals(bue.getCause().toString())
+ && Arrays.equals(bue.getLargeUpdateCounts(), luc1)
+ && Arrays.equals(bue.getUpdateCounts(), uc1));
+ }
+
+ /**
+ * Serialize a BatchUpdateException with an Integer.MAX_VALUE + 1 and
+ * validate you can read it back properly
+ */
+ @Test
+ public void test14() throws Exception {
+ int[] uc1 = {Integer.MAX_VALUE, Integer.MAX_VALUE + 1};
+ long[] luc1 = {Integer.MAX_VALUE, Integer.MAX_VALUE + 1};
+ BatchUpdateException be = new BatchUpdateException(reason, state, errorCode,
+ luc1, t);
+ BatchUpdateException bue
+ = createSerializedException(be);
+ assertTrue(reason.equals(bue.getMessage())
+ && bue.getSQLState().equals(state)
+ && cause.equals(bue.getCause().toString())
+ && bue.getErrorCode() == errorCode
+ && Arrays.equals(bue.getLargeUpdateCounts(), luc1)
+ && Arrays.equals(bue.getUpdateCounts(), uc1));
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test15() {
+ BatchUpdateException ex = new BatchUpdateException("Exception 1", uc, t1);
+ BatchUpdateException ex1 = new BatchUpdateException("Exception 2", uc);
+ BatchUpdateException ex2 = new BatchUpdateException("Exception 3", uc, t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test16() {
+ BatchUpdateException ex = new BatchUpdateException("Exception 1", uc, t1);
+ BatchUpdateException ex1 = new BatchUpdateException("Exception 2", uc);
+ BatchUpdateException ex2 = new BatchUpdateException("Exception 3", uc, t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ SQLException sqe = ex;
+ int num = 0;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+}
diff --git a/jdk/test/java/sql/test/sql/DataTruncationTests.java b/jdk/test/java/sql/test/sql/DataTruncationTests.java
new file mode 100644
index 00000000000..fbf7eebe90a
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/DataTruncationTests.java
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.DataTruncation;
+import java.sql.SQLException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class DataTruncationTests extends BaseTest {
+
+ private final String READ_TRUNCATION = "01004";
+ private final String WRITE_TRUNCATION = "22001";
+ private final String dtReason = "Data truncation";
+ private final int dterrorCode = 0;
+ private final String[] dtmsgs = {dtReason, "cause 1", dtReason,
+ dtReason, "cause 2"};
+ private boolean onRead = false;
+ private final boolean parameter = false;
+ private final int index = 21;
+ private final int dataSize = 25;
+ private final int transferSize = 10;
+
+ /**
+ * Create DataTruncation object indicating a truncation on read
+ */
+ @Test
+ public void test() {
+ onRead = true;
+ DataTruncation e = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize);
+ assertTrue(e.getMessage().equals(dtReason)
+ && e.getSQLState().equals(READ_TRUNCATION)
+ && e.getCause() == null
+ && e.getErrorCode() == dterrorCode
+ && e.getParameter() == parameter
+ && e.getRead() == onRead
+ && e.getDataSize() == dataSize
+ && e.getTransferSize() == transferSize
+ && e.getIndex() == index);
+ }
+
+ /**
+ * Create DataTruncation object indicating a truncation on write
+ */
+ @Test
+ public void test1() {
+ onRead = false;
+ DataTruncation e = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize);
+ assertTrue(e.getMessage().equals(dtReason)
+ && e.getSQLState().equals(WRITE_TRUNCATION)
+ && e.getCause() == null
+ && e.getErrorCode() == dterrorCode
+ && e.getParameter() == parameter
+ && e.getRead() == onRead
+ && e.getDataSize() == dataSize
+ && e.getTransferSize() == transferSize
+ && e.getIndex() == index);
+ }
+
+ /**
+ * Create DataTruncation object indicating a truncation on read with a
+ * Throwable
+ */
+ @Test
+ public void test2() {
+ onRead = true;
+ DataTruncation e = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize, t);
+ assertTrue(e.getMessage().equals(dtReason)
+ && e.getSQLState().equals(READ_TRUNCATION)
+ && cause.equals(e.getCause().toString())
+ && e.getErrorCode() == dterrorCode
+ && e.getParameter() == parameter
+ && e.getRead() == onRead
+ && e.getDataSize() == dataSize
+ && e.getTransferSize() == transferSize
+ && e.getIndex() == index);
+ }
+
+ /**
+ * Create DataTruncation object indicating a truncation on read with null
+ * specified for the Throwable
+ */
+ @Test
+ public void test3() {
+ onRead = true;;
+ DataTruncation e = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize, null);
+ assertTrue(e.getMessage().equals(dtReason)
+ && e.getSQLState().equals(READ_TRUNCATION)
+ && e.getCause() == null
+ && e.getErrorCode() == dterrorCode
+ && e.getParameter() == parameter
+ && e.getRead() == onRead
+ && e.getDataSize() == dataSize
+ && e.getTransferSize() == transferSize
+ && e.getIndex() == index);
+ }
+
+ /**
+ * Create DataTruncation object indicating a truncation on read and you can
+ * pass a -1 for the index
+ */
+ @Test
+ public void test4() {
+ onRead = true;
+ int negIndex = -1;
+ DataTruncation e = new DataTruncation(negIndex, parameter, onRead,
+ dataSize, transferSize);
+ assertTrue(e.getMessage().equals(dtReason)
+ && e.getSQLState().equals(READ_TRUNCATION)
+ && e.getCause() == null
+ && e.getErrorCode() == dterrorCode
+ && e.getParameter() == parameter
+ && e.getRead() == onRead
+ && e.getDataSize() == dataSize
+ && e.getTransferSize() == transferSize
+ && e.getIndex() == negIndex);
+ }
+
+ /**
+ * Serialize a DataTruncation and make sure you can read it back properly
+ */
+ @Test
+ public void test5() throws Exception {
+ DataTruncation e = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize);
+ DataTruncation ex1 = createSerializedException(e);
+ assertTrue(e.getMessage().equals(dtReason)
+ && e.getSQLState().equals(READ_TRUNCATION)
+ && e.getCause() == null
+ && e.getErrorCode() == dterrorCode
+ && e.getParameter() == parameter
+ && e.getRead() == onRead
+ && e.getDataSize() == dataSize
+ && e.getTransferSize() == transferSize
+ && e.getIndex() == index);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct using
+ * for-each loop
+ */
+ @Test
+ public void test11() {
+ DataTruncation ex = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize, t1);
+ DataTruncation ex1 = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize);
+ DataTruncation ex2 = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize, t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(dtmsgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct using
+ * traditional while loop
+ */
+ @Test
+ public void test12() {
+ DataTruncation ex = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize, t1);
+ DataTruncation ex1 = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize);
+ DataTruncation ex2 = new DataTruncation(index, parameter, onRead,
+ dataSize, transferSize, t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(dtmsgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(dtmsgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/DateTests.java b/jdk/test/java/sql/test/sql/DateTests.java
new file mode 100644
index 00000000000..5a660507eee
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/DateTests.java
@@ -0,0 +1,542 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.Date;
+import java.time.Instant;
+import java.time.LocalDate;
+import static org.testng.Assert.*;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class DateTests {
+
+ public DateTests() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception {
+ }
+
+ @BeforeMethod
+ public void setUpMethod() throws Exception {
+ }
+
+ @AfterMethod
+ public void tearDownMethod() throws Exception {
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_year() throws Exception {
+ String expResult = "20009-11-01";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_year2() throws Exception {
+ String expResult = "09-11-01";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_year3() throws Exception {
+ String expResult = "-11-01";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_month() throws Exception {
+ String expResult = "2009-111-01";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_month3() throws Exception {
+ String expResult = "2009--01";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_month4() throws Exception {
+ String expResult = "2009-13-01";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_day() throws Exception {
+ String expResult = "2009-11-011";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_day3() throws Exception {
+ String expResult = "2009-11-";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_day4() throws Exception {
+ String expResult = "2009-11-00";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_day5() throws Exception {
+ String expResult = "2009-11-33";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf() throws Exception {
+ String expResult = "--";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf2() throws Exception {
+ String expResult = "";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf3() throws Exception {
+ String expResult = null;
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf4() throws Exception {
+ String expResult = "-";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf5() throws Exception {
+ String expResult = "2009";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf6() throws Exception {
+ String expResult = "2009-01";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf7() throws Exception {
+ String expResult = "---";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf8() throws Exception {
+ String expResult = "2009-13--1";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Date string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_valueOf10() {
+ String expResult = "1900-1-0";
+ Date.valueOf(expResult);
+ }
+
+ /**
+ * Test that a date created from a date string is equal to the value
+ * returned from toString()
+ */
+ @Test
+ public void test_valueOf() {
+ String expResult = "2009-08-30";
+ Date d = Date.valueOf(expResult);
+ assertEquals(expResult, d.toString());
+ }
+
+ /**
+ * Test that two dates, one with lead 0s omitted for month are equal
+ */
+ @Test
+ public void testValid_month_single_digit() {
+ String testDate = "2009-1-01";
+ String expResult = "2009-01-01";
+ Date d = Date.valueOf(testDate);
+ Date d2 = Date.valueOf(expResult);
+ assertEquals(d, d2);
+ }
+
+ /**
+ * Test that two dates, one with lead 0s omitted for day are equal
+ */
+ @Test
+ public void testValid_day_single_digit() {
+ String testDate = "2009-11-1";
+ String expResult = "2009-11-01";
+ Date d = Date.valueOf(testDate);
+ Date d2 = Date.valueOf(expResult);
+ assertEquals(d, d2);
+ }
+
+ /**
+ * Test that two dates, one with lead 0s omitted for month and day are equal
+ */
+ @Test
+ public void testValid_month_day_single_digit() {
+ String testDate = "2009-1-1";
+ String expResult = "2009-01-01";
+ Date d = Date.valueOf(testDate);
+ Date d2 = Date.valueOf(expResult);
+ assertEquals(d, d2);
+ }
+
+ /**
+ * Validate that a Date.after() returns false when same date is compared
+ */
+ @Test
+ public void test1() {
+ Date d = Date.valueOf("1961-08-30");
+ assertFalse(d.after(d), "Error d.after(d) = true");
+ }
+
+ /**
+ * Validate that a Date.after() returns true when later date is compared to
+ * earlier date
+ */
+ @Test
+ public void test2() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(System.currentTimeMillis());
+ assertTrue(d2.after(d), "Error d2.after(d) = false");
+ }
+
+ /**
+ * Validate that a Date.after() returns false when earlier date is compared
+ * to later date
+ */
+ @Test
+ public void test3() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(d.getTime());
+ assertFalse(d.after(d2), "Error d.after(d2) = true");
+ }
+
+ /**
+ * Validate that a Date.after() returns false when date compared to another
+ * date created from the original date
+ */
+ @Test
+ public void test4() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(d.getTime());
+ assertFalse(d.after(d2), "Error d.after(d2) = true");
+ assertFalse(d2.after(d), "Error d2.after(d) = true");
+ }
+
+ /**
+ * Validate that a Date.before() returns false when same date is compared
+ */
+ @Test
+ public void test5() {
+ Date d = Date.valueOf("1961-08-30");
+ assertFalse(d.before(d), "Error d.before(d) = true");
+ }
+
+ /**
+ * Validate that a Date.before() returns true when earlier date is compared
+ * to later date
+ */
+ @Test
+ public void test6() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(System.currentTimeMillis());
+ assertTrue(d.before(d2), "Error d.before(d2) = false");
+ }
+
+ /**
+ * Validate that a Date.before() returns false when later date is compared
+ * to earlier date
+ */
+ @Test
+ public void test7() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(d.getTime());
+ assertFalse(d2.before(d), "Error d2.before(d) = true");
+ }
+
+ /**
+ * Validate that a Date.before() returns false when date compared to another
+ * date created from the original date
+ */
+ @Test
+ public void test8() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(d.getTime());
+ assertFalse(d.before(d2), "Error d.before(d2) = true");
+ assertFalse(d2.before(d), "Error d2.before(d) = true");
+ }
+
+ /**
+ * Validate that a Date.compareTo returns 0 when both Date objects are the
+ * same
+ */
+ @Test
+ public void test9() {
+ Date d = Date.valueOf("1961-08-30");
+ assertTrue(d.compareTo(d) == 0, "Error d.compareTo(d) !=0");
+ }
+
+ /**
+ * Validate that a Date.compareTo returns 0 when both Date objects represent
+ * the same date
+ */
+ @Test
+ public void test10() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(d.getTime());
+ assertTrue(d.compareTo(d2) == 0, "Error d.compareTo(d2) !=0");
+ }
+
+ /**
+ * Validate that a Date.compareTo returns -1 when comparing a date to a
+ * later date
+ */
+ @Test
+ public void test11() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(System.currentTimeMillis());
+ assertTrue(d.compareTo(d2) == -1, "Error d.compareTo(d2) != -1");
+ }
+
+ /**
+ * Validate that a Date.compareTo returns 1 when comparing a date to an
+ * earlier date
+ */
+ @Test
+ public void test12() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(System.currentTimeMillis());
+ assertTrue(d2.compareTo(d) == 1, "Error d.compareTo(d2) != 1");
+ }
+
+ /**
+ * Validate that a Date made from a LocalDate are equal
+ */
+ @Test
+ public void test13() {
+ Date d = Date.valueOf("1961-08-30");
+ LocalDate ldt = d.toLocalDate();
+ Date d2 = Date.valueOf(ldt);
+ assertTrue(d.equals(d2), "Error d != d2");
+ }
+
+ /**
+ * Validate that a Date LocalDate value, made from a LocalDate are equal
+ */
+ @Test
+ public void test14() {
+ LocalDate ldt = LocalDate.now();
+ Date d = Date.valueOf(ldt);
+ assertTrue(ldt.equals(d.toLocalDate()),
+ "Error LocalDate values are not equal");
+ }
+
+ /**
+ * Validate an NPE occurs when a null LocalDate is passed to valueOf
+ */
+ @Test(expectedExceptions = NullPointerException.class)
+ public void test15() throws Exception {
+ LocalDate ld = null;
+ Date.valueOf(ld);
+ }
+
+ /**
+ * Validate an UnsupportedOperationException occurs when toInstant() is
+ * called
+ */
+ @Test(expectedExceptions = UnsupportedOperationException.class)
+ public void test16() throws Exception {
+ Date d = Date.valueOf("1961-08-30");
+ Instant instant = d.toInstant();
+ }
+
+ /**
+ * Validate that two Date objects are equal when one is created from the
+ * toString() of the other
+ */
+ @Test
+ public void test17() {
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = Date.valueOf(d.toString());
+ assertTrue(d.equals(d2) && d2.equals(d), "Error d != d2");
+ }
+
+ /**
+ * Validate that two Date values one created using valueOf and another via a
+ * constructor are equal
+ */
+ @Test
+ public void test18() {
+
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(61, 7, 30);
+ assertTrue(d.equals(d2), "Error d != d2");
+ }
+
+ /**
+ * Validate that two Date values one created using getTime() of the other
+ * are equal
+ */
+ @Test
+ public void test19() {
+
+ Date d = Date.valueOf("1961-08-30");
+ Date d2 = new Date(d.getTime());
+ assertTrue(d.equals(d2), "Error d != d2");
+ }
+
+ /**
+ * Validate that a Date value is equal to itself
+ */
+ @Test
+ public void test20() {
+
+ Date d = Date.valueOf("1961-08-30");
+ assertTrue(d.equals(d), "Error d != d");
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling getHours
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test21() throws Exception {
+ Date d = Date.valueOf("1961-08-30");
+ d.getHours();
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling getMinutes
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test22() throws Exception {
+ Date d = Date.valueOf("1961-08-30");
+ d.getMinutes();
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling getSeconds
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test23() throws Exception {
+ Date d = Date.valueOf("1961-08-30");
+ d.getSeconds();
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling setHours
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test24() throws Exception {
+ Date d = Date.valueOf("1961-08-30");
+ d.setHours(8);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling setMinutes
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test25() throws Exception {
+ Date d = Date.valueOf("1961-08-30");
+ d.setMinutes(0);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling setSeconds
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test26() throws Exception {
+ Date d = Date.valueOf("1961-08-30");
+ d.setSeconds(0);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/DriverManagerTests.java b/jdk/test/java/sql/test/sql/DriverManagerTests.java
new file mode 100644
index 00000000000..938f23e38a9
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/DriverManagerTests.java
@@ -0,0 +1,354 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.CharArrayReader;
+import java.io.CharArrayWriter;
+import java.io.File;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.sql.Driver;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.Properties;
+import static org.testng.Assert.*;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+import util.StubDriver;
+
+public class DriverManagerTests {
+
+ private final String StubDriverURL = "jdbc:tennis:boy";
+ private final String StubDriverDAURL = "jdbc:luckydog:tennis";
+ private final String InvalidURL = "jdbc:cardio:tennis";
+ private String[] results = {"output", "more output", "and more", "the end"};
+ private String noOutput = "should not find this";
+
+ public DriverManagerTests() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception {
+ }
+
+ @BeforeMethod
+ public void setUpMethod() throws Exception {
+ removeAllDrivers();
+ }
+
+ @AfterMethod
+ public void tearDownMethod() throws Exception {
+ }
+
+ /**
+ * Utility method to remove all registered drivers
+ */
+ private static void removeAllDrivers() {
+ java.util.Enumeration e = DriverManager.getDrivers();
+ while (e.hasMoreElements()) {
+ try {
+ DriverManager.deregisterDriver((Driver) (e.nextElement()));
+ } catch (SQLException ex) {
+ System.out.print(ex.getMessage());
+ }
+ }
+ }
+
+ /**
+ * Utility method to see if a driver is registered
+ */
+ private boolean isDriverRegistered(Driver d) {
+ boolean foundDriver = false;
+ java.util.Enumeration e = DriverManager.getDrivers();
+ while (e.hasMoreElements()) {
+ if (d == (Driver) e.nextElement()) {
+ foundDriver = true;
+ break;
+ }
+ }
+ return foundDriver;
+ }
+
+ /**
+ * Validate that values set using setLoginTimeout will be returned by
+ * getLoginTimeout
+ */
+ @Test
+ public void test() {
+ int[] vals = {-1, 0, 5};
+ for (int val : vals) {
+ DriverManager.setLoginTimeout(val);
+ assertEquals(val, DriverManager.getLoginTimeout());
+ }
+ }
+
+ /**
+ * Validate that NullPointerException is thrown when null is passed to
+ * registerDriver
+ */
+ @Test(expectedExceptions = NullPointerException.class)
+ public void test1() throws Exception {
+ Driver d = null;
+ DriverManager.registerDriver(d);
+ }
+
+ /**
+ * Validate that NullPointerException is thrown when null is passed to
+ * registerDriver
+ */
+ @Test(expectedExceptions = NullPointerException.class)
+ public void test2() throws Exception {
+ Driver d = null;
+ DriverManager.registerDriver(d, null);
+ }
+
+ /**
+ * Validate that a null value allows for deRegisterDriver to return
+ */
+ @Test
+ public void test3() throws Exception {
+ DriverManager.deregisterDriver(null);
+
+ }
+
+ /**
+ * Validate that SQLException is thrown when there is no Driver to service
+ * the URL
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test4() throws Exception {
+ DriverManager.getConnection(InvalidURL);
+ }
+
+ /**
+ * Validate that SQLException is thrown when there is no Driver to service
+ * the URL
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test5() throws Exception {
+ DriverManager.getConnection(InvalidURL, new Properties());
+ }
+
+ /**
+ * Validate that SQLException is thrown when there is no Driver to service
+ * the URL
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test6() throws Exception {
+ DriverManager.getConnection(InvalidURL, "LuckyDog", "tennisanyone");
+ }
+
+ /**
+ * Validate that SQLException is thrown when null is passed for the URL
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test7() throws Exception {
+ DriverManager.getConnection(null);
+ }
+
+ /**
+ * Validate that SQLException is thrown when null is passed for the URL
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test8() throws Exception {
+ DriverManager.getConnection(null, new Properties());
+ }
+
+ /**
+ * Validate that SQLException is thrown when null is passed for the URL
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test9() throws Exception {
+ DriverManager.getConnection(null, "LuckyDog", "tennisanyone");
+ }
+
+ /**
+ * Validate that SQLException is thrown when there is no Driver to service
+ * the URL
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test10() throws Exception {
+ DriverManager.getDriver(InvalidURL);
+ }
+
+ /**
+ * Validate that SQLException is thrown when null is passed for the URL
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test11() throws Exception {
+ DriverManager.getDriver(null);
+ }
+
+ /**
+ * Validate that a non-null Driver is returned by getDriver when a valid URL
+ * is specified
+ */
+ @Test
+ public void test12() throws Exception {
+
+ DriverManager.registerDriver(new StubDriver());
+ assertTrue(DriverManager.getDriver(StubDriverURL) != null);
+ }
+
+ /**
+ * Validate that SQLException is thrown when the URL is not valid for any of
+ * the registered drivers
+ */
+ @Test(expectedExceptions = SQLException.class)
+ public void test13() throws Exception {
+ DriverManager.registerDriver(new StubDriver());
+ DriverManager.getDriver(InvalidURL);
+ }
+
+ /**
+ * Validate that a Connection object is returned when a valid URL is
+ * specified to getConnection
+ *
+ */
+ @Test
+ public void test14() throws Exception {
+
+ DriverManager.registerDriver(new StubDriver());
+ assertTrue(
+ DriverManager.getConnection(StubDriverURL) != null);
+ assertTrue(DriverManager.getConnection(StubDriverURL,
+ "LuckyDog", "tennisanyone") != null);
+ Properties props = new Properties();
+ props.put("user", "LuckyDog");
+ props.put("password", "tennisanyone");
+ assertTrue(
+ DriverManager.getConnection(StubDriverURL,
+ props) != null);
+ }
+
+ /**
+ * Register a driver and make sure you find it via its URL. Deregister the
+ * driver and validate it is not longer registered
+ *
+ * @throws Exception
+ */
+ @Test()
+ public void test15() throws Exception {
+ DriverManager.registerDriver(new StubDriver());
+ Driver d = DriverManager.getDriver(StubDriverURL);
+ assertTrue(d != null);
+ assertTrue(isDriverRegistered(d));
+ DriverManager.deregisterDriver(d);
+ assertFalse(isDriverRegistered(d));
+ }
+
+ /**
+ * Validate that DriverAction.release is called when a driver is registered
+ * via registerDriver(Driver, DriverAction)
+ *
+ * @throws Exception
+ */
+ @Test
+ public void test16() throws Exception {
+ File file = new File(util.StubDriverDA.DriverActionCalled);
+ file.delete();
+ assertFalse(file.exists());
+ Driver d = null;
+ Class.forName("util.StubDriverDA");
+ d = DriverManager.getDriver(StubDriverDAURL);
+ DriverManager.deregisterDriver(d);
+ assertFalse(isDriverRegistered(d), "Driver is registered");
+ assertTrue(file.exists());
+ }
+
+ /**
+ * Create a PrintStream and use to send output via DriverManager.println
+ * Validate that if you disable the stream, the output sent is not present
+ */
+ @Test
+ public void tests17() throws Exception {
+ ByteArrayOutputStream os = new ByteArrayOutputStream();
+ PrintStream ps = new PrintStream(os);
+ DriverManager.setLogStream(ps);
+ assertTrue(DriverManager.getLogStream() == ps);
+
+ DriverManager.println(results[0]);
+ DriverManager.setLogStream((PrintStream) null);
+ assertTrue(DriverManager.getLogStream() == null);
+ DriverManager.println(noOutput);
+ DriverManager.setLogStream(ps);
+ DriverManager.println(results[1]);
+ DriverManager.println(results[2]);
+ DriverManager.println(results[3]);
+ DriverManager.setLogStream((PrintStream) null);
+ DriverManager.println(noOutput);
+
+ /*
+ * Check we do not get the output when the stream is disabled
+ */
+ InputStreamReader is
+ = new InputStreamReader(new ByteArrayInputStream(os.toByteArray()));
+ BufferedReader reader = new BufferedReader(is);
+ for (String result : results) {
+ assertTrue(result.equals(reader.readLine()));
+ }
+ }
+
+ /**
+ * Create a PrintWriter and use to to send output via DriverManager.println
+ * Validate that if you disable the writer, the output sent is not present
+ */
+ @Test
+ public void tests18() throws Exception {
+ CharArrayWriter cw = new CharArrayWriter();
+ PrintWriter pw = new PrintWriter(cw);
+ DriverManager.setLogWriter(pw);
+ assertTrue(DriverManager.getLogWriter() == pw);
+
+ DriverManager.println(results[0]);
+ DriverManager.setLogWriter(null);
+ assertTrue(DriverManager.getLogWriter() == null);
+ DriverManager.println(noOutput);
+ DriverManager.setLogWriter(pw);
+ DriverManager.println(results[1]);
+ DriverManager.println(results[2]);
+ DriverManager.println(results[3]);
+ DriverManager.setLogWriter(null);
+ DriverManager.println(noOutput);
+
+ /*
+ * Check we do not get the output when the stream is disabled
+ */
+ BufferedReader reader
+ = new BufferedReader(new CharArrayReader(cw.toCharArray()));
+ for (String result : results) {
+ assertTrue(result.equals(reader.readLine()));
+ }
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLClientInfoExceptionTests.java b/jdk/test/java/sql/test/sql/SQLClientInfoExceptionTests.java
new file mode 100644
index 00000000000..84230b86758
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLClientInfoExceptionTests.java
@@ -0,0 +1,227 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.ClientInfoStatus;
+import java.sql.SQLClientInfoException;
+import java.sql.SQLException;
+import java.util.HashMap;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLClientInfoExceptionTests extends BaseTest {
+
+ private final HashMap map = new HashMap<>();
+
+ public SQLClientInfoExceptionTests() {
+ map.put("1", ClientInfoStatus.REASON_UNKNOWN_PROPERTY);
+ map.put("21", ClientInfoStatus.REASON_UNKNOWN_PROPERTY);
+ }
+
+ /**
+ * Create SQLClientInfoException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLClientInfoException e = new SQLClientInfoException(null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == 0
+ && e.getFailedProperties() == null);
+ }
+
+ /**
+ * Create SQLClientInfoException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLClientInfoException ex = new SQLClientInfoException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && ex.getFailedProperties() == null);
+ }
+
+ /**
+ * Create SQLClientInfoException with null Throwable
+ */
+ @Test
+ public void test2() {
+
+ SQLClientInfoException ex = new SQLClientInfoException(map, null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && ex.getFailedProperties().equals(map));
+ }
+
+ /**
+ * Create SQLClientInfoException with message
+ */
+ @Test
+ public void test3() {
+ SQLClientInfoException ex = new SQLClientInfoException(reason, map);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && ex.getFailedProperties().equals(map));
+ }
+
+ /**
+ * Create SQLClientInfoException with null Throwable
+ */
+ @Test
+ public void test4() {
+ SQLClientInfoException ex = new SQLClientInfoException(reason, map, null);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && ex.getFailedProperties().equals(map));
+ }
+
+ /**
+ * Create SQLClientInfoException with message, and SQLState
+ */
+ @Test
+ public void test5() {
+ SQLClientInfoException ex = new SQLClientInfoException(reason, state,
+ map);
+
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0
+ && ex.getFailedProperties().equals(map));
+ }
+
+ /**
+ * Create SQLClientInfoException with message, and SQLState
+ */
+ @Test
+ public void test6() {
+ SQLClientInfoException ex = new SQLClientInfoException(reason, state,
+ map, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0
+ && ex.getFailedProperties().equals(map));
+ }
+
+ /**
+ * Create SQLClientInfoException with message, SQLState, errorCode, and
+ * Throwable
+ */
+ @Test
+ public void test7() {
+ SQLClientInfoException ex = new SQLClientInfoException(reason, state,
+ errorCode, map);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode
+ && ex.getFailedProperties().equals(map));
+ }
+
+ /**
+ * Create SQLClientInfoException with message, SQLState, and error code
+ */
+ @Test
+ public void test8() {
+ SQLClientInfoException ex = new SQLClientInfoException(reason, state,
+ errorCode, map, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode
+ && ex.getFailedProperties().equals(map));
+ }
+
+ /**
+ * Serialize a SQLClientInfoException and make sure you can read it back
+ * properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLClientInfoException e = new SQLClientInfoException(reason, state,
+ errorCode, map, t);
+ SQLClientInfoException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode
+ && ex1.getFailedProperties().equals(map));
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct using
+ * for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLClientInfoException ex = new SQLClientInfoException("Exception 1",
+ map, t1);
+ SQLClientInfoException ex1 = new SQLClientInfoException("Exception 2",
+ map);
+ SQLClientInfoException ex2 = new SQLClientInfoException("Exception 3",
+ map, t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct using
+ * traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLClientInfoException ex = new SQLClientInfoException("Exception 1",
+ map, t1);
+ SQLClientInfoException ex1 = new SQLClientInfoException("Exception 2",
+ map);
+ SQLClientInfoException ex2 = new SQLClientInfoException("Exception 3",
+ map, t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLDataExceptionTests.java b/jdk/test/java/sql/test/sql/SQLDataExceptionTests.java
new file mode 100644
index 00000000000..8a5f8d1a2c1
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLDataExceptionTests.java
@@ -0,0 +1,215 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLDataException;
+import java.sql.SQLException;
+import java.sql.SQLNonTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLDataExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLDataException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLDataException e = new SQLDataException(null, null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLDataException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLDataException ex = new SQLDataException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLDataException with message
+ */
+ @Test
+ public void test2() {
+ SQLDataException ex = new SQLDataException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLDataException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLDataException ex = new SQLDataException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLDataException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLDataException ex = new SQLDataException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLDataException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLDataException ex = new SQLDataException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLDataException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLDataException ex = new SQLDataException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLDataException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLDataException ex = new SQLDataException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLDataException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLDataException ex = new SQLDataException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLDataException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLDataException ex = new SQLDataException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLDataException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLDataException e = new SQLDataException(reason, state, errorCode, t);
+ SQLDataException ex1 = createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLDataException ex = new SQLDataException("Exception 1", t1);
+ SQLDataException ex1 = new SQLDataException("Exception 2");
+ SQLDataException ex2 = new SQLDataException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLDataException ex = new SQLDataException("Exception 1", t1);
+ SQLDataException ex1 = new SQLDataException("Exception 2");
+ SQLDataException ex2 = new SQLDataException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLDataException and validate it is an instance of
+ * SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLDataException();
+ assertTrue(ex instanceof SQLNonTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLExceptionTests.java b/jdk/test/java/sql/test/sql/SQLExceptionTests.java
new file mode 100644
index 00000000000..e3643ef119c
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLExceptionTests.java
@@ -0,0 +1,202 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLException e = new SQLException(null, null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLException ex = new SQLException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLException with message
+ */
+ @Test
+ public void test2() {
+ SQLException ex = new SQLException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLException ex = new SQLException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLException ex = new SQLException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLException ex = new SQLException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLException ex = new SQLException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLException ex = new SQLException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLException ex = new SQLException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLException ex = new SQLException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLException e = new SQLException(reason, state, errorCode, t);
+ SQLException ex1 = createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLException ex = new SQLException("Exception 1", t1);
+ SQLException ex1 = new SQLException("Exception 2");
+ SQLException ex2 = new SQLException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLException ex = new SQLException("Exception 1", t1);
+ SQLException ex1 = new SQLException("Exception 2");
+ SQLException ex2 = new SQLException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ while (ex != null) {
+ assertTrue(msgs[num++].equals(ex.getMessage()));
+ Throwable c = ex.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ ex = ex.getNextException();
+ }
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLFeatureNotSupportedExceptionTests.java b/jdk/test/java/sql/test/sql/SQLFeatureNotSupportedExceptionTests.java
new file mode 100644
index 00000000000..5b95894412c
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLFeatureNotSupportedExceptionTests.java
@@ -0,0 +1,232 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
+import java.sql.SQLNonTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLFeatureNotSupportedExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLFeatureNotSupportedException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLFeatureNotSupportedException e =
+ new SQLFeatureNotSupportedException(null, null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLFeatureNotSupportedException ex = new SQLFeatureNotSupportedException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with message
+ */
+ @Test
+ public void test2() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException((Throwable) null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLFeatureNotSupportedException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLFeatureNotSupportedException e =
+ new SQLFeatureNotSupportedException(reason, state, errorCode, t);
+ SQLFeatureNotSupportedException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException("Exception 1", t1);
+ SQLFeatureNotSupportedException ex1 =
+ new SQLFeatureNotSupportedException("Exception 2");
+ SQLFeatureNotSupportedException ex2 =
+ new SQLFeatureNotSupportedException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLFeatureNotSupportedException ex =
+ new SQLFeatureNotSupportedException("Exception 1", t1);
+ SQLFeatureNotSupportedException ex1 =
+ new SQLFeatureNotSupportedException("Exception 2");
+ SQLFeatureNotSupportedException ex2 =
+ new SQLFeatureNotSupportedException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLFeatureNotSupportedException and validate it is an instance of
+ * SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLFeatureNotSupportedException();
+ assertTrue(ex instanceof SQLNonTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLIntegrityConstraintViolationExceptionTests.java b/jdk/test/java/sql/test/sql/SQLIntegrityConstraintViolationExceptionTests.java
new file mode 100644
index 00000000000..082e0af15c8
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLIntegrityConstraintViolationExceptionTests.java
@@ -0,0 +1,235 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLIntegrityConstraintViolationException;
+import java.sql.SQLNonTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLIntegrityConstraintViolationExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLIntegrityConstraintViolationException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLIntegrityConstraintViolationException e =
+ new SQLIntegrityConstraintViolationException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with message
+ */
+ @Test
+ public void test2() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLIntegrityConstraintViolationException and make sure
+ * you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLIntegrityConstraintViolationException e =
+ new SQLIntegrityConstraintViolationException(reason, state, errorCode, t);
+ SQLIntegrityConstraintViolationException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException("Exception 1", t1);
+ SQLIntegrityConstraintViolationException ex1 =
+ new SQLIntegrityConstraintViolationException("Exception 2");
+ SQLIntegrityConstraintViolationException ex2 =
+ new SQLIntegrityConstraintViolationException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLIntegrityConstraintViolationException ex =
+ new SQLIntegrityConstraintViolationException("Exception 1", t1);
+ SQLIntegrityConstraintViolationException ex1 =
+ new SQLIntegrityConstraintViolationException("Exception 2");
+ SQLIntegrityConstraintViolationException ex2 =
+ new SQLIntegrityConstraintViolationException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLIntegrityConstraintViolationException and validate it is an instance of
+ * SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLIntegrityConstraintViolationException();
+ assertTrue(ex instanceof SQLNonTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLInvalidAuthorizationSpecExceptionTests.java b/jdk/test/java/sql/test/sql/SQLInvalidAuthorizationSpecExceptionTests.java
new file mode 100644
index 00000000000..6e4eaa567ee
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLInvalidAuthorizationSpecExceptionTests.java
@@ -0,0 +1,239 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLInvalidAuthorizationSpecException;
+import java.sql.SQLNonTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLInvalidAuthorizationSpecExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException and setting all objects to
+ * null
+ */
+ @Test
+ public void test() {
+ SQLInvalidAuthorizationSpecException e
+ = new SQLInvalidAuthorizationSpecException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with message
+ */
+ @Test
+ public void test2() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with message, SQLState, and
+ * error code
+ */
+ @Test
+ public void test4() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with message, SQLState,
+ * errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with message, SQLState, and
+ * Throwable
+ */
+ @Test
+ public void test6() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException((Throwable) null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLInvalidAuthorizationSpecException and make sure you can
+ * read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLInvalidAuthorizationSpecException e
+ = new SQLInvalidAuthorizationSpecException(reason, state, errorCode, t);
+ SQLInvalidAuthorizationSpecException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct using
+ * for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException("Exception 1", t1);
+ SQLInvalidAuthorizationSpecException ex1
+ = new SQLInvalidAuthorizationSpecException("Exception 2");
+ SQLInvalidAuthorizationSpecException ex2
+ = new SQLInvalidAuthorizationSpecException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct using
+ * traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLInvalidAuthorizationSpecException ex
+ = new SQLInvalidAuthorizationSpecException("Exception 1", t1);
+ SQLInvalidAuthorizationSpecException ex1
+ = new SQLInvalidAuthorizationSpecException("Exception 2");
+ SQLInvalidAuthorizationSpecException ex2
+ = new SQLInvalidAuthorizationSpecException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLInvalidAuthorizationSpecException and validate it is an
+ * instance of SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLInvalidAuthorizationSpecException();
+ assertTrue(ex instanceof SQLNonTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLNonTransientConnectionExceptionTests.java b/jdk/test/java/sql/test/sql/SQLNonTransientConnectionExceptionTests.java
new file mode 100644
index 00000000000..dbd8b685844
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLNonTransientConnectionExceptionTests.java
@@ -0,0 +1,235 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLNonTransientConnectionException;
+import java.sql.SQLNonTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLNonTransientConnectionExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLNonTransientConnectionException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLNonTransientConnectionException e =
+ new SQLNonTransientConnectionException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with message
+ */
+ @Test
+ public void test2() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLNonTransientConnectionException and make sure you can
+ * read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLNonTransientConnectionException e =
+ new SQLNonTransientConnectionException(reason, state, errorCode, t);
+ SQLNonTransientConnectionException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException("Exception 1", t1);
+ SQLNonTransientConnectionException ex1 =
+ new SQLNonTransientConnectionException("Exception 2");
+ SQLNonTransientConnectionException ex2 =
+ new SQLNonTransientConnectionException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLNonTransientConnectionException ex =
+ new SQLNonTransientConnectionException("Exception 1", t1);
+ SQLNonTransientConnectionException ex1 =
+ new SQLNonTransientConnectionException("Exception 2");
+ SQLNonTransientConnectionException ex2 =
+ new SQLNonTransientConnectionException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLNonTransientConnectionException and validate it is an instance of
+ * SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLNonTransientConnectionException();
+ assertTrue(ex instanceof SQLNonTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLNonTransientExceptionTests.java b/jdk/test/java/sql/test/sql/SQLNonTransientExceptionTests.java
new file mode 100644
index 00000000000..061ffe20840
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLNonTransientExceptionTests.java
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLNonTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLNonTransientExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLNonTransientException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLNonTransientException e = new SQLNonTransientException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLNonTransientException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLNonTransientException ex = new SQLNonTransientException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientException with message
+ */
+ @Test
+ public void test2() {
+ SQLNonTransientException ex = new SQLNonTransientException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLNonTransientException ex = new SQLNonTransientException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {;
+ SQLNonTransientException ex =
+ new SQLNonTransientException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLNonTransientException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLNonTransientException ex =
+ new SQLNonTransientException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLNonTransientException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLNonTransientException ex = new SQLNonTransientException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLNonTransientException ex = new SQLNonTransientException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLNonTransientException ex = new SQLNonTransientException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLNonTransientException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLNonTransientException ex = new SQLNonTransientException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLNonTransientException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLNonTransientException e =
+ new SQLNonTransientException(reason, state, errorCode, t);
+ SQLNonTransientException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLNonTransientException ex = new SQLNonTransientException("Exception 1", t1);
+ SQLNonTransientException ex1 = new SQLNonTransientException("Exception 2");
+ SQLNonTransientException ex2 = new SQLNonTransientException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLNonTransientException ex = new SQLNonTransientException("Exception 1", t1);
+ SQLNonTransientException ex1 = new SQLNonTransientException("Exception 2");
+ SQLNonTransientException ex2 = new SQLNonTransientException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLRecoverableExceptionTests.java b/jdk/test/java/sql/test/sql/SQLRecoverableExceptionTests.java
new file mode 100644
index 00000000000..d23a131dbcd
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLRecoverableExceptionTests.java
@@ -0,0 +1,209 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLRecoverableException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLRecoverableExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLRecoverableException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLRecoverableException e = new SQLRecoverableException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLRecoverableException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLRecoverableException ex = new SQLRecoverableException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLRecoverableException with message
+ */
+ @Test
+ public void test2() {
+ SQLRecoverableException ex = new SQLRecoverableException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLRecoverableException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLRecoverableException ex = new SQLRecoverableException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLRecoverableException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLRecoverableException ex =
+ new SQLRecoverableException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLRecoverableException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLRecoverableException ex =
+ new SQLRecoverableException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLRecoverableException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLRecoverableException ex = new SQLRecoverableException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLRecoverableException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLRecoverableException ex = new SQLRecoverableException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLRecoverableException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLRecoverableException ex = new SQLRecoverableException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLRecoverableException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLRecoverableException ex = new SQLRecoverableException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLRecoverableException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLRecoverableException e =
+ new SQLRecoverableException(reason, state, errorCode, t);
+ SQLRecoverableException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLRecoverableException ex = new SQLRecoverableException("Exception 1", t1);
+ SQLRecoverableException ex1 = new SQLRecoverableException("Exception 2");
+ SQLRecoverableException ex2 = new SQLRecoverableException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLRecoverableException ex = new SQLRecoverableException("Exception 1", t1);
+ SQLRecoverableException ex1 = new SQLRecoverableException("Exception 2");
+ SQLRecoverableException ex2 = new SQLRecoverableException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLSyntaxErrorExceptionTests.java b/jdk/test/java/sql/test/sql/SQLSyntaxErrorExceptionTests.java
new file mode 100644
index 00000000000..863213cfcb8
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLSyntaxErrorExceptionTests.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLNonTransientException;
+import java.sql.SQLSyntaxErrorException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLSyntaxErrorExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLSyntaxErrorException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLSyntaxErrorException e = new SQLSyntaxErrorException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with message
+ */
+ @Test
+ public void test2() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLSyntaxErrorException ex =
+ new SQLSyntaxErrorException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLSyntaxErrorException ex =
+ new SQLSyntaxErrorException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLSyntaxErrorException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLSyntaxErrorException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+
+ SQLSyntaxErrorException e =
+ new SQLSyntaxErrorException(reason, state, errorCode, t);
+ SQLSyntaxErrorException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException("Exception 1", t1);
+ SQLSyntaxErrorException ex1 = new SQLSyntaxErrorException("Exception 2");
+ SQLSyntaxErrorException ex2 = new SQLSyntaxErrorException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLSyntaxErrorException ex = new SQLSyntaxErrorException("Exception 1", t1);
+ SQLSyntaxErrorException ex1 = new SQLSyntaxErrorException("Exception 2");
+ SQLSyntaxErrorException ex2 = new SQLSyntaxErrorException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLSyntaxErrorException and validate it is an instance of
+ * SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLSyntaxErrorException();
+ assertTrue(ex instanceof SQLNonTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLTimeoutExceptionTests.java b/jdk/test/java/sql/test/sql/SQLTimeoutExceptionTests.java
new file mode 100644
index 00000000000..dfe341545e4
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLTimeoutExceptionTests.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLTimeoutException;
+import java.sql.SQLTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLTimeoutExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLTimeoutException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLTimeoutException e = new SQLTimeoutException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTimeoutException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLTimeoutException ex = new SQLTimeoutException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTimeoutException with message
+ */
+ @Test
+ public void test2() {
+ SQLTimeoutException ex = new SQLTimeoutException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTimeoutException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLTimeoutException ex = new SQLTimeoutException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTimeoutException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLTimeoutException ex = new SQLTimeoutException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTimeoutException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLTimeoutException ex = new SQLTimeoutException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTimeoutException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLTimeoutException ex = new SQLTimeoutException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTimeoutException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLTimeoutException ex = new SQLTimeoutException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTimeoutException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLTimeoutException ex = new SQLTimeoutException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTimeoutException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLTimeoutException ex = new SQLTimeoutException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLTimeoutException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLTimeoutException e =
+ new SQLTimeoutException(reason, state, errorCode, t);
+ SQLTimeoutException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLTimeoutException ex = new SQLTimeoutException("Exception 1", t1);
+ SQLTimeoutException ex1 = new SQLTimeoutException("Exception 2");
+ SQLTimeoutException ex2 = new SQLTimeoutException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLTimeoutException ex = new SQLTimeoutException("Exception 1", t1);
+ SQLTimeoutException ex1 = new SQLTimeoutException("Exception 2");
+ SQLTimeoutException ex2 = new SQLTimeoutException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLTimeoutException and validate it is an instance of
+ * SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLTimeoutException();
+ assertTrue(ex instanceof SQLTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLTransactionRollbackExceptionTests.java b/jdk/test/java/sql/test/sql/SQLTransactionRollbackExceptionTests.java
new file mode 100644
index 00000000000..8453ebe1364
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLTransactionRollbackExceptionTests.java
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLTransactionRollbackException;
+import java.sql.SQLTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLTransactionRollbackExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLTransactionRollbackException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLTransactionRollbackException e =
+ new SQLTransactionRollbackException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLTransactionRollbackException ex = new SQLTransactionRollbackException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with message
+ */
+ @Test
+ public void test2() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransactionRollbackException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLTransactionRollbackException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLTransactionRollbackException e =
+ new SQLTransactionRollbackException(reason, state, errorCode, t);
+ SQLTransactionRollbackException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException("Exception 1", t1);
+ SQLTransactionRollbackException ex1 =
+ new SQLTransactionRollbackException("Exception 2");
+ SQLTransactionRollbackException ex2 =
+ new SQLTransactionRollbackException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLTransactionRollbackException ex =
+ new SQLTransactionRollbackException("Exception 1", t1);
+ SQLTransactionRollbackException ex1 =
+ new SQLTransactionRollbackException("Exception 2");
+ SQLTransactionRollbackException ex2 =
+ new SQLTransactionRollbackException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLTransactionRollbackException and validate it is an instance of
+ * SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLTransactionRollbackException();
+ assertTrue(ex instanceof SQLTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLTransientConnectionExceptionTests.java b/jdk/test/java/sql/test/sql/SQLTransientConnectionExceptionTests.java
new file mode 100644
index 00000000000..7999253b1fa
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLTransientConnectionExceptionTests.java
@@ -0,0 +1,233 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLTransientConnectionException;
+import java.sql.SQLTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLTransientConnectionExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLTransientConnectionException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLTransientConnectionException e =
+ new SQLTransientConnectionException( null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLTransientConnectionException ex = new SQLTransientConnectionException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with message
+ */
+ @Test
+ public void test2() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {;
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientConnectionException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLTransientConnectionException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLTransientConnectionException e =
+ new SQLTransientConnectionException(reason, state, errorCode, t);
+ SQLTransientConnectionException ex1 =
+ createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException("Exception 1", t1);
+ SQLTransientConnectionException ex1 =
+ new SQLTransientConnectionException("Exception 2");
+ SQLTransientConnectionException ex2 =
+ new SQLTransientConnectionException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLTransientConnectionException ex =
+ new SQLTransientConnectionException("Exception 1", t1);
+ SQLTransientConnectionException ex1 =
+ new SQLTransientConnectionException("Exception 2");
+ SQLTransientConnectionException ex2 =
+ new SQLTransientConnectionException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Create SQLTransientConnectionException and validate it is an instance of
+ * SQLNonTransientException
+ */
+ @Test
+ public void test13() {
+ Exception ex = new SQLTransientConnectionException();
+ assertTrue(ex instanceof SQLTransientException);
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLTransientExceptionTests.java b/jdk/test/java/sql/test/sql/SQLTransientExceptionTests.java
new file mode 100644
index 00000000000..d86f86b8fc6
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLTransientExceptionTests.java
@@ -0,0 +1,207 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLTransientException;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLTransientExceptionTests extends BaseTest {
+
+ /**
+ * Create SQLTransientException and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLTransientException e = new SQLTransientException(null,
+ null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransientException with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLTransientException ex = new SQLTransientException();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientException with message
+ */
+ @Test
+ public void test2() {
+ SQLTransientException ex = new SQLTransientException(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientException with message, and SQLState
+ */
+ @Test
+ public void test3() {
+ SQLTransientException ex = new SQLTransientException(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientException with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLTransientException ex = new SQLTransientException(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransientException with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLTransientException ex =
+ new SQLTransientException(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLTransientException with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLTransientException ex = new SQLTransientException(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientException with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLTransientException ex = new SQLTransientException(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientException with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLTransientException ex = new SQLTransientException((Throwable)null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLTransientException with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLTransientException ex = new SQLTransientException(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLTransientException and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLTransientException e =
+ new SQLTransientException(reason, state, errorCode, t);
+ SQLTransientException ex1 = createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLTransientException ex = new SQLTransientException("Exception 1", t1);
+ SQLTransientException ex1 = new SQLTransientException("Exception 2");
+ SQLTransientException ex2 = new SQLTransientException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct
+ * using traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLTransientException ex = new SQLTransientException("Exception 1", t1);
+ SQLTransientException ex1 = new SQLTransientException("Exception 2");
+ SQLTransientException ex2 = new SQLTransientException("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/SQLWarningTests.java b/jdk/test/java/sql/test/sql/SQLWarningTests.java
new file mode 100644
index 00000000000..2856742dc5c
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/SQLWarningTests.java
@@ -0,0 +1,249 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import static org.testng.Assert.*;
+import org.testng.annotations.Test;
+import util.BaseTest;
+
+public class SQLWarningTests extends BaseTest {
+
+ private final String[] warnings = {"Warning 1", "cause 1", "Warning 2",
+ "Warning 3", "cause 2"};
+
+ /**
+ * Create SQLWarning and setting all objects to null
+ */
+ @Test
+ public void test() {
+ SQLWarning e = new SQLWarning(null, null, errorCode, null);
+ assertTrue(e.getMessage() == null && e.getSQLState() == null
+ && e.getCause() == null && e.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLWarning with no-arg constructor
+ */
+ @Test
+ public void test1() {
+ SQLWarning ex = new SQLWarning();
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLWarning with message
+ */
+ @Test
+ public void test2() {
+ SQLWarning ex = new SQLWarning(reason);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLWarning with message, and SQLState
+ */
+ @Test
+ public void test3() {
+
+ SQLWarning ex = new SQLWarning(reason, state);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLWarning with message, SQLState, and error code
+ */
+ @Test
+ public void test4() {
+ SQLWarning ex = new SQLWarning(reason, state, errorCode);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && ex.getCause() == null
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLWarning with message, SQLState, errorCode, and Throwable
+ */
+ @Test
+ public void test5() {
+ SQLWarning ex = new SQLWarning(reason, state, errorCode, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Create SQLWarning with message, SQLState, and Throwable
+ */
+ @Test
+ public void test6() {
+ SQLWarning ex = new SQLWarning(reason, state, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState().equals(state)
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLWarning with message, and Throwable
+ */
+ @Test
+ public void test7() {
+ SQLWarning ex = new SQLWarning(reason, t);
+ assertTrue(ex.getMessage().equals(reason)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLWarning with null Throwable
+ */
+ @Test
+ public void test8() {
+ SQLWarning ex = new SQLWarning((Throwable) null);
+ assertTrue(ex.getMessage() == null
+ && ex.getSQLState() == null
+ && ex.getCause() == null
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Create SQLWarning with Throwable
+ */
+ @Test
+ public void test9() {
+ SQLWarning ex = new SQLWarning(t);
+ assertTrue(ex.getMessage().equals(cause)
+ && ex.getSQLState() == null
+ && cause.equals(ex.getCause().toString())
+ && ex.getErrorCode() == 0);
+ }
+
+ /**
+ * Serialize a SQLWarning and make sure you can read it back properly
+ */
+ @Test
+ public void test10() throws Exception {
+ SQLWarning e = new SQLWarning(reason, state, errorCode, t);
+ SQLWarning ex1 = createSerializedException(e);
+ assertTrue(reason.equals(ex1.getMessage())
+ && ex1.getSQLState().equals(state)
+ && cause.equals(ex1.getCause().toString())
+ && ex1.getErrorCode() == errorCode);
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct using
+ * for-each loop
+ */
+ @Test
+ public void test11() {
+ SQLWarning ex = new SQLWarning("Exception 1", t1);
+ SQLWarning ex1 = new SQLWarning("Exception 2");
+ SQLWarning ex2 = new SQLWarning("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(msgs[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned Exceptions is correct using
+ * traditional while loop
+ */
+ @Test
+ public void test12() {
+ SQLWarning ex = new SQLWarning("Exception 1", t1);
+ SQLWarning ex1 = new SQLWarning("Exception 2");
+ SQLWarning ex2 = new SQLWarning("Exception 3", t2);
+ ex.setNextException(ex1);
+ ex.setNextException(ex2);
+ int num = 0;
+ SQLException sqe = ex;
+ while (sqe != null) {
+ assertTrue(msgs[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextException();
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned SQLWarning is correct using
+ * for-each loop
+ */
+ @Test
+ public void test13() {
+ SQLWarning ex = new SQLWarning("Warning 1", t1);
+ SQLWarning ex1 = new SQLWarning("Warning 2");
+ SQLWarning ex2 = new SQLWarning("Warning 3", t2);
+ ex.setNextWarning(ex1);
+ ex.setNextWarning(ex2);
+ int num = 0;
+ for (Throwable e : ex) {
+ assertTrue(warnings[num++].equals(e.getMessage()));
+ }
+ }
+
+ /**
+ * Validate that the ordering of the returned SQLWarning is correct using
+ * traditional while loop
+ */
+ @Test
+ public void test14() {
+ SQLWarning ex = new SQLWarning("Warning 1", t1);
+ SQLWarning ex1 = new SQLWarning("Warning 2");
+ SQLWarning ex2 = new SQLWarning("Warning 3", t2);
+ ex.setNextWarning(ex1);
+ ex.setNextWarning(ex2);
+ int num = 0;
+ SQLWarning sqe = ex;
+ while (sqe != null) {
+ assertTrue(warnings[num++].equals(sqe.getMessage()));
+ Throwable c = sqe.getCause();
+ while (c != null) {
+ assertTrue(msgs[num++].equals(c.getMessage()));
+ c = c.getCause();
+ }
+ sqe = sqe.getNextWarning();
+ }
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/TimeTests.java b/jdk/test/java/sql/test/sql/TimeTests.java
new file mode 100644
index 00000000000..4064c37d18e
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/TimeTests.java
@@ -0,0 +1,376 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.Time;
+import java.time.LocalTime;
+import static org.testng.Assert.*;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class TimeTests {
+
+ public TimeTests() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception {
+ }
+
+ @BeforeMethod
+ public void setUpMethod() throws Exception {
+ }
+
+ @AfterMethod
+ public void tearDownMethod() throws Exception {
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling getYear
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test1() {
+ Time t = Time.valueOf("08:30:59");
+ t.getYear();
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling getMonth
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test2() {
+ Time t = Time.valueOf("08:30:59");
+ t.getMonth();
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling getDay
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test3() {
+ Time t = Time.valueOf("08:30:59");
+ t.getDay();
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling getDate
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test4() {
+ Time t = Time.valueOf("08:30:59");
+ t.getDate();
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling setYear
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test5() {
+ Time t = Time.valueOf("08:30:59");
+ t.setYear(8);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling setMonth
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test6() {
+ Time t = Time.valueOf("08:30:59");
+ t.setMonth(8);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling setDate
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test7() {
+ Time t = Time.valueOf("08:30:59");
+ t.setDate(30);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling getDate
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test8() {
+ Time t = Time.valueOf("08:30:59");
+ t.getDate();
+ }
+
+ /**
+ * Validate that a Time made from a toLocalTime() LocalTime are equal
+ */
+ @Test
+ public void test13() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = Time.valueOf(t.toLocalTime());
+ assertTrue(t.equals(t2), "Error t != t2");
+ }
+
+ /**
+ * Validate that a Time LocalTime value, made from a LocalTime are equal
+ */
+ @Test
+ public void test14() {
+ LocalTime lt = LocalTime.of(8, 30, 59);
+ Time t = Time.valueOf(lt);
+ System.out.println("lt=" + lt + ",t=" + t.toLocalTime());
+ assertTrue(lt.equals(t.toLocalTime()),
+ "Error LocalTime values are not equal");
+ }
+
+ /**
+ * Validate an NPE occurs when a null LocalDate is passed to valueOf
+ */
+ @Test(expectedExceptions = NullPointerException.class)
+ public void test15() throws Exception {
+ LocalTime ld = null;
+ Time.valueOf(ld);
+ }
+
+ /**
+ * Validate an UnsupportedOperationException occurs when toInstant() is
+ * called
+ */
+ @Test(expectedExceptions = UnsupportedOperationException.class)
+ public void test16() throws Exception {
+ Time t = new Time(System.currentTimeMillis());
+ t.toInstant();
+ }
+
+ /**
+ * Validate that a Time made from valueOf(String) returns the same String
+ * from Time.toString();
+ */
+ @Test
+ public void test17() {
+ String time = "08:30:59";
+ Time t = Time.valueOf(time);
+ assertTrue(time.equals(t.toString()), "Error t != t2");
+ }
+
+ /**
+ * Validate that two Time objects are equal when one is created from the
+ * toString() of the other
+ */
+ @Test
+ public void test18() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = Time.valueOf(t.toString());
+ assertTrue(t.equals(t2) && t2.equals(t), "Error t != t2");
+ }
+
+ /**
+ * Validate that two Time values one created using valueOf and another via a
+ * constructor are equal
+ */
+ @Test
+ public void test19() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(8, 30, 59);
+ assertTrue(t.equals(t2) && t2.equals(t), "Error t != t2");
+ }
+
+ /**
+ * Validate that two Time values one created using valueOf and another via a
+ * constructor are equal
+ */
+ @Test
+ public void test20() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(t.getTime());
+ assertTrue(t.equals(t2) && t2.equals(t), "Error t != t2");
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for calling valueOf with a
+ * null String
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test21() {
+ String time = null;
+ Time t = Time.valueOf(time);
+
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Time string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test22() throws Exception {
+ Time.valueOf("1961-08-30");
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Time string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test23() throws Exception {
+ Time.valueOf("8:");
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Time string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test24() throws Exception {
+ Time.valueOf("a:b:c");
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Time string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test25() throws Exception {
+ Time.valueOf("08:10");
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Time string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test26() throws Exception {
+ Time.valueOf("08:10:10:10");
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Time string
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test27() throws Exception {
+ Time.valueOf("08:10:Batman");
+ }
+
+ /**
+ * Validate that Time.after() returns false when same date is compared
+ */
+ @Test
+ public void test28() {
+ Time t = Time.valueOf("08:30:59");
+ assertFalse(t.after(t), "Error t.after(t) = true");
+ }
+
+ /**
+ * Validate that Time.after() returns true when later date is compared to
+ * earlier date
+ */
+ @Test
+ public void test29() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(System.currentTimeMillis());
+ assertTrue(t2.after(t), "Error t2.after(t) = false");
+ }
+
+ /**
+ * Validate that Time.after() returns false when earlier date is compared to
+ * itself
+ */
+ @Test
+ public void test30() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(t.getTime());
+ assertFalse(t.after(t2), "Error t.after(t2) = true");
+ assertFalse(t2.after(t), "Error t2.after(t) = true");
+ }
+
+ /**
+ * Validate that Time.before() returns false when same date is compared
+ */
+ @Test
+ public void test31() {
+ Time t = Time.valueOf("08:30:59");
+ assertFalse(t.before(t), "Error t.before(t) = true");
+ }
+
+ /**
+ * Validate that Time.before() returns true when earlier date is compared to
+ * later date
+ */
+ @Test
+ public void test32() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(System.currentTimeMillis());
+ assertTrue(t.before(t2), "Error t.before(t2) = false");
+ }
+
+ /**
+ * Validate that Time.before() returns false when earlier date is compared
+ * to itself
+ */
+ @Test
+ public void test33() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(t.getTime());
+ assertFalse(t.before(t2), "Error t.after(t2) = true");
+ assertFalse(t2.before(t), "Error t2.after(t) = true");
+ }
+
+ /**
+ * Validate that Time.compareTo returns 0 when both Date objects are the
+ * same
+ */
+ @Test
+ public void test34() {
+ Time t = Time.valueOf("08:30:59");
+ assertTrue(t.compareTo(t) == 0, "Error t.compareTo(t) !=0");
+ }
+
+ /**
+ * Validate thatTime.compareTo returns 0 when both Time objects are the same
+ */
+ @Test
+ public void test35() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(t.getTime());
+ assertTrue(t.compareTo(t2) == 0, "Error t.compareTo(t2) !=0");
+ }
+
+ /**
+ * Validate that Time.compareTo returns 1 when comparing a later Time to an
+ * earlier Time
+ */
+ @Test
+ public void test36() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(t.getTime() + 1);
+ assertTrue(t2.compareTo(t) == 1, "Error t2.compareTo(t) !=1");
+ }
+
+ /**
+ * Validate thatTime.compareTo returns 1 when comparing a later Time to an
+ * earlier Time
+ */
+ @Test
+ public void test37() {
+ Time t = Time.valueOf("08:30:59");
+ Time t2 = new Time(t.getTime() + 1);
+ assertTrue(t.compareTo(t2) == -1, "Error t.compareTo(t2) != -1");
+ }
+}
diff --git a/jdk/test/java/sql/test/sql/TimestampTests.java b/jdk/test/java/sql/test/sql/TimestampTests.java
new file mode 100644
index 00000000000..ac87f16c013
--- /dev/null
+++ b/jdk/test/java/sql/test/sql/TimestampTests.java
@@ -0,0 +1,640 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.sql;
+
+import java.sql.Date;
+import java.sql.Time;
+import java.sql.Timestamp;
+import java.time.Instant;
+import java.time.LocalDateTime;
+import java.util.Calendar;
+import static org.testng.Assert.*;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+public class TimestampTests {
+
+ public TimestampTests() {
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception {
+ }
+
+ @BeforeMethod
+ public void setUpMethod() throws Exception {
+ }
+
+ @AfterMethod
+ public void tearDownMethod() throws Exception {
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Timestamp
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_timestamp() throws Exception {
+ String testTS = "2009-11-01-01 10:50";
+ Timestamp.valueOf(testTS);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Timestamp
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_year2() throws Exception {
+ String testTS = "aaaa-11-01-01 10:50";
+ Timestamp.valueOf(testTS);
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid Timestamp
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void testInvalid_year3() throws Exception {
+ String testTS = "aaaa-11-01 10:50";
+ Timestamp.valueOf(testTS);
+ }
+
+ /**
+ * Validate that two Timestamp are equal when the leading 0 in seconds is
+ * omitted
+ */
+ @Test
+ public void test1() throws Exception {
+ String testTS = "2009-01-01 10:50:00";
+ String ExpectedTS = "2009-01-01 10:50:0";
+ Timestamp ts = Timestamp.valueOf(testTS);
+ Timestamp ts2 = Timestamp.valueOf(ExpectedTS);
+ assertEquals(ts, ts2, "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate two Timestamps created from the same string are equal
+ */
+ @Test
+ public void test2() throws Exception {
+ String testTS = "2009-01-01 10:50:0";
+ Timestamp ts = Timestamp.valueOf(testTS);
+ Timestamp ts2 = Timestamp.valueOf(testTS);
+ assertEquals(ts, ts2, "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that two Timestamp values one with leading 0s for month and day
+ * equals same string without the leading 0s.
+ */
+ @Test
+ public void test3() throws Exception {
+ String testTS = "2009-1-1 10:50:0";
+ String ExpectedTS = "2009-01-01 10:50:0";
+ Timestamp ts = Timestamp.valueOf(testTS);
+ Timestamp ts2 = Timestamp.valueOf(ExpectedTS);
+ assertEquals(ts, ts2, "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that two Timestamp values one with leading 0s for day omitted
+ * are equal
+ */
+ @Test
+ public void test4() throws Exception {
+ String testTS = "2009-01-1 10:50:0";
+ String ExpectedTS = "2009-01-01 10:50:0";
+ Timestamp ts = Timestamp.valueOf(testTS);
+ Timestamp ts2 = Timestamp.valueOf(ExpectedTS);
+ assertEquals(ts, ts2, "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that two Timestamp values one with leading 0s for month omitted
+ * and both with leading 0s for seconds omitted are equal
+ */
+ @Test
+ public void test5() throws Exception {
+ String testTS = "2009-1-01 10:50:0";
+ String ExpectedTS = "2009-01-01 10:50:0";
+ Timestamp ts = Timestamp.valueOf(testTS);
+ Timestamp ts2 = Timestamp.valueOf(ExpectedTS);
+ assertEquals(ts, ts2, "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that two Timestamp values one with leading 0s for month omitted
+ */
+ @Test
+ public void test6() throws Exception {
+ String testTS = "2005-1-01 10:20:50.00";
+ String ExpectedTS = "2005-01-01 10:20:50.00";
+ Timestamp ts = Timestamp.valueOf(testTS);
+ Timestamp ts2 = Timestamp.valueOf(ExpectedTS);
+ assertEquals(ts, ts2, "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that two Timestamp values one created using valueOf and another
+ * via a constructor are equal
+ */
+ @Test
+ public void test7() {
+
+ Timestamp ts1 = Timestamp.valueOf("1996-12-13 14:15:25.001");
+ Timestamp ts2 = new Timestamp(96, 11, 13, 14, 15, 25, 1000000);
+ assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that two Timestamp values one created using valueOf and another
+ * via a constructor are equal
+ */
+ @Test
+ public void test8() {
+ Timestamp ts1 = Timestamp.valueOf("1996-12-13 14:15:25.001");
+ Timestamp ts2 = new Timestamp(ts1.getTime());
+ assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that two Timestamp values one created using valueOf and another
+ * via a constructor are equal
+ */
+ @Test
+ public void test9() {
+
+ Timestamp ts1 = Timestamp.valueOf("1996-12-13 14:15:25.0");
+ Timestamp ts2 = new Timestamp(96, 11, 13, 14, 15, 25, 0);
+ assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that a Timestamp cannot be equal to null
+ */
+ @Test
+ public void test10() {
+
+ Timestamp ts1 = Timestamp.valueOf("1961-08-30 14:15:25.745634");
+ assertFalse(ts1.equals(null), "Error ts1 == null");
+ }
+
+ /**
+ * Validate that a Timestamp is equal to another timestamp created with the
+ * using the same value but not equal to a Timestamp which is one day later
+ */
+ @Test
+ public void test11() {
+
+ Timestamp ts1 = Timestamp.valueOf("1996-12-10 12:26:19.12");
+ Timestamp ts2 = Timestamp.valueOf("1996-12-10 12:26:19.12");
+ Timestamp ts3 = Timestamp.valueOf("1996-12-11 12:24:19.12");
+ assertTrue(ts1.equals(ts2) && ts2.equals(ts1), "Error ts1 != ts2");
+ assertFalse(ts1.equals(ts3) && ts3.equals(ts1), "Error ts1 == ts3");
+
+ }
+
+ /**
+ * Validate that a Timestamp is equal to itself
+ */
+ @Test
+ public void test12() {
+ Timestamp ts1 = Timestamp.valueOf("1996-10-15 12:26:19.12");
+ assertTrue(ts1.equals(ts1), "Error ts1 != ts1");
+ }
+
+ /**
+ * Validate that two Timestamps are equal when one is created from the
+ * toString() of the other
+ */
+ @Test
+ public void test13() {
+ Timestamp ts1 = Timestamp.valueOf("1996-12-10 12:26:19.12");
+ Timestamp ts2 = Timestamp.valueOf(ts1.toString());
+ assertTrue(ts1.equals(ts2) && ts2.equals(ts1), "Error ts1 != ts2");
+ }
+
+ // Before Tests
+ /**
+ * Validate that Timestamp ts1 is before Timestamp ts2
+ */
+ @Test
+ public void test14() {
+ Timestamp ts1 = Timestamp.valueOf("1996-12-13 14:15:25.745634");
+ Timestamp ts2 = Timestamp.valueOf("1996-12-13 15:15:25.645634");
+ assertTrue(ts1.before(ts2), "Error ts1 not before ts2");
+ }
+
+ /**
+ * Validate that Timestamp ts1 is before Timestamp ts2
+ */
+ @Test
+ public void test15() {
+ Timestamp ts1 = Timestamp.valueOf("1961-08-30 14:15:25");
+ Timestamp ts2 = Timestamp.valueOf("1999-12-13 15:15:25");
+ assertTrue(ts1.before(ts2), "Error ts1 not before ts2");
+ }
+
+ /**
+ * Validate that Timestamp ts1 is before Timestamp ts2
+ */
+ @Test
+ public void test16() {
+
+ Timestamp ts1 = Timestamp.valueOf("1999-12-13 14:15:25.745634");
+ Timestamp ts2 = Timestamp.valueOf("1999-11-13 15:15:25.645634");
+ assertFalse(ts1.before(ts2), "Error ts1 before ts2");
+ }
+
+ /*
+ * Validate that a NullPointerException is thrown if a null is passed to
+ * the before method
+ */
+ @Test(expectedExceptions = NullPointerException.class)
+ public void test17() throws Exception {
+ Timestamp ts1 = Timestamp.valueOf("1996-12-13 14:15:25.745634");
+ ts1.before(null);
+ }
+
+ /*
+ * Validate a Timestamp cannot be before itself
+ */
+ @Test
+ public void test18() {
+ Timestamp ts1 = Timestamp.valueOf("1999-11-10 12:26:19.3456543");
+ assertFalse(ts1.before(ts1), "Error ts1 before ts1!");
+ }
+
+ /**
+ * Create 3 Timestamps and make sure the 1st is before the other two
+ * Timestamps which are each greater than the one before it
+ */
+ @Test
+ public void test19() {
+
+ Timestamp ts1 = new Timestamp(1234560000);
+ Timestamp ts2 = new Timestamp(1234567000);
+ Timestamp ts3 = new Timestamp(1234569000);
+ assertTrue(ts1.before(ts2) && ts2.before(ts3) && ts1.before(ts3));
+ }
+
+ /**
+ * Validate that Timestamp ts1 is not after Timestamp ts2
+ */
+ @Test
+ public void test20() {
+ Timestamp ts1 = Timestamp.valueOf("1999-12-13 14:15:25.745634");
+ Timestamp ts2 = Timestamp.valueOf("1999-12-13 15:15:25.645634");
+ assertFalse(ts1.after(ts2), "Error ts1 is after ts2");
+
+ }
+
+ /**
+ * Validate that Timestamp ts1 is after Timestamp ts2
+ */
+ @Test
+ public void test21() {
+ Timestamp ts1 = Timestamp.valueOf("1996-12-13 14:15:25.745634");
+ Timestamp ts2 = Timestamp.valueOf("1996-11-13 15:15:25.645634");
+ assertTrue(ts1.after(ts2), "Error ts1 not after ts2");
+ }
+
+ /**
+ * Validate that a NullPointerException is thrown if a null is passed to the
+ * after method
+ */
+ @Test(expectedExceptions = NullPointerException.class)
+ public void test22() throws Exception {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ ts1.after(null);
+ }
+
+ /**
+ * Validate that a Timestamp cannot be after itself
+ */
+ @Test
+ public void test23() {
+ Timestamp ts1 = Timestamp.valueOf("1999-11-10 12:26:19.3456543");
+ assertFalse(ts1.after(ts1), "Error ts1 is after itself");
+ }
+ /**
+ * Validate that a Timestamp after() works correctly with Timestamp
+ * created using milliseconds
+ */
+ @Test
+ public void test24() {
+
+ Timestamp ts1 = new Timestamp(1234568000);
+ Timestamp ts2 = new Timestamp(1234565000);
+ Timestamp ts3 = new Timestamp(1234562000);
+ assertTrue(ts1.after(ts2) && ts2.after(ts3) && ts1.after(ts3));
+ }
+
+ /**
+ * Validate compareTo returns 0 for Timestamps that are the same
+ */
+ @Test
+ public void test25() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ Timestamp ts2 = new Timestamp(ts1.getTime());
+ assertTrue(ts1.compareTo(ts2) == 0, "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate compareTo returns -1 for when the 1st Timestamp is earlier than
+ * the 2nd Timestamp
+ */
+ @Test
+ public void test26() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ Timestamp ts2 = new Timestamp(ts1.getTime() + 1000);
+ assertTrue(ts1.compareTo(ts2) == -1, "Error ts1 not before ts2");
+ assertTrue(ts2.compareTo(ts1) == 1, "Error ts1 is not before ts2");
+ }
+
+ /**
+ * Validate compareTo returns 1 for when the 1st Timestamp is later than the
+ * 2nd Timestamp
+ */
+ @Test
+ public void test27() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ Timestamp ts2 = new Timestamp(ts1.getTime() - 1000);
+ assertTrue(ts1.compareTo(ts2) == 1, "Error ts1 not after ts2");
+ assertTrue(ts2.compareTo(ts1) == -1, "Error ts1 not after ts2");
+ }
+
+ /**
+ * Validate compareTo returns 0 for Timestamps that are the same
+ */
+ @Test
+ public void test28() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ java.util.Date ts2 = new java.util.Date(ts1.getTime());
+ assertTrue(ts1.compareTo(ts2) == 0, "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate compareTo returns 0 for Timestamps that are the same
+ */
+ @Test
+ public void test29() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ java.util.Date d = new java.util.Date(ts1.getTime());
+ assertFalse(ts1.equals(d), "Error ts1 == d");
+ }
+
+ /**
+ * Validate compareTo returns 0 for Timestamps that are the same
+ */
+ @Test
+ public void test30() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ java.util.Date d = new Timestamp(ts1.getTime());
+ assertTrue(ts1.equals(d), "Error ts1 != d");
+ }
+
+ /**
+ * Validate equals returns false when a Date object is passed to equals
+ */
+ @Test
+ public void test31() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ Date d = new Date(ts1.getTime());
+ assertFalse(ts1.equals(d), "Error ts1 != d");
+ }
+
+ /**
+ * Validate equals returns false when a Date object is passed to equals
+ */
+ @Test
+ public void test32() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ java.util.Date d = new Date(ts1.getTime());
+ assertFalse(ts1.equals(d), "Error ts1 != d");
+ }
+
+ /**
+ * Validate equals returns false when a Time object is passed to equals
+ */
+ @Test
+ public void test33() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ Time t1 = new Time(ts1.getTime());
+ assertFalse(ts1.equals(t1), "Error ts1 == t1");
+ }
+
+ /**
+ * Validate equals returns false when a String object is passed to equals
+ */
+ @Test
+ public void test34() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ assertFalse(ts1.equals("1966-08-30 08:08:08"), "Error ts1 == a String");
+ }
+
+ /**
+ * Validate getTime() returns the same value from 2 timeStamps created by
+ */
+ @Test
+ public void test35() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ Timestamp ts2 = Timestamp.valueOf("1966-08-30 08:08:08");
+ assertTrue(ts2.getTime() == ts1.getTime(),
+ "ts1.getTime() != ts2.getTime()");
+ assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate getTime() returns the same value from 2 timeStamps when
+ * setTime() is used to specify the same value for both Timestamps
+ */
+ @Test
+ public void test36() {
+ Timestamp ts1 = Timestamp.valueOf("1966-08-30 08:08:08");
+ Timestamp ts2 = Timestamp.valueOf("1961-08-30 00:00:00");
+ ts2.setTime(ts1.getTime());
+ assertTrue(ts2.getTime() == ts1.getTime(),
+ "ts1.getTime() != ts2.getTime()");
+ assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid nanos value
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test38() throws Exception {
+ Timestamp ts1 = Timestamp.valueOf("1961-08-30 00:00:00");
+ ts1.setNanos(-1);
+
+ }
+
+ /**
+ * Validate an IllegalArgumentException is thrown for an invalid nanos value
+ */
+ @Test(expectedExceptions = IllegalArgumentException.class)
+ public void test39() throws Exception {
+ int nanos = 999999999;
+ Timestamp ts1 = Timestamp.valueOf("1961-08-30 00:00:00");
+ ts1.setNanos(nanos + 1);
+
+ }
+
+ /**
+ * Validate you can set nanos to 999999999
+ */
+ @Test
+ public void test40() throws Exception {
+ int nanos = 999999999;
+ Timestamp ts1 = Timestamp.valueOf("1961-08-30 00:00:00");
+ ts1.setNanos(nanos);
+ assertTrue(ts1.getNanos() == nanos, "Error Invalid Nanos value");
+
+ }
+
+ /**
+ * Validate you can set nanos to 0
+ */
+ @Test
+ public void test41() throws Exception {
+ int nanos = 0;
+ Timestamp ts1 = Timestamp.valueOf("1961-08-30 00:00:00");
+ ts1.setNanos(nanos);
+ assertTrue(ts1.getNanos() == nanos, "Error Invalid Nanos value");
+
+ }
+
+ /**
+ * Validate that a Timestamp made from a LocalDateTime are equal
+ */
+ @Test
+ public void test42() throws Exception {
+ Timestamp ts1 = Timestamp.valueOf("1961-08-30 00:00:00");
+ LocalDateTime ldt = ts1.toLocalDateTime();
+ Timestamp ts2 = Timestamp.valueOf(ldt);
+ assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that a Timestamp LocalDateTime value, made from a LocalDateTime
+ * are equal
+ */
+ @Test
+ public void test43() throws Exception {
+ LocalDateTime ldt = LocalDateTime.now();
+ Timestamp ts2 = Timestamp.valueOf(ldt);
+ assertTrue(ldt.equals(ts2.toLocalDateTime()),
+ "Error LocalDateTime values are not equal");
+ }
+
+ /**
+ * Validate an NPE occurs when a null LocalDateTime is passed to valueOF
+ */
+ @Test(expectedExceptions = NullPointerException.class)
+ public void test44() throws Exception {
+ LocalDateTime ldt = null;
+ Timestamp.valueOf(ldt);
+ }
+
+ /**
+ * Validate that a Timestamp made from a Instant are equal
+ */
+ @Test
+ public void test45() throws Exception {
+ Timestamp ts1 = Timestamp.valueOf("1961-08-30 00:00:00");
+ Instant instant = ts1.toInstant();
+ Timestamp ts2 = Timestamp.from(instant);
+ assertTrue(ts1.equals(ts2), "Error ts1 != ts2");
+ }
+
+ /**
+ * Validate that a Timestamp made from a Instant are equal
+ */
+ @Test
+ public void test46() throws Exception {
+ Instant instant = Instant.now();
+ Timestamp ts2 = Timestamp.from(instant);
+ assertTrue(instant.equals(ts2.toInstant()),
+ "Error Instant values do not match");
+ }
+
+ /**
+ * Validate an NPE occurs when a null instant is passed to from
+ */
+ @Test(expectedExceptions = NullPointerException.class)
+ public void test47() throws Exception {
+ Instant instant = null;
+ Timestamp.from(instant);
+ }
+
+ // Added SQE tests
+ /**
+ * Create a Timestamp and a 2nd Timestamp that is 1 month earlier and
+ * validate that it is not before or after the original Timestamp
+ */
+ @Test
+ public void test48() {
+ Calendar cal = Calendar.getInstance();
+ Timestamp ts1 = new Timestamp(System.currentTimeMillis());
+ cal.setTimeInMillis(ts1.getTime());
+ cal.add(Calendar.MONTH, -1);
+ cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
+ Timestamp ts2 = new Timestamp(cal.getTimeInMillis());
+ assertFalse(ts1.before(ts2) || ts2.after(ts1));
+ }
+
+ /**
+ * Create two Timestamps and validate that compareTo returns 1 to indicate
+ * the 1st Timestamp is greater than the 2nd Timestamp
+ */
+ @Test
+ public void test49() {
+ Calendar cal = Calendar.getInstance();
+ Timestamp ts1 = new Timestamp(System.currentTimeMillis());
+ cal.setTimeInMillis(ts1.getTime());
+ cal.add(Calendar.MONTH, -1);
+ cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
+ Timestamp ts2 = new Timestamp(cal.getTimeInMillis());
+ assertTrue(ts1.compareTo(ts2) == 1);
+ }
+
+ /**
+ * Create two Timestamps and validate that the 1st Timestamp is not equal to
+ * the 2nd Timestamp but equal to itself
+ */
+ @Test
+ public void test50() {
+ Calendar cal = Calendar.getInstance();
+ Timestamp ts1 = new Timestamp(System.currentTimeMillis());
+ cal.setTimeInMillis(ts1.getTime());
+ cal.add(Calendar.MONTH, -1);
+ cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
+ Timestamp ts2 = new Timestamp(cal.getTimeInMillis());
+ assertTrue(!ts1.equals(ts2) && ts1.equals(ts1));
+ }
+
+}
diff --git a/jdk/test/java/sql/util/BaseTest.java b/jdk/test/java/sql/util/BaseTest.java
new file mode 100644
index 00000000000..2668c4899c7
--- /dev/null
+++ b/jdk/test/java/sql/util/BaseTest.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package util;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.ObjectInputStream;
+import java.io.ObjectOutputStream;
+import java.sql.SQLException;
+import org.testng.annotations.AfterClass;
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeClass;
+import org.testng.annotations.BeforeMethod;
+
+public class BaseTest {
+
+ protected final String reason = "reason";
+ protected final String state = "SQLState";
+ protected final String cause = "java.lang.Throwable: cause";
+ protected final Throwable t = new Throwable("cause");
+ protected final Throwable t1 = new Throwable("cause 1");
+ protected final Throwable t2 = new Throwable("cause 2");
+ protected final int errorCode = 21;
+ protected final String[] msgs = {"Exception 1", "cause 1", "Exception 2",
+ "Exception 3", "cause 2"};
+
+ @BeforeClass
+ public static void setUpClass() throws Exception {
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws Exception {
+ }
+
+ @BeforeMethod
+ public void setUpMethod() throws Exception {
+ }
+
+ @AfterMethod
+ public void tearDownMethod() throws Exception {
+ }
+
+ /**
+ * Take some form of SQLException, serialize and deserialize it
+ *
+ * @param SQLException
+ * @param ex SQLException
+ * @return deserialized SQLException
+ * @throws IOException
+ * @throws ClassNotFoundException
+ */
+ @SuppressWarnings("unchecked")
+ protected T
+ createSerializedException(T ex)
+ throws IOException, ClassNotFoundException {
+ T ex1;
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ try (ObjectOutputStream oos = new ObjectOutputStream(baos) ) {
+ oos.writeObject(ex);
+ }
+ try (ObjectInputStream ois =
+ new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()))) {
+ ex1 = (T) ois.readObject();
+ }
+ return ex1;
+ }
+
+}
diff --git a/jdk/test/java/sql/util/DriverActionImpl.java b/jdk/test/java/sql/util/DriverActionImpl.java
new file mode 100644
index 00000000000..4a286ad8f3c
--- /dev/null
+++ b/jdk/test/java/sql/util/DriverActionImpl.java
@@ -0,0 +1,43 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package util;
+
+import java.sql.DriverAction;
+
+/**
+ * Simple implementation of DriverAction which calls back into the Driver when
+ * release is called.
+ */
+class DriverActionImpl implements DriverAction {
+
+ public DriverActionImpl(StubDriverDA d) {
+ driver = d;
+ }
+
+ private final StubDriverDA driver;
+
+ @Override
+ public void deregister() {
+ driver.release();
+ }
+}
diff --git a/jdk/test/java/sql/util/SerializedBatchUpdateException.java b/jdk/test/java/sql/util/SerializedBatchUpdateException.java
new file mode 100644
index 00000000000..00efc5275a7
--- /dev/null
+++ b/jdk/test/java/sql/util/SerializedBatchUpdateException.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package util;
+
+public class SerializedBatchUpdateException {
+ /**
+ * Serialized BatchUpdateException from JDBC 4.0 with the following values
+ * reason = "This was the error msg"
+ * SQLState = "user defined sqlState"
+ * vendor Code = 99999
+ * Update Counts = {1, 2, 21}
+ * cause = = "java.lang.Throwable: throw 1"
+ */
+ public static byte[] DATA = {
+ (byte) 0xac, (byte) 0xed, (byte) 0x0, (byte) 0x5, (byte) 0x73, (byte) 0x72, (byte) 0x0, (byte) 0x1d, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2e, (byte) 0x73, (byte) 0x71, (byte) 0x6c, (byte) 0x2e, (byte) 0x42, (byte) 0x61, (byte) 0x74, (byte) 0x63, (byte) 0x68, (byte) 0x55, (byte) 0x70, (byte) 0x64, (byte) 0x61, (byte) 0x74, (byte) 0x65, (byte) 0x45, (byte) 0x78, (byte) 0x63, (byte) 0x65,
+ (byte) 0x70, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0x52, (byte) 0xf4, (byte) 0x73, (byte) 0xc0, (byte) 0xc1, (byte) 0x8b, (byte) 0xe, (byte) 0x5d, (byte) 0x3, (byte) 0x0, (byte) 0x2, (byte) 0x5b, (byte) 0x0, (byte) 0x10, (byte) 0x6c, (byte) 0x6f, (byte) 0x6e, (byte) 0x67, (byte) 0x55, (byte) 0x70, (byte) 0x64, (byte) 0x61, (byte) 0x74, (byte) 0x65, (byte) 0x43, (byte) 0x6f, (byte) 0x75,
+ (byte) 0x6e, (byte) 0x74, (byte) 0x73, (byte) 0x74, (byte) 0x0, (byte) 0x2, (byte) 0x5b, (byte) 0x4a, (byte) 0x5b, (byte) 0x0, (byte) 0xc, (byte) 0x75, (byte) 0x70, (byte) 0x64, (byte) 0x61, (byte) 0x74, (byte) 0x65, (byte) 0x43, (byte) 0x6f, (byte) 0x75, (byte) 0x6e, (byte) 0x74, (byte) 0x73, (byte) 0x74, (byte) 0x0, (byte) 0x2, (byte) 0x5b, (byte) 0x49, (byte) 0x78, (byte) 0x72, (byte) 0x0, (byte) 0x15,
+ (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2e, (byte) 0x73, (byte) 0x71, (byte) 0x6c, (byte) 0x2e, (byte) 0x53, (byte) 0x51, (byte) 0x4c, (byte) 0x45, (byte) 0x78, (byte) 0x63, (byte) 0x65, (byte) 0x70, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0x1d, (byte) 0xa1, (byte) 0xe9, (byte) 0x30, (byte) 0xdb, (byte) 0x3e, (byte) 0x75, (byte) 0xdc, (byte) 0x2, (byte) 0x0, (byte) 0x3,
+ (byte) 0x49, (byte) 0x0, (byte) 0xa, (byte) 0x76, (byte) 0x65, (byte) 0x6e, (byte) 0x64, (byte) 0x6f, (byte) 0x72, (byte) 0x43, (byte) 0x6f, (byte) 0x64, (byte) 0x65, (byte) 0x4c, (byte) 0x0, (byte) 0x8, (byte) 0x53, (byte) 0x51, (byte) 0x4c, (byte) 0x53, (byte) 0x74, (byte) 0x61, (byte) 0x74, (byte) 0x65, (byte) 0x74, (byte) 0x0, (byte) 0x12, (byte) 0x4c, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61,
+ (byte) 0x2f, (byte) 0x6c, (byte) 0x61, (byte) 0x6e, (byte) 0x67, (byte) 0x2f, (byte) 0x53, (byte) 0x74, (byte) 0x72, (byte) 0x69, (byte) 0x6e, (byte) 0x67, (byte) 0x3b, (byte) 0x4c, (byte) 0x0, (byte) 0x4, (byte) 0x6e, (byte) 0x65, (byte) 0x78, (byte) 0x74, (byte) 0x74, (byte) 0x0, (byte) 0x17, (byte) 0x4c, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2f, (byte) 0x73, (byte) 0x71, (byte) 0x6c,
+ (byte) 0x2f, (byte) 0x53, (byte) 0x51, (byte) 0x4c, (byte) 0x45, (byte) 0x78, (byte) 0x63, (byte) 0x65, (byte) 0x70, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0x3b, (byte) 0x78, (byte) 0x72, (byte) 0x0, (byte) 0x13, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2e, (byte) 0x6c, (byte) 0x61, (byte) 0x6e, (byte) 0x67, (byte) 0x2e, (byte) 0x45, (byte) 0x78, (byte) 0x63, (byte) 0x65,
+ (byte) 0x70, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0xd0, (byte) 0xfd, (byte) 0x1f, (byte) 0x3e, (byte) 0x1a, (byte) 0x3b, (byte) 0x1c, (byte) 0xc4, (byte) 0x2, (byte) 0x0, (byte) 0x0, (byte) 0x78, (byte) 0x72, (byte) 0x0, (byte) 0x13, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2e, (byte) 0x6c, (byte) 0x61, (byte) 0x6e, (byte) 0x67, (byte) 0x2e, (byte) 0x54, (byte) 0x68,
+ (byte) 0x72, (byte) 0x6f, (byte) 0x77, (byte) 0x61, (byte) 0x62, (byte) 0x6c, (byte) 0x65, (byte) 0xd5, (byte) 0xc6, (byte) 0x35, (byte) 0x27, (byte) 0x39, (byte) 0x77, (byte) 0xb8, (byte) 0xcb, (byte) 0x3, (byte) 0x0, (byte) 0x4, (byte) 0x4c, (byte) 0x0, (byte) 0x5, (byte) 0x63, (byte) 0x61, (byte) 0x75, (byte) 0x73, (byte) 0x65, (byte) 0x74, (byte) 0x0, (byte) 0x15, (byte) 0x4c, (byte) 0x6a, (byte) 0x61,
+ (byte) 0x76, (byte) 0x61, (byte) 0x2f, (byte) 0x6c, (byte) 0x61, (byte) 0x6e, (byte) 0x67, (byte) 0x2f, (byte) 0x54, (byte) 0x68, (byte) 0x72, (byte) 0x6f, (byte) 0x77, (byte) 0x61, (byte) 0x62, (byte) 0x6c, (byte) 0x65, (byte) 0x3b, (byte) 0x4c, (byte) 0x0, (byte) 0xd, (byte) 0x64, (byte) 0x65, (byte) 0x74, (byte) 0x61, (byte) 0x69, (byte) 0x6c, (byte) 0x4d, (byte) 0x65, (byte) 0x73, (byte) 0x73, (byte) 0x61,
+ (byte) 0x67, (byte) 0x65, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x4, (byte) 0x5b, (byte) 0x0, (byte) 0xa, (byte) 0x73, (byte) 0x74, (byte) 0x61, (byte) 0x63, (byte) 0x6b, (byte) 0x54, (byte) 0x72, (byte) 0x61, (byte) 0x63, (byte) 0x65, (byte) 0x74, (byte) 0x0, (byte) 0x1e, (byte) 0x5b, (byte) 0x4c, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2f, (byte) 0x6c, (byte) 0x61,
+ (byte) 0x6e, (byte) 0x67, (byte) 0x2f, (byte) 0x53, (byte) 0x74, (byte) 0x61, (byte) 0x63, (byte) 0x6b, (byte) 0x54, (byte) 0x72, (byte) 0x61, (byte) 0x63, (byte) 0x65, (byte) 0x45, (byte) 0x6c, (byte) 0x65, (byte) 0x6d, (byte) 0x65, (byte) 0x6e, (byte) 0x74, (byte) 0x3b, (byte) 0x4c, (byte) 0x0, (byte) 0x14, (byte) 0x73, (byte) 0x75, (byte) 0x70, (byte) 0x70, (byte) 0x72, (byte) 0x65, (byte) 0x73, (byte) 0x73,
+ (byte) 0x65, (byte) 0x64, (byte) 0x45, (byte) 0x78, (byte) 0x63, (byte) 0x65, (byte) 0x70, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0x73, (byte) 0x74, (byte) 0x0, (byte) 0x10, (byte) 0x4c, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2f, (byte) 0x75, (byte) 0x74, (byte) 0x69, (byte) 0x6c, (byte) 0x2f, (byte) 0x4c, (byte) 0x69, (byte) 0x73, (byte) 0x74, (byte) 0x3b, (byte) 0x78,
+ (byte) 0x70, (byte) 0x73, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x7, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0xc, (byte) 0x74, (byte) 0x0, (byte) 0x7, (byte) 0x74, (byte) 0x68, (byte) 0x72, (byte) 0x6f, (byte) 0x77, (byte) 0x20, (byte) 0x31, (byte) 0x75, (byte) 0x72, (byte) 0x0, (byte) 0x1e, (byte) 0x5b, (byte) 0x4c, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61,
+ (byte) 0x2e, (byte) 0x6c, (byte) 0x61, (byte) 0x6e, (byte) 0x67, (byte) 0x2e, (byte) 0x53, (byte) 0x74, (byte) 0x61, (byte) 0x63, (byte) 0x6b, (byte) 0x54, (byte) 0x72, (byte) 0x61, (byte) 0x63, (byte) 0x65, (byte) 0x45, (byte) 0x6c, (byte) 0x65, (byte) 0x6d, (byte) 0x65, (byte) 0x6e, (byte) 0x74, (byte) 0x3b, (byte) 0x2, (byte) 0x46, (byte) 0x2a, (byte) 0x3c, (byte) 0x3c, (byte) 0xfd, (byte) 0x22, (byte) 0x39,
+ (byte) 0x2, (byte) 0x0, (byte) 0x0, (byte) 0x78, (byte) 0x70, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x2, (byte) 0x73, (byte) 0x72, (byte) 0x0, (byte) 0x1b, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x2e, (byte) 0x6c, (byte) 0x61, (byte) 0x6e, (byte) 0x67, (byte) 0x2e, (byte) 0x53, (byte) 0x74, (byte) 0x61, (byte) 0x63, (byte) 0x6b, (byte) 0x54, (byte) 0x72, (byte) 0x61, (byte) 0x63,
+ (byte) 0x65, (byte) 0x45, (byte) 0x6c, (byte) 0x65, (byte) 0x6d, (byte) 0x65, (byte) 0x6e, (byte) 0x74, (byte) 0x61, (byte) 0x9, (byte) 0xc5, (byte) 0x9a, (byte) 0x26, (byte) 0x36, (byte) 0xdd, (byte) 0x85, (byte) 0x2, (byte) 0x0, (byte) 0x4, (byte) 0x49, (byte) 0x0, (byte) 0xa, (byte) 0x6c, (byte) 0x69, (byte) 0x6e, (byte) 0x65, (byte) 0x4e, (byte) 0x75, (byte) 0x6d, (byte) 0x62, (byte) 0x65, (byte) 0x72,
+ (byte) 0x4c, (byte) 0x0, (byte) 0xe, (byte) 0x64, (byte) 0x65, (byte) 0x63, (byte) 0x6c, (byte) 0x61, (byte) 0x72, (byte) 0x69, (byte) 0x6e, (byte) 0x67, (byte) 0x43, (byte) 0x6c, (byte) 0x61, (byte) 0x73, (byte) 0x73, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x4, (byte) 0x4c, (byte) 0x0, (byte) 0x8, (byte) 0x66, (byte) 0x69, (byte) 0x6c, (byte) 0x65, (byte) 0x4e, (byte) 0x61, (byte) 0x6d,
+ (byte) 0x65, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x4, (byte) 0x4c, (byte) 0x0, (byte) 0xa, (byte) 0x6d, (byte) 0x65, (byte) 0x74, (byte) 0x68, (byte) 0x6f, (byte) 0x64, (byte) 0x4e, (byte) 0x61, (byte) 0x6d, (byte) 0x65, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x4, (byte) 0x78, (byte) 0x70, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x23, (byte) 0x74, (byte) 0x0,
+ (byte) 0x17, (byte) 0x43, (byte) 0x72, (byte) 0x65, (byte) 0x61, (byte) 0x74, (byte) 0x65, (byte) 0x42, (byte) 0x61, (byte) 0x74, (byte) 0x63, (byte) 0x68, (byte) 0x45, (byte) 0x78, (byte) 0x63, (byte) 0x65, (byte) 0x70, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0x53, (byte) 0x65, (byte) 0x72, (byte) 0x74, (byte) 0x0, (byte) 0x1c, (byte) 0x43, (byte) 0x72, (byte) 0x65, (byte) 0x61, (byte) 0x74,
+ (byte) 0x65, (byte) 0x42, (byte) 0x61, (byte) 0x74, (byte) 0x63, (byte) 0x68, (byte) 0x45, (byte) 0x78, (byte) 0x63, (byte) 0x65, (byte) 0x70, (byte) 0x74, (byte) 0x69, (byte) 0x6f, (byte) 0x6e, (byte) 0x53, (byte) 0x65, (byte) 0x72, (byte) 0x2e, (byte) 0x6a, (byte) 0x61, (byte) 0x76, (byte) 0x61, (byte) 0x74, (byte) 0x0, (byte) 0x9, (byte) 0x77, (byte) 0x72, (byte) 0x69, (byte) 0x74, (byte) 0x65, (byte) 0x54,
+ (byte) 0x65, (byte) 0x73, (byte) 0x74, (byte) 0x73, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x10, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x1a, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x12, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x13, (byte) 0x74, (byte) 0x0, (byte) 0x4, (byte) 0x6d, (byte) 0x61, (byte) 0x69, (byte) 0x6e, (byte) 0x70, (byte) 0x78,
+ (byte) 0x74, (byte) 0x0, (byte) 0x16, (byte) 0x54, (byte) 0x68, (byte) 0x69, (byte) 0x73, (byte) 0x20, (byte) 0x77, (byte) 0x61, (byte) 0x73, (byte) 0x20, (byte) 0x74, (byte) 0x68, (byte) 0x65, (byte) 0x20, (byte) 0x65, (byte) 0x72, (byte) 0x72, (byte) 0x6f, (byte) 0x72, (byte) 0x20, (byte) 0x6d, (byte) 0x73, (byte) 0x67, (byte) 0x75, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0xe, (byte) 0x0,
+ (byte) 0x0, (byte) 0x0, (byte) 0x2, (byte) 0x73, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x10, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x28, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x12, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x13, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x14, (byte) 0x73, (byte) 0x71, (byte) 0x0, (byte) 0x7e,
+ (byte) 0x0, (byte) 0x10, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x1a, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x12, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x13, (byte) 0x71, (byte) 0x0, (byte) 0x7e, (byte) 0x0, (byte) 0x16, (byte) 0x70, (byte) 0x78, (byte) 0x0, (byte) 0x1, (byte) 0x86, (byte) 0x9f, (byte) 0x74, (byte) 0x0, (byte) 0x15, (byte) 0x75, (byte) 0x73,
+ (byte) 0x65, (byte) 0x72, (byte) 0x20, (byte) 0x64, (byte) 0x65, (byte) 0x66, (byte) 0x69, (byte) 0x6e, (byte) 0x65, (byte) 0x64, (byte) 0x20, (byte) 0x73, (byte) 0x71, (byte) 0x6c, (byte) 0x53, (byte) 0x74, (byte) 0x61, (byte) 0x74, (byte) 0x65, (byte) 0x70, (byte) 0x75, (byte) 0x72, (byte) 0x0, (byte) 0x2, (byte) 0x5b, (byte) 0x4a, (byte) 0x78, (byte) 0x20, (byte) 0x4, (byte) 0xb5, (byte) 0x12, (byte) 0xb1,
+ (byte) 0x75, (byte) 0x93, (byte) 0x2, (byte) 0x0, (byte) 0x0, (byte) 0x78, (byte) 0x70, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x3, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x1, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x2, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x0,
+ (byte) 0x0, (byte) 0x0, (byte) 0x15, (byte) 0x75, (byte) 0x72, (byte) 0x0, (byte) 0x2, (byte) 0x5b, (byte) 0x49, (byte) 0x4d, (byte) 0xba, (byte) 0x60, (byte) 0x26, (byte) 0x76, (byte) 0xea, (byte) 0xb2, (byte) 0xa5, (byte) 0x2, (byte) 0x0, (byte) 0x0, (byte) 0x78, (byte) 0x70, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x3, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x1, (byte) 0x0, (byte) 0x0,
+ (byte) 0x0, (byte) 0x2, (byte) 0x0, (byte) 0x0, (byte) 0x0, (byte) 0x15, (byte) 0x78
+ };
+}
diff --git a/jdk/test/java/sql/util/StubBlob.java b/jdk/test/java/sql/util/StubBlob.java
new file mode 100644
index 00000000000..59917c7094f
--- /dev/null
+++ b/jdk/test/java/sql/util/StubBlob.java
@@ -0,0 +1,73 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package util;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.sql.Blob;
+import java.sql.SQLException;
+
+
+public class StubBlob implements Blob {
+ public long length() throws SQLException {
+ return 0;
+ }
+ public byte[] getBytes(long pos, int length)
+ throws SQLException {
+ return null;
+ }
+ public InputStream getBinaryStream()
+ throws SQLException {
+ return null;
+ }
+ public long position(byte[] pattern, long start)
+ throws SQLException {
+ return 0;
+ }
+ public long position(Blob pattern, long start)
+ throws SQLException {
+ return 0;
+ }
+ public int setBytes(long pos, byte[] bytes)
+ throws SQLException {
+ return 0;
+ }
+ public int setBytes(long pos, byte[] bytes, int offset, int len)
+ throws SQLException {
+ return 0;
+ }
+ public OutputStream setBinaryStream(long pos)
+ throws SQLException {
+ return null;
+ }
+ public void truncate(long len)
+ throws SQLException {
+ }
+ /* 6.0 implementation */
+
+ public void free() throws SQLException {}
+
+ public InputStream getBinaryStream(long pos, long length) throws SQLException {
+ return null;
+ }
+}
diff --git a/jdk/test/java/sql/util/StubConnection.java b/jdk/test/java/sql/util/StubConnection.java
new file mode 100644
index 00000000000..88c44262f61
--- /dev/null
+++ b/jdk/test/java/sql/util/StubConnection.java
@@ -0,0 +1,315 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package util;
+
+import java.sql.Array;
+import java.sql.Blob;
+import java.sql.CallableStatement;
+import java.sql.Clob;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.NClob;
+import java.sql.PreparedStatement;
+import java.sql.SQLClientInfoException;
+import java.sql.SQLException;
+import java.sql.SQLWarning;
+import java.sql.SQLXML;
+import java.sql.Savepoint;
+import java.sql.Statement;
+import java.sql.Struct;
+import java.util.Map;
+import java.util.Properties;
+import java.util.concurrent.Executor;
+
+public class StubConnection implements Connection {
+
+ @Override
+ public Statement createStatement() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(String sql) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public CallableStatement prepareCall(String sql) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public String nativeSQL(String sql) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setAutoCommit(boolean autoCommit) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public boolean getAutoCommit() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void commit() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void rollback() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void close() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public boolean isClosed() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public DatabaseMetaData getMetaData() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setReadOnly(boolean readOnly) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public boolean isReadOnly() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setCatalog(String catalog) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public String getCatalog() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setTransactionIsolation(int level) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public int getTransactionIsolation() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public SQLWarning getWarnings() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void clearWarnings() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Map> getTypeMap() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setTypeMap(Map> map) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setHoldability(int holdability) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public int getHoldability() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Savepoint setSavepoint() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Savepoint setSavepoint(String name) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void rollback(Savepoint savepoint) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void releaseSavepoint(Savepoint savepoint) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Clob createClob() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Blob createBlob() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public NClob createNClob() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public SQLXML createSQLXML() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public boolean isValid(int timeout) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setClientInfo(String name, String value) throws SQLClientInfoException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setClientInfo(Properties properties) throws SQLClientInfoException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public String getClientInfo(String name) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Properties getClientInfo() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setSchema(String schema) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public String getSchema() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void abort(Executor executor) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public int getNetworkTimeout() throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public T unwrap(Class iface) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public boolean isWrapperFor(Class> iface) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+}
diff --git a/jdk/test/java/sql/util/StubDriver.java b/jdk/test/java/sql/util/StubDriver.java
new file mode 100644
index 00000000000..12253080377
--- /dev/null
+++ b/jdk/test/java/sql/util/StubDriver.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package util;
+
+import java.sql.Connection;
+import java.sql.Driver;
+import java.sql.DriverPropertyInfo;
+import java.sql.SQLException;
+import java.sql.SQLFeatureNotSupportedException;
+import java.util.Properties;
+import java.util.logging.Logger;
+
+public class StubDriver implements Driver {
+
+ public StubDriver() {
+ }
+
+ @Override
+ public Connection connect(String url, Properties info) throws SQLException {
+ if (acceptsURL(url)) {
+ return new StubConnection();
+ }
+ return null;
+ }
+
+ @Override
+ public boolean acceptsURL(String url) throws SQLException {
+ return url.matches("^jdbc:tennis:.*");
+ }
+
+ @Override
+ public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+
+ @Override
+ public int getMajorVersion() {
+ return 1;
+ }
+
+ @Override
+ public int getMinorVersion() {
+ return 0;
+ }
+
+ @Override
+ public boolean jdbcCompliant() {
+ return true;
+ }
+
+ @Override
+ public Logger getParentLogger() throws SQLFeatureNotSupportedException {
+ throw new UnsupportedOperationException("Not supported yet.");
+ }
+}
diff --git a/jdk/test/java/sql/util/StubDriverDA.java b/jdk/test/java/sql/util/StubDriverDA.java
new file mode 100644
index 00000000000..5b23f0846d8
--- /dev/null
+++ b/jdk/test/java/sql/util/StubDriverDA.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package util;
+
+import java.io.File;
+import java.io.IOException;
+import java.sql.DriverAction;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Simple java.sql.Driver stub class that registers the driver via a static
+ * block with a DriverAction Implementation
+ * @author ljanders
+ */
+public class StubDriverDA extends StubDriver {
+
+ public static final String DriverActionCalled = "DriverActionCalled.txt";
+
+ static DriverAction da;
+
+ static {
+ try {
+ DriverManager.registerDriver(new StubDriverDA(), da);
+ } catch (SQLException ex) {
+ Logger.getLogger(StubDriverDA.class.getName()).log(Level.SEVERE, null, ex);
+ }
+ }
+
+ public StubDriverDA() {
+ da = new DriverActionImpl(this);
+ }
+
+ @Override
+ public boolean acceptsURL(String url) throws SQLException {
+ return url.matches("^jdbc:luckydog:.*");
+ }
+
+ /**
+ * This method will write out a text file when called by the
+ * DriverActionImpl.release method when DriverManager.deregisterDriver
+ * is called. This is used by DriverManagerTests to validate that
+ * DriverAction.release was called
+ */
+ protected void release() {
+ File file = new File(DriverActionCalled);
+ try {
+ file.createNewFile();
+ } catch (IOException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+}
diff --git a/jdk/test/java/time/tck/java/time/chrono/CopticChronology.java b/jdk/test/java/time/tck/java/time/chrono/CopticChronology.java
index c72b7370de8..626b2863dd6 100644
--- a/jdk/test/java/time/tck/java/time/chrono/CopticChronology.java
+++ b/jdk/test/java/time/tck/java/time/chrono/CopticChronology.java
@@ -1,4 +1,5 @@
/*
+ * 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/jdk/test/java/time/tck/java/time/chrono/CopticDate.java b/jdk/test/java/time/tck/java/time/chrono/CopticDate.java
index a296c5940ec..09e2e47d815 100644
--- a/jdk/test/java/time/tck/java/time/chrono/CopticDate.java
+++ b/jdk/test/java/time/tck/java/time/chrono/CopticDate.java
@@ -1,4 +1,5 @@
/*
+ * 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/jdk/test/java/time/tck/java/time/chrono/CopticEra.java b/jdk/test/java/time/tck/java/time/chrono/CopticEra.java
index c1d7f56071a..be78ff5b09c 100644
--- a/jdk/test/java/time/tck/java/time/chrono/CopticEra.java
+++ b/jdk/test/java/time/tck/java/time/chrono/CopticEra.java
@@ -1,4 +1,5 @@
/*
+ * 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/jdk/test/java/time/tck/java/time/chrono/TCKChronoPeriod.java b/jdk/test/java/time/tck/java/time/chrono/TCKChronoPeriod.java
index 58a1c35eddb..b8b1bd2d5cb 100644
--- a/jdk/test/java/time/tck/java/time/chrono/TCKChronoPeriod.java
+++ b/jdk/test/java/time/tck/java/time/chrono/TCKChronoPeriod.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,7 @@ import java.time.temporal.UnsupportedTemporalTypeException;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
+@Test
public class TCKChronoPeriod {
//-----------------------------------------------------------------------
diff --git a/jdk/test/java/time/test/java/time/temporal/TestIsoWeekFields.java b/jdk/test/java/time/test/java/time/temporal/TestIsoWeekFields.java
new file mode 100644
index 00000000000..d79d13f89a3
--- /dev/null
+++ b/jdk/test/java/time/test/java/time/temporal/TestIsoWeekFields.java
@@ -0,0 +1,280 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package test.java.time.temporal;
+
+import static java.time.temporal.ChronoField.DAY_OF_WEEK;
+import static org.testng.Assert.assertEquals;
+
+import java.time.LocalDate;
+import java.time.LocalTime;
+import java.time.MonthDay;
+import java.time.OffsetDateTime;
+import java.time.Year;
+import java.time.chrono.ThaiBuddhistDate;
+import java.time.temporal.ChronoUnit;
+import java.time.temporal.IsoFields;
+import java.time.temporal.TemporalField;
+import java.time.temporal.ValueRange;
+import java.time.temporal.WeekFields;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+/**
+ * Test.
+ */
+@Test
+public class TestIsoWeekFields {
+
+ @DataProvider(name = "fields")
+ Object[][] data_Fields() {
+ return new Object[][] {
+ {IsoFields.WEEK_OF_WEEK_BASED_YEAR, IsoFields.WEEK_BASED_YEAR},
+ {WeekFields.ISO.weekOfWeekBasedYear(), WeekFields.ISO.weekBasedYear()},
+ };
+ }
+
+ //-----------------------------------------------------------------------
+ // WEEK_OF_WEEK_BASED_YEAR
+ //-----------------------------------------------------------------------
+ @Test(dataProvider = "fields")
+ public void test_WOWBY_basics(TemporalField weekField, TemporalField yearField) {
+ assertEquals(weekField.isDateBased(), true);
+ assertEquals(weekField.isTimeBased(), false);
+ assertEquals(weekField.getBaseUnit(), ChronoUnit.WEEKS);
+ assertEquals(weekField.getRangeUnit(), IsoFields.WEEK_BASED_YEARS);
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_WOWBY_isSupportedBy(TemporalField weekField, TemporalField yearField) {
+ assertEquals(weekField.isSupportedBy(LocalTime.NOON), false);
+ assertEquals(weekField.isSupportedBy(MonthDay.of(2, 1)), false);
+ assertEquals(weekField.isSupportedBy(LocalDate.MIN), true);
+ assertEquals(weekField.isSupportedBy(OffsetDateTime.MAX), true);
+ }
+
+ @Test
+ public void test_WOWBY_isSupportedBy_fieldsDiffer() {
+ assertEquals(IsoFields.WEEK_OF_WEEK_BASED_YEAR.isSupportedBy(ThaiBuddhistDate.now()), false);
+ assertEquals(WeekFields.ISO.weekOfWeekBasedYear().isSupportedBy(ThaiBuddhistDate.now()), true);
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_WOWBY_range(TemporalField weekField, TemporalField yearField) {
+ assertEquals(weekField.range(), ValueRange.of(1, 52, 53));
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_WOWBY_rangeRefinedBy(TemporalField weekField, TemporalField yearField) {
+ assertEquals(weekField.rangeRefinedBy(LocalDate.of(2012, 12, 31)), ValueRange.of(1, 52));
+ assertEquals(weekField.rangeRefinedBy(LocalDate.of(2013, 12, 29)), ValueRange.of(1, 52));
+ assertEquals(weekField.rangeRefinedBy(LocalDate.of(2013, 12, 30)), ValueRange.of(1, 52));
+ assertEquals(weekField.rangeRefinedBy(LocalDate.of(2014, 12, 28)), ValueRange.of(1, 52));
+ assertEquals(weekField.rangeRefinedBy(LocalDate.of(2014, 12, 29)), ValueRange.of(1, 53));
+ assertEquals(weekField.rangeRefinedBy(LocalDate.of(2016, 1, 3)), ValueRange.of(1, 53));
+ assertEquals(weekField.rangeRefinedBy(LocalDate.of(2016, 1, 4)), ValueRange.of(1, 52));
+ }
+
+ //-----------------------------------------------------------------------
+ // WEEK_BASED_YEAR
+ //-----------------------------------------------------------------------
+ @Test(dataProvider = "fields")
+ public void test_WBY_basics(TemporalField weekField, TemporalField yearField) {
+ assertEquals(yearField.isDateBased(), true);
+ assertEquals(yearField.isTimeBased(), false);
+ assertEquals(yearField.getBaseUnit(), IsoFields.WEEK_BASED_YEARS);
+ assertEquals(yearField.getRangeUnit(), ChronoUnit.FOREVER);
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_WBY_isSupportedBy(TemporalField weekField, TemporalField yearField) {
+ assertEquals(yearField.isSupportedBy(LocalTime.NOON), false);
+ assertEquals(yearField.isSupportedBy(MonthDay.of(2, 1)), false);
+ assertEquals(yearField.isSupportedBy(LocalDate.MIN), true);
+ assertEquals(yearField.isSupportedBy(OffsetDateTime.MAX), true);
+ }
+
+ @Test
+ public void test_WBY_isSupportedBy_ISO() {
+ assertEquals(IsoFields.WEEK_BASED_YEAR.isSupportedBy(ThaiBuddhistDate.now()), false);
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_WBY_range(TemporalField weekField, TemporalField yearField) {
+ assertEquals(yearField.range(), ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE));
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_WBY_rangeRefinedBy(TemporalField weekField, TemporalField yearField) {
+ assertEquals(yearField.rangeRefinedBy(LocalDate.of(2012, 12, 31)), ValueRange.of(Year.MIN_VALUE, Year.MAX_VALUE));
+ }
+
+ //-----------------------------------------------------------------------
+ @Test(dataProvider = "fields")
+ public void test_getFrom(TemporalField weekField, TemporalField yearField) {
+ // tests every day from 2011 to 2016 inclusive
+ LocalDate date = LocalDate.of(2011, 1, 3);
+ int wby = 2011;
+ int week = 1;
+ int dow = 1;
+ for (int i = 1; i <= ((52 + 52 + 52 + 52 + 53 + 52) * 7); i++) {
+ assertEquals(yearField.getFrom(date), wby);
+ assertEquals(weekField.getFrom(date), week);
+ assertEquals(DAY_OF_WEEK.getFrom(date), dow);
+ if (dow == 7) {
+ dow = 1;
+ week++;
+ } else {
+ dow++;
+ }
+ if (week > wbyLen(wby)) {
+ week = 1;
+ wby++;
+ }
+ date = date.plusDays(1);
+ }
+ assertEquals(yearField.getFrom(date), 2017);
+ assertEquals(weekField.getFrom(date), 1);
+ assertEquals(DAY_OF_WEEK.getFrom(date), 1);
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_adjustInto_dow(TemporalField weekField, TemporalField yearField) {
+ // tests every day from 2012 to 2016 inclusive
+ LocalDate date = LocalDate.of(2012, 1, 2);
+ int wby = 2012;
+ int week = 1;
+ int dow = 1;
+ for (int i = 1; i <= ((52 + 52 + 52 + 53 + 52) * 7); i++) {
+ for (int j = 1; j <= 7; j++) {
+ LocalDate adjusted = DAY_OF_WEEK.adjustInto(date, j);
+ assertEquals(adjusted.get(DAY_OF_WEEK), j);
+ assertEquals(adjusted.get(weekField), week);
+ assertEquals(adjusted.get(yearField), wby);
+ }
+ if (dow == 7) {
+ dow = 1;
+ week++;
+ } else {
+ dow++;
+ }
+ if (week > wbyLen(wby)) {
+ week = 1;
+ wby++;
+ }
+ date = date.plusDays(1);
+ }
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_adjustInto_week(TemporalField weekField, TemporalField yearField) {
+ // tests every day from 2012 to 2016 inclusive
+ LocalDate date = LocalDate.of(2012, 1, 2);
+ int wby = 2012;
+ int week = 1;
+ int dow = 1;
+ for (int i = 1; i <= ((52 + 52 + 52 + 53 + 52) * 7); i++) {
+ int weeksInYear = (wby == 2015 ? 53 : 52);
+ for (int j = 1; j <= weeksInYear; j++) {
+ LocalDate adjusted = weekField.adjustInto(date, j);
+ assertEquals(adjusted.get(weekField), j);
+ assertEquals(adjusted.get(DAY_OF_WEEK), dow);
+ assertEquals(adjusted.get(yearField), wby);
+ }
+ if (dow == 7) {
+ dow = 1;
+ week++;
+ } else {
+ dow++;
+ }
+ if (week > wbyLen(wby)) {
+ week = 1;
+ wby++;
+ }
+ date = date.plusDays(1);
+ }
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_adjustInto_wby(TemporalField weekField, TemporalField yearField) {
+ // tests every day from 2012 to 2016 inclusive
+ LocalDate date = LocalDate.of(2012, 1, 2);
+ int wby = 2012;
+ int week = 1;
+ int dow = 1;
+ for (int i = 1; i <= ((52 + 52 + 52 + 53 + 52) * 7); i++) {
+ for (int j = 2004; j <= 2015; j++) {
+ LocalDate adjusted = yearField.adjustInto(date, j);
+ assertEquals(adjusted.get(yearField), j);
+ assertEquals(adjusted.get(DAY_OF_WEEK), dow);
+ assertEquals(adjusted.get(weekField), (week == 53 && wbyLen(j) == 52 ? 52 : week), "" + date + " " + adjusted);
+ }
+ if (dow == 7) {
+ dow = 1;
+ week++;
+ } else {
+ dow++;
+ }
+ if (week > wbyLen(wby)) {
+ week = 1;
+ wby++;
+ }
+ date = date.plusDays(1);
+ }
+ }
+
+ @Test(dataProvider = "fields")
+ public void test_addTo_weekBasedYears(TemporalField weekField, TemporalField yearField) {
+ // tests every day from 2012 to 2016 inclusive
+ LocalDate date = LocalDate.of(2012, 1, 2);
+ int wby = 2012;
+ int week = 1;
+ int dow = 1;
+ for (int i = 1; i <= ((52 + 52 + 52 + 53 + 52) * 7); i++) {
+ for (int j = -5; j <= 5; j++) {
+ LocalDate adjusted = IsoFields.WEEK_BASED_YEARS.addTo(date, j);
+ assertEquals(adjusted.get(yearField), wby + j);
+ assertEquals(adjusted.get(DAY_OF_WEEK), dow);
+ assertEquals(adjusted.get(weekField), (week == 53 && wbyLen(wby + j) == 52 ? 52 : week), "" + date + " " + adjusted);
+ }
+ if (dow == 7) {
+ dow = 1;
+ week++;
+ } else {
+ dow++;
+ }
+ if (week > wbyLen(wby)) {
+ week = 1;
+ wby++;
+ }
+ date = date.plusDays(1);
+ }
+ }
+
+ private int wbyLen(int wby) {
+ return (wby == 2004 || wby == 2009 || wby == 2015 || wby == 2020 ? 53 : 52);
+ }
+
+}
diff --git a/jdk/test/javax/imageio/plugins/jpeg/TruncatedImageWarningTest.java b/jdk/test/javax/imageio/plugins/jpeg/TruncatedImageWarningTest.java
new file mode 100644
index 00000000000..6ca40d1c58b
--- /dev/null
+++ b/jdk/test/javax/imageio/plugins/jpeg/TruncatedImageWarningTest.java
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test
+ * @bug 8032370
+ *
+ * @summary Test verifies that Image I/O jpeg reader correctly handles
+ * and warns of a truncated image stream.
+ *
+ * @run main TruncatedImageWarningTest
+ */
+
+import java.io.File;
+import java.io.IOException;
+import javax.imageio.ImageIO;
+import javax.imageio.ImageReader;
+import javax.imageio.event.IIOReadWarningListener;
+import javax.imageio.stream.ImageInputStream;
+
+public class TruncatedImageWarningTest implements IIOReadWarningListener {
+
+ private static String fileName = "truncated.jpg";
+ boolean receivedWarning = false;
+
+ public static void main(String[] args) throws IOException {
+
+ String sep = System.getProperty("file.separator");
+ String dir = System.getProperty("test.src", ".");
+ String filePath = dir+sep+fileName;
+ System.out.println("Test file: " + filePath);
+ File f = new File(filePath);
+ ImageInputStream in = ImageIO.createImageInputStream(f);
+ ImageReader reader = ImageIO.getImageReaders(in).next();
+ TruncatedImageWarningTest twt = new TruncatedImageWarningTest();
+ reader.addIIOReadWarningListener(twt);
+ reader.setInput(in);
+ reader.read(0);
+ if (!twt.receivedWarning) {
+ throw new RuntimeException("No expected warning");
+ }
+ }
+
+ public void warningOccurred(ImageReader source, String warning) {
+ System.out.println("Expected warning: " + warning);
+ receivedWarning = true;
+ }
+}
diff --git a/jdk/test/javax/imageio/plugins/jpeg/truncated.jpg b/jdk/test/javax/imageio/plugins/jpeg/truncated.jpg
new file mode 100644
index 00000000000..db3fca890c8
Binary files /dev/null and b/jdk/test/javax/imageio/plugins/jpeg/truncated.jpg differ
diff --git a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java
index 62fd8e2536c..833dc77807d 100644
--- a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java
+++ b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
/**
* @test
- * @bug 4635230 6283345 6303830 6824440 6867348 7094155
+ * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184
* @summary Basic unit tests for generating XML Signatures with JSR 105
* @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
* X509KeySelector.java GenerationTests.java
@@ -135,6 +135,7 @@ public class GenerationTests {
test_create_signature_enveloping_sha512_rsa_sha512();
test_create_signature_reference_dependency();
test_create_signature_with_attr_in_no_namespace();
+ test_create_signature_with_empty_id();
}
private static void setup() throws Exception {
@@ -509,6 +510,30 @@ public class GenerationTests {
System.out.println();
}
+ static void test_create_signature_with_empty_id() throws Exception {
+ System.out.println("* Generating signature-with-empty-id.xml");
+
+ // create references
+ List refs = Collections.singletonList
+ (fac.newReference("#", sha1));
+
+ // create SignedInfo
+ SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
+
+ // create object with empty id
+ Document doc = db.newDocument();
+ XMLObject obj = fac.newXMLObject(Collections.singletonList
+ (new DOMStructure(doc.createTextNode("I am the text."))),
+ "", "text/plain", null);
+
+ // create XMLSignature
+ XMLSignature sig = fac.newXMLSignature(si, rsa,
+ Collections.singletonList(obj),
+ "signature", null);
+ DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA"), doc);
+ sig.sign(dsc);
+ }
+
static void test_create_signature() throws Exception {
System.out.println("* Generating signature.xml");
diff --git a/jdk/test/jdk/net/Sockets/Test.java b/jdk/test/jdk/net/Sockets/Test.java
new file mode 100644
index 00000000000..da609bf7501
--- /dev/null
+++ b/jdk/test/jdk/net/Sockets/Test.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8032808
+ * @run main/othervm -Xcheck:jni Test
+ * @run main/othervm/policy=policy.fail -Xcheck:jni Test fail
+ * @run main/othervm/policy=policy.success -Xcheck:jni Test success
+ */
+
+import java.net.*;
+import java.nio.channels.*;
+import java.util.concurrent.*;
+import jdk.net.*;
+
+public class Test {
+
+ static boolean security;
+ static boolean success;
+
+ interface Runner {
+ public void run() throws Exception;
+ }
+
+ public static void main(String[] args) throws Exception {
+
+ // quick check to see if supportedOptions() working before
+ // creating any sockets and libnet loaded
+
+ Sockets.supportedOptions(Socket.class);
+
+ security = System.getSecurityManager() != null;
+ success = security && args[0].equals("success");
+
+ // Main thing is to check for JNI problems
+ // Doesn't matter if current system does not support the option
+ // and currently setting the option with the loopback interface
+ // doesn't work either
+
+ System.out.println ("Security Manager enabled: " + security);
+ if (security) {
+ System.out.println ("Success expected: " + success);
+ }
+
+ final SocketFlow flowIn = SocketFlow.create()
+ .bandwidth(1000)
+ .priority(SocketFlow.HIGH_PRIORITY);
+
+ ServerSocket ss = new ServerSocket(0);
+ int tcp_port = ss.getLocalPort();
+ final InetAddress loop = InetAddress.getByName("127.0.0.1");
+ final InetSocketAddress loopad = new InetSocketAddress(loop, tcp_port);
+
+ DatagramSocket dg = new DatagramSocket(0);
+ final int udp_port = dg.getLocalPort();
+
+ final Socket s = new Socket("127.0.0.1", tcp_port);
+ final SocketChannel sc = SocketChannel.open();
+ sc.connect (new InetSocketAddress("127.0.0.1", tcp_port));
+
+ doTest(()->{
+ Sockets.setOption(s, ExtendedSocketOptions.SO_FLOW_SLA, flowIn);
+ });
+ doTest(()->{
+ Sockets.getOption(s, ExtendedSocketOptions.SO_FLOW_SLA);
+ });
+ doTest(()->{
+ sc.setOption(ExtendedSocketOptions.SO_FLOW_SLA, flowIn);
+ });
+ doTest(()->{
+ sc.getOption(ExtendedSocketOptions.SO_FLOW_SLA);
+ });
+ doTest(()->{
+ DatagramSocket dg1 = new DatagramSocket(0);
+ dg1.connect(loop, udp_port);
+ Sockets.setOption(dg1, ExtendedSocketOptions.SO_FLOW_SLA, flowIn);
+ });
+ doTest(()->{
+ DatagramChannel dg2 = DatagramChannel.open();
+ dg2.bind(new InetSocketAddress(loop, 0));
+ dg2.connect(new InetSocketAddress(loop, udp_port));
+ dg2.setOption(ExtendedSocketOptions.SO_FLOW_SLA, flowIn);
+ });
+ doTest(()->{
+ MulticastSocket mc1 = new MulticastSocket(0);
+ mc1.connect(loop, udp_port);
+ Sockets.setOption(mc1, ExtendedSocketOptions.SO_FLOW_SLA, flowIn);
+ });
+ doTest(()->{
+ AsynchronousSocketChannel asc = AsynchronousSocketChannel.open();
+ Future f = asc.connect(loopad);
+ f.get();
+ asc.setOption(ExtendedSocketOptions.SO_FLOW_SLA, flowIn);
+ });
+ }
+
+ static void doTest(Runner func) throws Exception {
+ try {
+ func.run();
+ if (security && !success) {
+ throw new RuntimeException("Test failed");
+ }
+ } catch (SecurityException e) {
+ if (success) {
+ throw new RuntimeException("Test failed");
+ }
+ } catch (UnsupportedOperationException e) {}
+ }
+}
diff --git a/jdk/test/jdk/net/Sockets/policy.fail b/jdk/test/jdk/net/Sockets/policy.fail
new file mode 100644
index 00000000000..29d1215e708
--- /dev/null
+++ b/jdk/test/jdk/net/Sockets/policy.fail
@@ -0,0 +1,4 @@
+grant {
+ permission java.net.SocketPermission "127.0.0.1", "connect,accept" ;
+ permission java.net.SocketPermission "localhost", "listen" ;
+};
diff --git a/jdk/test/jdk/net/Sockets/policy.success b/jdk/test/jdk/net/Sockets/policy.success
new file mode 100644
index 00000000000..6f99151a38f
--- /dev/null
+++ b/jdk/test/jdk/net/Sockets/policy.success
@@ -0,0 +1,6 @@
+grant {
+ permission java.net.SocketPermission "127.0.0.1", "connect,accept" ;
+ permission java.net.SocketPermission "localhost", "listen" ;
+ permission jdk.net.NetworkPermission "setOption.SO_FLOW_SLA";
+ permission jdk.net.NetworkPermission "getOption.SO_FLOW_SLA";
+};
diff --git a/jdk/test/demo/zipfs/Basic.java b/jdk/test/jdk/nio/zipfs/Basic.java
similarity index 96%
rename from jdk/test/demo/zipfs/Basic.java
rename to jdk/test/jdk/nio/zipfs/Basic.java
index ae2ad15b52d..b4b526ad489 100644
--- a/jdk/test/demo/zipfs/Basic.java
+++ b/jdk/test/jdk/nio/zipfs/Basic.java
@@ -29,13 +29,16 @@ import java.net.URI;
import java.io.IOException;
/**
- * Basic test for zip provider
+ *
+ * @test
+ * @bug 8038500
+ * @summary Basic test for zip provider
*/
public class Basic {
public static void main(String[] args) throws Exception {
- Path zipfile = Paths.get(args[0]);
-
+ Path zipfile = Paths.get(System.getProperty("test.jdk"),
+ "jre/lib/ext/zipfs.jar");
// Test: zip should should be returned in provider list
boolean found = false;
diff --git a/jdk/src/share/demo/nio/zipfs/Demo.java b/jdk/test/jdk/nio/zipfs/Demo.java
similarity index 92%
rename from jdk/src/share/demo/nio/zipfs/Demo.java
rename to jdk/test/jdk/nio/zipfs/Demo.java
index 17927b1b15c..c68c5ee9f35 100644
--- a/jdk/src/share/demo/nio/zipfs/Demo.java
+++ b/jdk/test/jdk/nio/zipfs/Demo.java
@@ -1,43 +1,26 @@
/*
- * Copyright (c) 2010 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
+ * 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.
*
- * - Redistributions of source code must retain the above copyright
- * notice, this list of conditions and the following disclaimer.
+ * 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).
*
- * - Redistributions in binary form must reproduce the above copyright
- * notice, this list of conditions and the following disclaimer in the
- * documentation and/or other materials provided with the distribution.
+ * 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.
*
- * - Neither the name of Oracle nor the names of its
- * contributors may be used to endorse or promote products derived
- * from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
- * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
- * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
- * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
- * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
- * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
- * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
- * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
- * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
- * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
*/
-/*
- * This source code is provided to illustrate the usage of a given feature
- * or technique and has been deliberately simplified. Additional steps
- * required for a production-quality application, such as security checks,
- * input validation and proper error handling, might not be present in
- * this sample code.
- */
-
-
import java.io.*;
import java.nio.*;
import java.nio.channels.*;
@@ -51,6 +34,7 @@ import java.util.*;
import static java.nio.file.StandardOpenOption.*;
import static java.nio.file.StandardCopyOption.*;
+
/*
* ZipFileSystem usage demo
*
diff --git a/jdk/test/demo/zipfs/PathOps.java b/jdk/test/jdk/nio/zipfs/PathOps.java
similarity index 98%
rename from jdk/test/demo/zipfs/PathOps.java
rename to jdk/test/jdk/nio/zipfs/PathOps.java
index ec1af09c9c5..321de439c58 100644
--- a/jdk/test/demo/zipfs/PathOps.java
+++ b/jdk/test/jdk/nio/zipfs/PathOps.java
@@ -27,7 +27,10 @@ import java.util.*;
import java.io.IOException;
/**
- * Tests path operations for zip provider.
+ *
+ * @test
+ * @bug 8038500
+ * @summary Tests path operations for zip provider.
*/
public class PathOps {
@@ -447,8 +450,8 @@ public class PathOps {
}
public static void main(String[] args) throws Throwable {
-
- Path zipfile = Paths.get(args[0]);
+ Path zipfile = Paths.get(System.getProperty("test.jdk"),
+ "jre/lib/ext/zipfs.jar");
fs = FileSystems.newFileSystem(zipfile, null);
npes();
doPathOpTests();
diff --git a/jdk/test/demo/zipfs/ZFSTests.java b/jdk/test/jdk/nio/zipfs/ZFSTests.java
similarity index 100%
rename from jdk/test/demo/zipfs/ZFSTests.java
rename to jdk/test/jdk/nio/zipfs/ZFSTests.java
diff --git a/jdk/test/demo/zipfs/ZipFSTester.java b/jdk/test/jdk/nio/zipfs/ZipFSTester.java
similarity index 98%
rename from jdk/test/demo/zipfs/ZipFSTester.java
rename to jdk/test/jdk/nio/zipfs/ZipFSTester.java
index e1afd0e2a19..47e75e11ec6 100644
--- a/jdk/test/demo/zipfs/ZipFSTester.java
+++ b/jdk/test/jdk/nio/zipfs/ZipFSTester.java
@@ -37,20 +37,25 @@ import static java.nio.file.StandardCopyOption.*;
/*
* Tests various zipfs operations.
+ *
+ * @test
+ * @bug 6990846 7009092 7009085 7015391 7014948 7005986 7017840 7007596
+ * 7157656 8002390 7012868 7012856 8015728 8038500
+ * @summary Test Zip filesystem provider
*/
public class ZipFSTester {
public static void main(String[] args) throws Throwable {
-
- try (FileSystem fs = newZipFileSystem(Paths.get(args[0]),
- new HashMap()))
+ try (FileSystem fs = newZipFileSystem(
+ Paths.get(System.getProperty("test.jdk"), "jre/lib/ext/zipfs.jar"),
+ new HashMap()))
{
test0(fs);
test1(fs);
test2(fs); // more tests
- testTime(Paths.get(args[0]));
}
+ testTime(Paths.get(System.getProperty("test.jdk"), "jre/lib/ext/zipfs.jar"));
}
static void test0(FileSystem fs)
diff --git a/jdk/test/lib/testlibrary/jdk/testlibrary/FileUtils.java b/jdk/test/lib/testlibrary/jdk/testlibrary/FileUtils.java
index 7882262274f..3c85782b85f 100644
--- a/jdk/test/lib/testlibrary/jdk/testlibrary/FileUtils.java
+++ b/jdk/test/lib/testlibrary/jdk/testlibrary/FileUtils.java
@@ -191,4 +191,3 @@ public final class FileUtils {
return excs;
}
}
-
diff --git a/jdk/test/lib/testlibrary/jdk/testlibrary/IOUtils.java b/jdk/test/lib/testlibrary/jdk/testlibrary/IOUtils.java
new file mode 100644
index 00000000000..4bfddd0485c
--- /dev/null
+++ b/jdk/test/lib/testlibrary/jdk/testlibrary/IOUtils.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package jdk.testlibrary;
+
+/**
+ * Defines useful I/O methods.
+ */
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Arrays;
+
+public final class IOUtils {
+
+ /*
+ * Prevent instantiation.
+ */
+ private IOUtils() {}
+
+ /**
+ * Read all bytes from in
+ * until EOF is detected.
+ * @param in input stream, must not be null
+ * @return bytes read
+ * @throws IOException Any IO error.
+ */
+ public static byte[] readFully(InputStream is) throws IOException {
+ byte[] output = {};
+ int pos = 0;
+ while (true) {
+ int bytesToRead;
+ if (pos >= output.length) { // Only expand when there's no room
+ bytesToRead = output.length + 1024;
+ if (output.length < pos + bytesToRead) {
+ output = Arrays.copyOf(output, pos + bytesToRead);
+ }
+ } else {
+ bytesToRead = output.length - pos;
+ }
+ int cc = is.read(output, pos, bytesToRead);
+ if (cc < 0) {
+ if (output.length != pos) {
+ output = Arrays.copyOf(output, pos);
+ }
+ break;
+ }
+ pos += cc;
+ }
+ return output;
+ }
+}
diff --git a/jdk/test/lib/testlibrary/jdk/testlibrary/Utils.java b/jdk/test/lib/testlibrary/jdk/testlibrary/Utils.java
index 7d4687ee88f..90c473e6231 100644
--- a/jdk/test/lib/testlibrary/jdk/testlibrary/Utils.java
+++ b/jdk/test/lib/testlibrary/jdk/testlibrary/Utils.java
@@ -119,6 +119,26 @@ public final class Utils {
return opts.toArray(new String[0]);
}
+ /**
+ * Removes any options specifying which GC to use, for example "-XX:+UseG1GC".
+ * Removes any options matching: -XX:(+/-)Use*GC
+ * Used when a test need to set its own GC version. Then any
+ * GC specified by the framework must first be removed.
+ * @return A copy of given opts with all GC options removed.
+ */
+ private static final Pattern useGcPattern = Pattern.compile("\\-XX\\:[\\+\\-]Use.+GC");
+ public static List removeGcOpts(List opts) {
+ List optsWithoutGC = new ArrayList();
+ for (String opt : opts) {
+ if (useGcPattern.matcher(opt).matches()) {
+ System.out.println("removeGcOpts: removed " + opt);
+ } else {
+ optsWithoutGC.add(opt);
+ }
+ }
+ return optsWithoutGC;
+ }
+
/**
* Splits a string by white space.
* Works like String.split(), but returns an empty array
diff --git a/jdk/test/sun/net/www/http/HttpClient/B8025710.java b/jdk/test/sun/net/www/http/HttpClient/B8025710.java
new file mode 100644
index 00000000000..8074c761188
--- /dev/null
+++ b/jdk/test/sun/net/www/http/HttpClient/B8025710.java
@@ -0,0 +1,409 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.*;
+import java.net.*;
+import java.security.*;
+import java.security.cert.X509Certificate;
+import java.util.ArrayList;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.net.ServerSocketFactory;
+import javax.net.SocketFactory;
+import javax.net.ssl.*;
+
+/**
+ * @test
+ * @bug 8025710
+ * @summary Proxied https connection reuse by HttpClient can send CONNECT to the server
+ */
+public class B8025710 {
+
+ private final static AtomicBoolean connectInServer = new AtomicBoolean();
+ private static final String keystorefile =
+ System.getProperty("test.src", "./")
+ + "/../../../../../javax/net/ssl/etc/keystore";
+ private static final String passphrase = "passphrase";
+
+ public static void main(String[] args) throws Exception {
+ new B8025710().runTest();
+
+ if (connectInServer.get())
+ throw new RuntimeException("TEST FAILED: server got proxy header");
+ else
+ System.out.println("TEST PASSED");
+ }
+
+ private void runTest() throws Exception {
+ ProxyServer proxyServer = new ProxyServer();
+ HttpServer httpServer = new HttpServer();
+ httpServer.start();
+ proxyServer.start();
+
+ URL url = new URL("https", InetAddress.getLocalHost().getHostName(),
+ httpServer.getPort(), "/");
+
+ Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyServer.getAddress());
+
+ HttpsURLConnection.setDefaultSSLSocketFactory(createTestSSLSocketFactory());
+
+ // Make two connections. The bug occurs when the second request is made
+ for (int i = 0; i < 2; i++) {
+ System.out.println("Client: Requesting " + url.toExternalForm()
+ + " via " + proxy.toString()
+ + " (attempt " + (i + 1) + " of 2)");
+
+ HttpsURLConnection connection =
+ (HttpsURLConnection) url.openConnection(proxy);
+
+ connection.setRequestMethod("POST");
+ connection.setDoInput(true);
+ connection.setDoOutput(true);
+ connection.setRequestProperty("User-Agent", "Test/1.0");
+ connection.getOutputStream().write("Hello, world!".getBytes("UTF-8"));
+
+ if (connection.getResponseCode() != 200) {
+ System.err.println("Client: Unexpected response code "
+ + connection.getResponseCode());
+ break;
+ }
+
+ String response = readLine(connection.getInputStream());
+ if (!"Hi!".equals(response)) {
+ System.err.println("Client: Unexpected response body: "
+ + response);
+ }
+ }
+ httpServer.close();
+ proxyServer.close();
+ httpServer.join();
+ proxyServer.join();
+ }
+
+ class ProxyServer extends Thread implements Closeable {
+
+ private final ServerSocket proxySocket;
+ private final Pattern connectLinePattern =
+ Pattern.compile("^CONNECT ([^: ]+):([0-9]+) HTTP/[0-9.]+$");
+ private final String PROXY_RESPONSE =
+ "HTTP/1.0 200 Connection Established\r\n"
+ + "Proxy-Agent: TestProxy/1.0\r\n"
+ + "\r\n";
+
+ ProxyServer() throws Exception {
+ super("ProxyServer Thread");
+
+ // Create the http proxy server socket
+ proxySocket = ServerSocketFactory.getDefault().createServerSocket();
+ proxySocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ }
+
+ public SocketAddress getAddress() { return proxySocket.getLocalSocketAddress(); }
+
+ @Override
+ public void close() throws IOException {
+ proxySocket.close();
+ }
+
+ @Override
+ public void run() {
+ ArrayList threads = new ArrayList<>();
+ int connectionCount = 0;
+ try {
+ while (connectionCount++ < 2) {
+ final Socket clientSocket = proxySocket.accept();
+ final int proxyConnectionCount = connectionCount;
+ System.out.println("Proxy: NEW CONNECTION "
+ + proxyConnectionCount);
+
+ Thread t = new Thread("ProxySocket" + proxyConnectionCount) {
+ @Override
+ public void run() {
+ try {
+ String firstLine =
+ readHeader(clientSocket.getInputStream());
+
+ Matcher connectLineMatcher =
+ connectLinePattern.matcher(firstLine);
+ if (!connectLineMatcher.matches()) {
+ System.out.println("Proxy: Unexpected"
+ + " request to the proxy: "
+ + firstLine);
+ return;
+ }
+
+ String host = connectLineMatcher.group(1);
+ String portStr = connectLineMatcher.group(2);
+ int port = Integer.parseInt(portStr);
+
+ Socket serverSocket = SocketFactory.getDefault()
+ .createSocket(host, port);
+
+ clientSocket.getOutputStream()
+ .write(PROXY_RESPONSE.getBytes("UTF-8"));
+
+ ProxyTunnel copyToClient =
+ new ProxyTunnel(serverSocket, clientSocket);
+ ProxyTunnel copyToServer =
+ new ProxyTunnel(clientSocket, serverSocket);
+
+ copyToClient.start();
+ copyToServer.start();
+
+ copyToClient.join();
+ // here copyToClient.close() would not provoke the
+ // bug ( since it would trigger the retry logic in
+ // HttpURLConnction.writeRequests ), so close only
+ // the output to get the connection in this state.
+ clientSocket.shutdownOutput();
+
+ try {
+ Thread.sleep(3000);
+ } catch (InterruptedException ignored) { }
+
+ // now close all connections to finish the test
+ copyToServer.close();
+ copyToClient.close();
+ } catch (IOException | NumberFormatException
+ | InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ };
+ threads.add(t);
+ t.start();
+ }
+ for (Thread t: threads)
+ t.join();
+ } catch (IOException | InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * This inner class provides unidirectional data flow through the sockets
+ * by continuously copying bytes from the input socket onto the output
+ * socket, until both sockets are open and EOF has not been received.
+ */
+ class ProxyTunnel extends Thread {
+ private final Socket sockIn;
+ private final Socket sockOut;
+ private final InputStream input;
+ private final OutputStream output;
+
+ public ProxyTunnel(Socket sockIn, Socket sockOut) throws IOException {
+ super("ProxyTunnel");
+ this.sockIn = sockIn;
+ this.sockOut = sockOut;
+ input = sockIn.getInputStream();
+ output = sockOut.getOutputStream();
+ }
+
+ public void run() {
+ byte[] buf = new byte[8192];
+ int bytesRead;
+
+ try {
+ while ((bytesRead = input.read(buf)) >= 0) {
+ output.write(buf, 0, bytesRead);
+ output.flush();
+ }
+ } catch (IOException ignored) {
+ close();
+ }
+ }
+
+ public void close() {
+ try {
+ if (!sockIn.isClosed())
+ sockIn.close();
+ if (!sockOut.isClosed())
+ sockOut.close();
+ } catch (IOException ignored) { }
+ }
+ }
+
+ /**
+ * the server thread
+ */
+ class HttpServer extends Thread implements Closeable {
+
+ private final ServerSocket serverSocket;
+ private final SSLSocketFactory sslSocketFactory;
+ private final String serverResponse =
+ "HTTP/1.1 200 OK\r\n"
+ + "Content-Type: text/plain\r\n"
+ + "Content-Length: 3\r\n"
+ + "\r\n"
+ + "Hi!";
+ private int connectionCount = 0;
+
+ HttpServer() throws Exception {
+ super("HttpServer Thread");
+
+ KeyStore ks = KeyStore.getInstance("JKS");
+ ks.load(new FileInputStream(keystorefile), passphrase.toCharArray());
+ KeyManagerFactory factory = KeyManagerFactory.getInstance("SunX509");
+ factory.init(ks, passphrase.toCharArray());
+ SSLContext ctx = SSLContext.getInstance("TLS");
+ ctx.init(factory.getKeyManagers(), null, null);
+
+ sslSocketFactory = ctx.getSocketFactory();
+
+ // Create the server that the test wants to connect to via the proxy
+ serverSocket = ServerSocketFactory.getDefault().createServerSocket();
+ serverSocket.bind(new InetSocketAddress(InetAddress.getLocalHost(), 0));
+ }
+
+ public int getPort() { return serverSocket.getLocalPort(); }
+
+ @Override
+ public void close() throws IOException { serverSocket.close(); }
+
+ @Override
+ public void run() {
+ try {
+ while (connectionCount++ < 2) {
+ Socket socket = serverSocket.accept();
+ System.out.println("Server: NEW CONNECTION "
+ + connectionCount);
+
+ SSLSocket sslSocket = (SSLSocket) sslSocketFactory
+ .createSocket(socket,null, getPort(), false);
+ sslSocket.setUseClientMode(false);
+ sslSocket.startHandshake();
+
+ String firstLine = readHeader(sslSocket.getInputStream());
+ if (firstLine != null && firstLine.contains("CONNECT")) {
+ System.out.println("Server: BUG! HTTP CONNECT"
+ + " encountered: " + firstLine);
+ connectInServer.set(true);
+ }
+
+ // write the success response, the request body is not read.
+ // close only output and keep input open.
+ OutputStream out = sslSocket.getOutputStream();
+ out.write(serverResponse.getBytes("UTF-8"));
+ socket.shutdownOutput();
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ /**
+ * read the header and return only the first line.
+ *
+ * @param inputStream the stream to read from
+ * @return the first line of the stream
+ * @throws IOException if reading failed
+ */
+ private static String readHeader(InputStream inputStream)
+ throws IOException {
+ String line;
+ String firstLine = null;
+ while ((line = readLine(inputStream)) != null && line.length() > 0) {
+ if (firstLine == null) {
+ firstLine = line;
+ }
+ }
+
+ return firstLine;
+ }
+
+ /**
+ * read a line from stream.
+ *
+ * @param inputStream the stream to read from
+ * @return the line
+ * @throws IOException if reading failed
+ */
+ private static String readLine(InputStream inputStream)
+ throws IOException {
+ final StringBuilder line = new StringBuilder();
+ int ch;
+ while ((ch = inputStream.read()) != -1) {
+ if (ch == '\r') {
+ continue;
+ }
+
+ if (ch == '\n') {
+ break;
+ }
+
+ line.append((char) ch);
+ }
+
+ return line.toString();
+ }
+
+ private SSLSocketFactory createTestSSLSocketFactory() {
+
+ HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
+ @Override
+ public boolean verify(String hostname, SSLSession sslSession) {
+ // ignore the cert's CN; it's not important to this test
+ return true;
+ }
+ });
+
+ // Set up the socket factory to use a trust manager that trusts all
+ // certs, since trust validation isn't important to this test
+ final TrustManager[] trustAllCertChains = new TrustManager[] {
+ new X509TrustManager() {
+ @Override
+ public X509Certificate[] getAcceptedIssuers() {
+ return null;
+ }
+
+ @Override
+ public void checkClientTrusted(X509Certificate[] certs,
+ String authType) {
+ }
+
+ @Override
+ public void checkServerTrusted(X509Certificate[] certs,
+ String authType) {
+ }
+ }
+ };
+
+ final SSLContext sc;
+ try {
+ sc = SSLContext.getInstance("TLS");
+ } catch (NoSuchAlgorithmException e) {
+ throw new RuntimeException(e);
+ }
+
+ try {
+ sc.init(null, trustAllCertChains, new java.security.SecureRandom());
+ } catch (KeyManagementException e) {
+ throw new RuntimeException(e);
+ }
+
+ return sc.getSocketFactory();
+ }
+}
diff --git a/jdk/test/sun/nio/cs/TestUTF8.java b/jdk/test/sun/nio/cs/TestUTF8.java
index c54ae66f4d9..010fbf17b43 100644
--- a/jdk/test/sun/nio/cs/TestUTF8.java
+++ b/jdk/test/sun/nio/cs/TestUTF8.java
@@ -23,7 +23,7 @@
/*
* @test
- * @bug 4486841 7040220 7096080
+ * @bug 4486841 7040220 7096080 8039751
* @summary Test UTF-8 charset
*/
@@ -291,14 +291,18 @@ public class TestUTF8 {
{1, (byte)0xE0, (byte)0xC0, (byte)0xBF }, // invalid second byte
{2, (byte)0xE0, (byte)0xA0, (byte)0x7F }, // invalid third byte
{2, (byte)0xE0, (byte)0xA0, (byte)0xC0 }, // invalid third byte
+ {2, (byte)0xE1, (byte)0x80, (byte)0x42}, // invalid third byte
+
{1, (byte)0xFF, (byte)0xFF, (byte)0xFF }, // all ones
{1, (byte)0xE0, (byte)0xC0, (byte)0x80 }, // invalid second byte
{1, (byte)0xE0, (byte)0x80, (byte)0xC0 }, // invalid first byte
{1, (byte)0xE0, (byte)0x41,}, // invalid second byte & 2 bytes
+ {1, (byte)0xE1, (byte)0x40,}, // invalid second byte & 2 bytes
{3, (byte)0xED, (byte)0xAE, (byte)0x80 }, // 3 bytes surrogate
{3, (byte)0xED, (byte)0xB0, (byte)0x80 }, // 3 bytes surrogate
+
// Four-byte sequences
{1, (byte)0xF0, (byte)0x80, (byte)0x80, (byte)0x80 }, // U+0000 zero-padded
{1, (byte)0xF0, (byte)0x80, (byte)0x81, (byte)0xBF }, // U+007F zero-padded
@@ -323,6 +327,32 @@ public class TestUTF8 {
{1, (byte)0xF4, (byte)0xC0, (byte)0x80, (byte)0xC0 }, // out-range 4-byte
{1, (byte)0xF5, (byte)0x80, (byte)0x80, (byte)0xC0 }, // out-range 4-byte
+ // #8039751
+ {1, (byte)0xF6, (byte)0x80, (byte)0x80, (byte)0x80 }, // out-range 1st byte
+ {1, (byte)0xF6, (byte)0x80, (byte)0x80, },
+ {1, (byte)0xF6, (byte)0x80, },
+ {1, (byte)0xF6, },
+ {1, (byte)0xF5, (byte)0x80, (byte)0x80, (byte)0x80 }, // out-range 1st byte
+ {1, (byte)0xF5, (byte)0x80, (byte)0x80, },
+ {1, (byte)0xF5, (byte)0x80, },
+ {1, (byte)0xF5 },
+
+ {1, (byte)0xF4, (byte)0x90, (byte)0x80, (byte)0x80 }, // out-range 2nd byte
+ {1, (byte)0xF4, (byte)0x90, (byte)0x80 },
+ {1, (byte)0xF4, (byte)0x90 },
+
+ {1, (byte)0xF4, (byte)0x7f, (byte)0x80, (byte)0x80 }, // out-range/ascii 2nd byte
+ {1, (byte)0xF4, (byte)0x7f, (byte)0x80 },
+ {1, (byte)0xF4, (byte)0x7f },
+
+ {1, (byte)0xF0, (byte)0x80, (byte)0x80, (byte)0x80 }, // out-range 2nd byte
+ {1, (byte)0xF0, (byte)0x80, (byte)0x80 },
+ {1, (byte)0xF0, (byte)0x80 },
+
+ {1, (byte)0xF0, (byte)0xc0, (byte)0x80, (byte)0x80 }, // out-range 2nd byte
+ {1, (byte)0xF0, (byte)0xc0, (byte)0x80 },
+ {1, (byte)0xF0, (byte)0xc0 },
+
// Five-byte sequences
{1, (byte)0xF8, (byte)0x80, (byte)0x80, (byte)0x80, (byte)0x80}, // invalid first byte
{1, (byte)0xF8, (byte)0x80, (byte)0x80, (byte)0x80, (byte)0x80 }, // U+0000 zero-padded
@@ -553,7 +583,6 @@ public class TestUTF8 {
check4ByteSurrs("UTF-8");
checkMalformed("UTF-8", malformed);
checkUnderOverflow("UTF-8");
-
checkRoundtrip("CESU-8");
check6ByteSurrs("CESU-8");
checkMalformed("CESU-8", malformed_cesu8);
diff --git a/jdk/test/sun/security/tools/jarsigner/CertChainUnclosed.java b/jdk/test/sun/security/tools/jarsigner/CertChainUnclosed.java
index 18b2eb721ef..e259207db9c 100644
--- a/jdk/test/sun/security/tools/jarsigner/CertChainUnclosed.java
+++ b/jdk/test/sun/security/tools/jarsigner/CertChainUnclosed.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -30,13 +30,15 @@
import java.nio.file.Files;
import java.nio.file.Paths;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
import java.util.Locale;
public class CertChainUnclosed {
public static void main(String[] args) throws Exception {
- String os = java.security.AccessController.doPrivileged(
- new sun.security.action.GetPropertyAction("os.name"));
+ String os = AccessController.doPrivileged(
+ (PrivilegedAction)() -> System.getProperty("os.name"));
if (!os.toUpperCase(Locale.US).contains("WINDOWS")) {
System.out.println("Not Windows. Skip test.");
return;
diff --git a/jdk/test/sun/security/tools/jarsigner/EntriesOrder.java b/jdk/test/sun/security/tools/jarsigner/EntriesOrder.java
index 96c90e98e12..908f6ef48be 100644
--- a/jdk/test/sun/security/tools/jarsigner/EntriesOrder.java
+++ b/jdk/test/sun/security/tools/jarsigner/EntriesOrder.java
@@ -25,6 +25,9 @@
* @test
* @bug 8031572
* @summary jarsigner -verify exits with 0 when a jar file is not properly signed
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.IOUtils
+ * @run main EntriesOrder
*/
import java.io.FileInputStream;
@@ -39,6 +42,8 @@ import java.util.jar.JarInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
+import jdk.testlibrary.IOUtils;
+
public class EntriesOrder {
public static void main(String[] args) throws Exception {
@@ -106,7 +111,7 @@ public class EntriesOrder {
Enumeration jes = jf.entries();
while (jes.hasMoreElements()) {
JarEntry je = jes.nextElement();
- sun.misc.IOUtils.readFully(jf.getInputStream(je), -1, true);
+ IOUtils.readFully(jf.getInputStream(je));
Certificate[] certs = je.getCertificates();
if (certs != null && certs.length > 0) {
cc++;
@@ -138,7 +143,7 @@ public class EntriesOrder {
while (true) {
JarEntry je = jis.getNextJarEntry();
if (je == null) break;
- sun.misc.IOUtils.readFully(jis, -1, true);
+ IOUtils.readFully(jis);
Certificate[] certs = je.getCertificates();
if (certs != null && certs.length > 0) {
cc++;
diff --git a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java
index 65b1cca3e1d..113bb26217d 100644
--- a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java
+++ b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java
@@ -24,10 +24,9 @@
import com.sun.net.httpserver.*;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
-import java.io.File;
import java.io.FileInputStream;
-import java.io.FileOutputStream;
import java.io.IOException;
+import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigInteger;
@@ -38,9 +37,15 @@ import java.security.Signature;
import java.security.cert.Certificate;
import java.security.cert.X509Certificate;
import java.util.Calendar;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+
+import sun.misc.IOUtils;
import sun.security.pkcs.ContentInfo;
import sun.security.pkcs.PKCS7;
+import sun.security.pkcs.PKCS9Attribute;
import sun.security.pkcs.SignerInfo;
+import sun.security.timestamp.TimestampToken;
import sun.security.util.DerOutputStream;
import sun.security.util.DerValue;
import sun.security.util.ObjectIdentifier;
@@ -51,6 +56,8 @@ public class TimestampCheck {
static final String TSKS = "tsks";
static final String JAR = "old.jar";
+ static final String defaultPolicyId = "2.3.4.5";
+
static class Handler implements HttpHandler {
public void handle(HttpExchange t) throws IOException {
int len = 0;
@@ -94,6 +101,11 @@ public class TimestampCheck {
* 6: extension is missing
* 7: extension is non-critical
* 8: extension does not have timestamping
+ * 9: no cert in response
+ * 10: normal
+ * 11: always return default policy id
+ * 12: normal
+ * otherwise: normal
* @returns the signed
*/
byte[] sign(byte[] input, int path) throws Exception {
@@ -106,6 +118,7 @@ public class TimestampCheck {
messageImprint.data.getDerValue());
System.err.println("AlgorithmId: " + aid);
+ ObjectIdentifier policyId = new ObjectIdentifier(defaultPolicyId);
BigInteger nonce = null;
while (value.data.available() > 0) {
DerValue v = value.data.getDerValue();
@@ -114,6 +127,9 @@ public class TimestampCheck {
System.err.println("nonce: " + nonce);
} else if (v.tag == DerValue.tag_Boolean) {
System.err.println("certReq: " + v.getBoolean());
+ } else if (v.tag == DerValue.tag_ObjectId) {
+ policyId = v.getOID();
+ System.err.println("PolicyID: " + policyId);
}
}
@@ -127,6 +143,10 @@ public class TimestampCheck {
if (path == 7) alias = "tsbad2";
if (path == 8) alias = "tsbad3";
+ if (path == 11) {
+ policyId = new ObjectIdentifier(defaultPolicyId);
+ }
+
DerOutputStream statusInfo = new DerOutputStream();
statusInfo.putInteger(0);
@@ -150,7 +170,7 @@ public class TimestampCheck {
DerOutputStream tst = new DerOutputStream();
tst.putInteger(1);
- tst.putOID(new ObjectIdentifier("1.2.3.4")); // policy
+ tst.putOID(policyId);
if (path != 3 && path != 4) {
tst.putDerValue(messageImprint);
@@ -260,15 +280,43 @@ public class TimestampCheck {
jarsigner(cmd, 7, false); // tsbad2
jarsigner(cmd, 8, false); // tsbad3
jarsigner(cmd, 9, false); // no cert in timestamp
- jarsigner(cmd + " -tsapolicyid 1.2.3.4", 0, true);
- jarsigner(cmd + " -tsapolicyid 1.2.3.5", 0, false);
+ jarsigner(cmd + " -tsapolicyid 1.2.3.4", 10, true);
+ checkTimestamp("new_10.jar", "1.2.3.4", "SHA-256");
+ jarsigner(cmd + " -tsapolicyid 1.2.3.5", 11, false);
+ jarsigner(cmd + " -tsadigestalg SHA", 12, true);
+ checkTimestamp("new_12.jar", defaultPolicyId, "SHA-1");
} else { // Run as a standalone server
System.err.println("Press Enter to quit server");
System.in.read();
}
} finally {
server.stop(0);
- new File("x.jar").delete();
+ }
+ }
+
+ static void checkTimestamp(String file, String policyId, String digestAlg)
+ throws Exception {
+ try (JarFile jf = new JarFile(file)) {
+ JarEntry je = jf.getJarEntry("META-INF/OLD.RSA");
+ try (InputStream is = jf.getInputStream(je)) {
+ byte[] content = IOUtils.readFully(is, -1, true);
+ PKCS7 p7 = new PKCS7(content);
+ SignerInfo[] si = p7.getSignerInfos();
+ if (si == null || si.length == 0) {
+ throw new Exception("Not signed");
+ }
+ PKCS9Attribute p9 = si[0].getUnauthenticatedAttributes()
+ .getAttribute(PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
+ PKCS7 tsToken = new PKCS7((byte[]) p9.getValue());
+ TimestampToken tt =
+ new TimestampToken(tsToken.getContentInfo().getData());
+ if (!tt.getHashAlgorithm().toString().equals(digestAlg)) {
+ throw new Exception("Digest alg different");
+ }
+ if (!tt.getPolicyID().equals(policyId)) {
+ throw new Exception("policyId different");
+ }
+ }
}
}
diff --git a/jdk/test/sun/tools/jinfo/JInfoLauncherTest.java b/jdk/test/sun/tools/jinfo/JInfoLauncherTest.java
new file mode 100644
index 00000000000..ecd88831770
--- /dev/null
+++ b/jdk/test/sun/tools/jinfo/JInfoLauncherTest.java
@@ -0,0 +1,342 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import org.testng.annotations.Test;
+import org.testng.annotations.BeforeClass;
+import sun.tools.jinfo.JInfo;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.util.Arrays;
+
+import static org.testng.Assert.*;
+
+/**
+ * @test
+ * @bug 8039080
+ * @run testng JInfoLauncherTest
+ * @summary Test JInfo launcher argument parsing
+ */
+@Test
+public class JInfoLauncherTest {
+ public static final String VALIDATION_EXCEPTION_CLSNAME =
+ IllegalArgumentException.class.getName();
+
+ private Constructor jInfoConstructor;
+ private Field fldUseSA;
+
+ @BeforeClass
+ public void setup() throws Exception {
+ jInfoConstructor = JInfo.class.getDeclaredConstructor(String[].class);
+ jInfoConstructor.setAccessible(true);
+ fldUseSA = JInfo.class.getDeclaredField("useSA");
+ fldUseSA.setAccessible(true);
+ }
+
+ private JInfo newJInfo(String[] args) throws Exception {
+ try {
+ return jInfoConstructor.newInstance((Object) args);
+ } catch (Exception e) {
+ if (isValidationException(e.getCause())) {
+ throw (Exception)e.getCause();
+ }
+ throw e;
+ }
+ }
+
+ private boolean getUseSA(JInfo jinfo) throws Exception {
+ return fldUseSA.getBoolean(jinfo);
+ }
+
+ private void cmdPID(String cmd, String ... params) throws Exception {
+ int offset = (cmd != null ? 1 : 0);
+ String[] args = new String[offset + params.length];
+ args[0] = cmd;
+ System.arraycopy(params, 0, args, offset, params.length);
+ JInfo j = newJInfo(args);
+ assertFalse(getUseSA(j), "Local jinfo must not forward to SA");
+ }
+
+ private void cmdCore(String cmd, String ... params) throws Exception {
+ int offset = (cmd != null ? 1 : 0);
+ String[] args = new String[offset + params.length];
+ args[0] = cmd;
+ System.arraycopy(params, 0, args, offset, params.length);
+ JInfo j = newJInfo(args);
+ assertTrue(getUseSA(j), "Core jinfo must forward to SA");
+ }
+
+ private void cmdRemote(String cmd, String ... params) throws Exception {
+ int offset = (cmd != null ? 1 : 0);
+ String[] args = new String[offset + params.length];
+ args[0] = cmd;
+ System.arraycopy(params, 0, args, offset, params.length);
+ JInfo j = newJInfo(args);
+ assertTrue(getUseSA(j), "Remote jinfo must forward to SA");
+ }
+
+ private void cmdExtraArgs(String cmd, int argsLen) throws Exception {
+ String[] args = new String[argsLen + 1 + (cmd != null ? 1 : 0)];
+ Arrays.fill(args, "a");
+ if (cmd != null) {
+ args[0] = cmd;
+ } else {
+ cmd = "default";
+ }
+ try {
+ JInfo j = newJInfo(args);
+ fail("\"" + cmd + "\" does not support more than " + argsLen +
+ " arguments");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ private void cmdMissingArgs(String cmd, int reqArgs) throws Exception {
+ String[] args = new String[reqArgs - 1 + (cmd != null ? 1 : 0)];
+ Arrays.fill(args, "a");
+ if (cmd != null) {
+ args[0] = cmd;
+ } else {
+ cmd = "default";
+ }
+ try {
+ JInfo j = newJInfo(args);
+ fail("\"" + cmd + "\" requires at least " + reqArgs + " argument");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testDefaultPID() throws Exception {
+ cmdPID(null, "1234");
+ }
+
+ public void testFlagsPID() throws Exception {
+ cmdPID("-flags", "1234");
+ }
+
+ public void testSyspropsPID() throws Exception {
+ cmdPID("-sysprops", "1234");
+ }
+
+ public void testReadFlagPID() throws Exception {
+ cmdPID("-flag", "SomeManagementFlag", "1234");
+ }
+
+ public void testSetFlag1PID() throws Exception {
+ cmdPID("-flag", "+SomeManagementFlag", "1234");
+ }
+
+ public void testSetFlag2PID() throws Exception {
+ cmdPID("-flag", "-SomeManagementFlag", "1234");
+ }
+
+ public void testSetFlag3PID() throws Exception {
+ cmdPID("-flag", "SomeManagementFlag=314", "1234");
+ }
+
+ public void testDefaultCore() throws Exception {
+ cmdCore(null, "myapp.exe", "my.core");
+ }
+
+ public void testFlagsCore() throws Exception {
+ cmdCore("-flags", "myapp.exe", "my.core");
+ }
+
+ public void testSyspropsCore() throws Exception {
+ cmdCore("-sysprops", "myapp.exe", "my.core");
+ }
+
+ public void testReadFlagCore() throws Exception {
+ try {
+ cmdCore("-flag", "SomeManagementFlag", "myapp.exe", "my.core");
+ fail("Flags can not be read from core files");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testSetFlag1Core() throws Exception {
+ try {
+ cmdCore("-flag", "+SomeManagementFlag", "myapp.exe", "my.core");
+ fail("Flags can not be set in core files");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testSetFlag2Core() throws Exception {
+ try {
+ cmdCore("-flag", "-SomeManagementFlag", "myapp.exe", "my.core");
+ fail("Flags can not be set in core files");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testSetFlag3Core() throws Exception {
+ try {
+ cmdCore("-flag", "SomeManagementFlag=314", "myapp.exe", "my.core");
+ fail("Flags can not be set in core files");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testDefaultRemote() throws Exception {
+ cmdRemote(null, "serverid@host");
+ }
+
+ public void testFlagsRemote() throws Exception {
+ cmdRemote("-flags", "serverid@host");
+ }
+
+ public void testSyspropsRemote() throws Exception {
+ cmdRemote("-sysprops", "serverid@host");
+ }
+
+ public void testReadFlagRemote() throws Exception {
+ try {
+ cmdCore("-flag", "SomeManagementFlag", "serverid@host");
+ fail("Flags can not be read from SA server");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testSetFlag1Remote() throws Exception {
+ try {
+ cmdCore("-flag", "+SomeManagementFlag","serverid@host");
+ fail("Flags can not be set on SA server");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testSetFlag2Remote() throws Exception {
+ try {
+ cmdCore("-flag", "-SomeManagementFlag", "serverid@host");
+ fail("Flags can not be read set on SA server");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testSetFlag3Remote() throws Exception {
+ try {
+ cmdCore("-flag", "SomeManagementFlag=314", "serverid@host");
+ fail("Flags can not be read set on SA server");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ public void testDefaultExtraArgs() throws Exception {
+ cmdExtraArgs(null, 2);
+ }
+
+ public void testFlagsExtraArgs() throws Exception {
+ cmdExtraArgs("-flags", 2);
+ }
+
+ public void testSyspropsExtraArgs() throws Exception {
+ cmdExtraArgs("-sysprops", 2);
+ }
+
+ public void testFlagExtraArgs() throws Exception {
+ cmdExtraArgs("-flag", 2);
+ }
+
+ public void testHelp1ExtraArgs() throws Exception {
+ cmdExtraArgs("-h", 0);
+ }
+
+ public void testHelp2ExtraArgs() throws Exception {
+ cmdExtraArgs("-help", 0);
+ }
+
+ public void testDefaultMissingArgs() throws Exception {
+ cmdMissingArgs(null, 1);
+ }
+
+ public void testFlagsMissingArgs() throws Exception {
+ cmdMissingArgs("-flags", 1);
+ }
+
+ public void testSyspropsMissingArgs() throws Exception {
+ cmdMissingArgs("-sysprops", 1);
+ }
+
+ public void testFlagMissingArgs() throws Exception {
+ cmdMissingArgs("-flag", 2);
+ }
+
+ public void testUnknownCommand() throws Exception {
+ try {
+ JInfo j = newJInfo(new String[]{"-unknown_command"});
+ fail("JInfo accepts unknown commands");
+ } catch (Exception e) {
+ if (!isValidationException(e)) {
+ throw e;
+ }
+ // ignore
+ }
+ }
+
+ private static boolean isValidationException(Throwable e) {
+ return e.getClass().getName().equals(VALIDATION_EXCEPTION_CLSNAME);
+ }
+}
diff --git a/langtools/.hgtags b/langtools/.hgtags
index 0f2ed6e96c3..994cf39c50c 100644
--- a/langtools/.hgtags
+++ b/langtools/.hgtags
@@ -250,3 +250,6 @@ fa2ec6b6b1697ae4a78b03b609664dc6b47dee86 jdk9-b04
1d5e6fc88a4cca287090c16b0530a0d5849a5603 jdk9-b05
31946c0a3f4dc2c78f6f09a0524aaa2a0dad1c78 jdk9-b06
e25d44c21b29e155734f8d832f2edac3d0debe35 jdk9-b07
+ea02d24b3f1dd1417132d6587dd38b056cca0be2 jdk9-b08
+2d13524486b46a0f879361fbadf68fe42d02d221 jdk9-b09
+7736a820af6f15cef9a1499f122e40abc83b2fbd jdk9-b10
diff --git a/langtools/make/netbeans/langtools/build.xml b/langtools/make/netbeans/langtools/build.xml
index c0b6ae26c29..0f7aeb2cee6 100644
--- a/langtools/make/netbeans/langtools/build.xml
+++ b/langtools/make/netbeans/langtools/build.xml
@@ -1,6 +1,6 @@
diff --git a/langtools/make/netbeans/langtools/nbproject/project.properties b/langtools/make/netbeans/langtools/nbproject/project.properties
new file mode 100644
index 00000000000..31b5a412ac6
--- /dev/null
+++ b/langtools/make/netbeans/langtools/nbproject/project.properties
@@ -0,0 +1,10 @@
+auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.expand-tabs=true
+auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.indent-shift-width=4
+auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.spaces-per-tab=4
+auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.tab-size=8
+auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-limit-width=100
+auxiliary.org-netbeans-modules-editor-indent.CodeStyle.project.text-line-wrap=none
+auxiliary.org-netbeans-modules-editor-indent.CodeStyle.usedProfile=project
+auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importGroupsOrder=java;javax;*;static java;static javax;static *
+auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.importInnerClasses=true
+auxiliary.org-netbeans-modules-editor-indent.text.x-java.CodeStyle.project.separateStaticImports=true
diff --git a/langtools/make/netbeans/langtools/nbproject/project.xml b/langtools/make/netbeans/langtools/nbproject/project.xml
index 710d523bfae..1327daed9f3 100644
--- a/langtools/make/netbeans/langtools/nbproject/project.xml
+++ b/langtools/make/netbeans/langtools/nbproject/project.xml
@@ -1,6 +1,6 @@
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
diff --git a/langtools/make/netbeans/langtools/nbproject/standard-ide-actions.ent b/langtools/make/netbeans/langtools/nbproject/standard-ide-actions.ent
deleted file mode 100644
index 2d1afa7a046..00000000000
--- a/langtools/make/netbeans/langtools/nbproject/standard-ide-actions.ent
+++ /dev/null
@@ -1,173 +0,0 @@
-
-
-
-
-
-
- build
-
-
-
- clean
-
-
-
- clean
- build
-
-
-
- compile-single
- ${root}/src/share/classes
-
- includes
- ${root}/src/share/classes
- \.java$
- relative-path
-
- ,
-
-
-
-
-
- run
-
-
-
- run-single
-
- run.classname
- ${root}/src/share/classes
- \.java$
- java-name
-
-
-
-
-
-
-
-
-
- jtreg
-
- jtreg.tests
- ${root}/test
- \.(java|sh)$
- relative-path
-
- ,
-
-
-
-
-
- jtreg
-
-
-
- debug
-
-
-
- debug-single
-
- debug.classname
- ${root}/src/share/classes
- \.java$
- java-name
-
-
-
-
-
-
-
-
-
- debug-jtreg
-
- jtreg.tests
- ${root}/test
- \.(java|sh)$
- relative-path
-
-
-
-
-
-
-
- debug-fix
- ${root}/src/share/classes
-
- class
- ${root}/src/share/classes
- \.java$
- relative-path-noext
-
-
-
-
-
-
-
- javadoc
-
-
-
- select-tool
-
-
-
- test-select-tool-1
-
-
-
- test-select-tool-2
-
diff --git a/langtools/make/tools/genstubs/GenStubs.java b/langtools/make/tools/genstubs/GenStubs.java
index ffa95c97792..9f8fc7a7a59 100644
--- a/langtools/make/tools/genstubs/GenStubs.java
+++ b/langtools/make/tools/genstubs/GenStubs.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -316,7 +316,8 @@ public class GenStubs {
}
defs.add(def);
}
- return m.TopLevel(tree.packageAnnotations, tree.pid, defs.toList());
+ tree.defs = tree.defs.intersect(defs.toList());
+ return tree;
}
@Override
diff --git a/langtools/src/share/classes/com/sun/source/tree/CompilationUnitTree.java b/langtools/src/share/classes/com/sun/source/tree/CompilationUnitTree.java
index 9ded6b676b5..d401a31bfa5 100644
--- a/langtools/src/share/classes/com/sun/source/tree/CompilationUnitTree.java
+++ b/langtools/src/share/classes/com/sun/source/tree/CompilationUnitTree.java
@@ -41,6 +41,12 @@ import javax.tools.JavaFileObject;
public interface CompilationUnitTree extends Tree {
List extends AnnotationTree> getPackageAnnotations();
ExpressionTree getPackageName();
+
+ /**
+ * Return the PackageTree associated with this compilation unit.
+ * @since 1.9
+ */
+ PackageTree getPackage();
List extends ImportTree> getImports();
List extends Tree> getTypeDecls();
JavaFileObject getSourceFile();
diff --git a/langtools/src/share/classes/com/sun/source/tree/PackageTree.java b/langtools/src/share/classes/com/sun/source/tree/PackageTree.java
new file mode 100644
index 00000000000..c2d822e8b05
--- /dev/null
+++ b/langtools/src/share/classes/com/sun/source/tree/PackageTree.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.sun.source.tree;
+
+import java.util.List;
+
+/**
+ * Represents the package declaration.
+ *
+ * @jls sections 7.3, and 7.4
+ *
+ * @author Paul Govereau
+ * @since 1.9
+ */
+@jdk.Exported
+public interface PackageTree extends Tree {
+ List extends AnnotationTree> getAnnotations();
+ ExpressionTree getPackageName();
+}
diff --git a/langtools/src/share/classes/com/sun/source/tree/Tree.java b/langtools/src/share/classes/com/sun/source/tree/Tree.java
index b416f08a0fe..de3166dc5ad 100644
--- a/langtools/src/share/classes/com/sun/source/tree/Tree.java
+++ b/langtools/src/share/classes/com/sun/source/tree/Tree.java
@@ -207,6 +207,12 @@ public interface Tree {
*/
LAMBDA_EXPRESSION(LambdaExpressionTree.class),
+ /**
+ * Used for instances of {@link PackageTree}.
+ * @since 1.9
+ */
+ PACKAGE(PackageTree.class),
+
/**
* Used for instances of {@link ParenthesizedTree}.
*/
diff --git a/langtools/src/share/classes/com/sun/source/tree/TreeVisitor.java b/langtools/src/share/classes/com/sun/source/tree/TreeVisitor.java
index 9a03ef2518c..db1f32af9ee 100644
--- a/langtools/src/share/classes/com/sun/source/tree/TreeVisitor.java
+++ b/langtools/src/share/classes/com/sun/source/tree/TreeVisitor.java
@@ -88,6 +88,7 @@ public interface TreeVisitor {
R visitNewArray(NewArrayTree node, P p);
R visitNewClass(NewClassTree node, P p);
R visitLambdaExpression(LambdaExpressionTree node, P p);
+ R visitPackage(PackageTree node, P p);
R visitParenthesized(ParenthesizedTree node, P p);
R visitReturn(ReturnTree node, P p);
R visitMemberSelect(MemberSelectTree node, P p);
diff --git a/langtools/src/share/classes/com/sun/source/util/SimpleTreeVisitor.java b/langtools/src/share/classes/com/sun/source/util/SimpleTreeVisitor.java
index 4ae4ac15e12..19599456959 100644
--- a/langtools/src/share/classes/com/sun/source/util/SimpleTreeVisitor.java
+++ b/langtools/src/share/classes/com/sun/source/util/SimpleTreeVisitor.java
@@ -65,6 +65,10 @@ public class SimpleTreeVisitor implements TreeVisitor {
return defaultAction(node, p);
}
+ public R visitPackage(PackageTree node, P p) {
+ return defaultAction(node, p);
+ }
+
public R visitImport(ImportTree node, P p) {
return defaultAction(node, p);
}
diff --git a/langtools/src/share/classes/com/sun/source/util/TreeScanner.java b/langtools/src/share/classes/com/sun/source/util/TreeScanner.java
index c709f59d730..a14cad476c4 100644
--- a/langtools/src/share/classes/com/sun/source/util/TreeScanner.java
+++ b/langtools/src/share/classes/com/sun/source/util/TreeScanner.java
@@ -114,13 +114,18 @@ public class TreeScanner implements TreeVisitor {
****************************************************************************/
public R visitCompilationUnit(CompilationUnitTree node, P p) {
- R r = scan(node.getPackageAnnotations(), p);
- r = scanAndReduce(node.getPackageName(), p, r);
+ R r = scan(node.getPackage(), p);
r = scanAndReduce(node.getImports(), p, r);
r = scanAndReduce(node.getTypeDecls(), p, r);
return r;
}
+ public R visitPackage(PackageTree node, P p) {
+ R r = scan(node.getAnnotations(), p);
+ r = scanAndReduce(node.getPackageName(), p, r);
+ return r;
+ }
+
public R visitImport(ImportTree node, P p) {
return scan(node.getQualifiedIdentifier(), p);
}
diff --git a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConfigurationImpl.java b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConfigurationImpl.java
index ad32ee5088f..a9f3d17c422 100644
--- a/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConfigurationImpl.java
+++ b/langtools/src/share/classes/com/sun/tools/doclets/formats/html/ConfigurationImpl.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -248,7 +248,7 @@ public class ConfigurationImpl extends Configuration {
} else if (opt.equals("-doctitle")) {
doctitle = os[1];
} else if (opt.equals("-windowtitle")) {
- windowtitle = os[1];
+ windowtitle = os[1].replaceAll("\\<.*?>", "");
} else if (opt.equals("-top")) {
top = os[1];
} else if (opt.equals("-bottom")) {
diff --git a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Extern.java b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Extern.java
index 571c54ee485..e043db17293 100644
--- a/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Extern.java
+++ b/langtools/src/share/classes/com/sun/tools/doclets/internal/toolkit/util/Extern.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -177,7 +177,7 @@ public class Extern {
try {
url = adjustEndFileSeparator(url);
if (isUrl(pkglisturl)) {
- readPackageListFromURL(url, toURL(pkglisturl));
+ readPackageListFromURL(url, toURL(adjustEndFileSeparator(pkglisturl)));
} else {
readPackageListFromFile(url, DocFile.createFileForInput(configuration, pkglisturl));
}
diff --git a/langtools/src/share/classes/com/sun/tools/doclint/Checker.java b/langtools/src/share/classes/com/sun/tools/doclint/Checker.java
index e89a460525f..54b79ba4271 100644
--- a/langtools/src/share/classes/com/sun/tools/doclint/Checker.java
+++ b/langtools/src/share/classes/com/sun/tools/doclint/Checker.java
@@ -75,6 +75,7 @@ import com.sun.source.doctree.UnknownBlockTagTree;
import com.sun.source.doctree.UnknownInlineTagTree;
import com.sun.source.doctree.ValueTree;
import com.sun.source.doctree.VersionTree;
+import com.sun.source.tree.Tree;
import com.sun.source.util.DocTreePath;
import com.sun.source.util.DocTreePathScanner;
import com.sun.source.util.TreePath;
@@ -145,8 +146,8 @@ public class Checker extends DocTreePathScanner {
boolean isOverridingMethod = !env.currOverriddenMethods.isEmpty();
- if (p.getLeaf() == p.getCompilationUnit()) {
- // If p points to a compilation unit, the implied declaration is the
+ if (p.getLeaf().getKind() == Tree.Kind.PACKAGE) {
+ // If p points to a package, the implied declaration is the
// package declaration (if any) for the compilation unit.
// Handle this case specially, because doc comments are only
// expected in package-info files.
diff --git a/langtools/src/share/classes/com/sun/tools/doclint/DocLint.java b/langtools/src/share/classes/com/sun/tools/doclint/DocLint.java
index 0c8e6661e36..1f8db0dc414 100644
--- a/langtools/src/share/classes/com/sun/tools/doclint/DocLint.java
+++ b/langtools/src/share/classes/com/sun/tools/doclint/DocLint.java
@@ -42,6 +42,7 @@ import javax.tools.StandardLocation;
import com.sun.source.doctree.DocCommentTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
+import com.sun.source.tree.PackageTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.VariableTree;
@@ -346,13 +347,10 @@ public class DocLint implements Plugin {
abstract void visitDecl(Tree tree, Name name);
@Override
- public Void visitCompilationUnit(CompilationUnitTree tree, Void ignore) {
- if (tree.getPackageName() != null) {
- visitDecl(tree, null);
- }
- return super.visitCompilationUnit(tree, ignore);
+ public Void visitPackage(PackageTree tree, Void ignore) {
+ visitDecl(tree, null);
+ return super.visitPackage(tree, ignore);
}
-
@Override
public Void visitClass(ClassTree tree, Void ignore) {
visitDecl(tree, tree.getSimpleName());
diff --git a/langtools/src/share/classes/com/sun/tools/javac/code/TypeAnnotationPosition.java b/langtools/src/share/classes/com/sun/tools/javac/code/TypeAnnotationPosition.java
index 0845f121ab8..39b53f99cba 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/code/TypeAnnotationPosition.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/code/TypeAnnotationPosition.java
@@ -151,18 +151,14 @@ public class TypeAnnotationPosition {
public final int parameter_index;
// For class extends, implements, and throws clauses
+ public final int type_index;
- // This field is effectively final. However, it needs to be
- // modified by Gen for the time being. Do not introduce new
- // mutations.
- public int type_index;
-
- // For exception parameters, index into exception table.
- // In com.sun.tools.javac.jvm.Gen.genCatch we first set the type_index
- // to the catch type index - that value is only temporary.
- // Then in com.sun.tools.javac.jvm.Code.fillExceptionParameterPositions
- // we use that value to determine the exception table index.
- public int exception_index = Integer.MIN_VALUE;
+ // For exception parameters, index into exception table. In
+ // com.sun.tools.javac.jvm.Gen.genCatch, we first use this to hold
+ // the catch type index. Then in
+ // com.sun.tools.javac.jvm.Code.fillExceptionParameterPositions we
+ // use that value to determine the exception table index.
+ private int exception_index = Integer.MIN_VALUE;
// If this type annotation is within a lambda expression,
// store a pointer to the lambda expression tree in order
@@ -309,6 +305,38 @@ public class TypeAnnotationPosition {
isValidOffset = true;
}
+ public boolean hasExceptionIndex() {
+ return exception_index >= 0;
+ }
+
+ public int getExceptionIndex() {
+ Assert.check(exception_index >= 0, "exception_index does not contain a bytecode offset");
+ return exception_index;
+ }
+
+ public void setExceptionIndex(final int exception_index) {
+ Assert.check(hasCatchType(), "exception_index already contains a bytecode offset");
+ Assert.check(exception_index >= 0, "Expected a valid bytecode offset");
+ this.exception_index = exception_index;
+ }
+
+ public boolean hasCatchType() {
+ return exception_index < 0 && exception_index != Integer.MIN_VALUE;
+ }
+
+ public int getCatchType() {
+ Assert.check(hasCatchType(),
+ "exception_index does not contain a valid catch type");
+ return (-this.exception_index) - 1 ;
+ }
+
+ public void setCatchType(final int catchType) {
+ Assert.check(this.exception_index < 0,
+ "exception_index already contains a bytecode index");
+ Assert.check(catchType >= 0, "Expected a valid catch type");
+ this.exception_index = -(catchType + 1);
+ }
+
/**
* Decode the binary representation for a type path and set
* the {@code location} field.
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java
index 1db0f325214..c23b92881f9 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Attr.java
@@ -2616,7 +2616,7 @@ public class Attr extends JCTree.Visitor {
* - an instance field, we use the first constructor.
* - a static field, we create a fake clinit method.
*/
- private Env lambdaEnv(JCLambda that, Env env) {
+ public Env lambdaEnv(JCLambda that, Env env) {
Env lambdaEnv;
Symbol owner = env.info.scope.owner;
if (owner.kind == VAR && owner.owner.kind == TYP) {
@@ -3011,15 +3011,6 @@ public class Attr extends JCTree.Visitor {
Type ctype = cfolder.fold1(opc, argtype);
if (ctype != null) {
owntype = cfolder.coerce(ctype, owntype);
-
- // Remove constant types from arguments to
- // conserve space. The parser will fold concatenations
- // of string literals; the code here also
- // gets rid of intermediate results when some of the
- // operands are constant identifiers.
- if (tree.arg.type.tsym == syms.stringType.tsym) {
- tree.arg.type = syms.stringType;
- }
}
}
}
@@ -3053,18 +3044,6 @@ public class Attr extends JCTree.Visitor {
Type ctype = cfolder.fold2(opc, left, right);
if (ctype != null) {
owntype = cfolder.coerce(ctype, owntype);
-
- // Remove constant types from arguments to
- // conserve space. The parser will fold concatenations
- // of string literals; the code here also
- // gets rid of intermediate results when some of the
- // operands are constant identifiers.
- if (tree.lhs.type.tsym == syms.stringType.tsym) {
- tree.lhs.type = syms.stringType;
- }
- if (tree.rhs.type.tsym == syms.stringType.tsym) {
- tree.rhs.type = syms.stringType;
- }
}
}
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java b/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java
index f3a6489e42a..617d2d177e7 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/DeferredAttr.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,7 @@
package com.sun.tools.javac.comp;
-import com.sun.source.tree.MemberReferenceTree;
+import com.sun.source.tree.LambdaExpressionTree.BodyKind;
import com.sun.tools.javac.code.*;
import com.sun.tools.javac.tree.*;
import com.sun.tools.javac.util.*;
@@ -35,10 +35,8 @@ import com.sun.tools.javac.code.Type.*;
import com.sun.tools.javac.comp.Attr.ResultInfo;
import com.sun.tools.javac.comp.Infer.InferenceContext;
import com.sun.tools.javac.comp.Resolve.MethodResolutionPhase;
-import com.sun.tools.javac.comp.Resolve.ReferenceLookupHelper;
import com.sun.tools.javac.tree.JCTree.*;
-
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
@@ -48,6 +46,7 @@ import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
+import static com.sun.tools.javac.code.Kinds.VAL;
import static com.sun.tools.javac.code.TypeTag.*;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
@@ -75,6 +74,8 @@ public class DeferredAttr extends JCTree.Visitor {
final Symtab syms;
final TreeMaker make;
final Types types;
+ final Flow flow;
+ final Names names;
public static DeferredAttr instance(Context context) {
DeferredAttr instance = context.get(deferredAttrKey);
@@ -95,7 +96,8 @@ public class DeferredAttr extends JCTree.Visitor {
syms = Symtab.instance(context);
make = TreeMaker.instance(context);
types = Types.instance(context);
- Names names = Names.instance(context);
+ flow = Flow.instance(context);
+ names = Names.instance(context);
stuckTree = make.Ident(names.empty).setType(Type.stuckType);
emptyDeferredAttrContext =
new DeferredAttrContext(AttrMode.CHECK, null, MethodResolutionPhase.BOX, infer.emptyContext, null, null) {
@@ -138,6 +140,11 @@ public class DeferredAttr extends JCTree.Visitor {
return DEFERRED;
}
+ @Override
+ public String toString() {
+ return "DeferredType";
+ }
+
/**
* A speculative cache is used to keep track of all overload resolution rounds
* that triggered speculative attribution on a given deferred type. Each entry
@@ -376,7 +383,9 @@ public class DeferredAttr extends JCTree.Visitor {
}
}
//where
- protected TreeScanner unenterScanner = new TreeScanner() {
+ protected UnenterScanner unenterScanner = new UnenterScanner();
+
+ class UnenterScanner extends TreeScanner {
@Override
public void visitClassDef(JCClassDecl tree) {
ClassSymbol csym = tree.sym;
@@ -389,7 +398,7 @@ public class DeferredAttr extends JCTree.Visitor {
syms.classes.remove(csym.flatname);
super.visitClassDef(tree);
}
- };
+ }
/**
* A deferred context is created on each method check. A deferred context is
@@ -593,19 +602,111 @@ public class DeferredAttr extends JCTree.Visitor {
public void visitLambda(JCLambda tree) {
Check.CheckContext checkContext = resultInfo.checkContext;
Type pt = resultInfo.pt;
- if (inferenceContext.inferencevars.contains(pt)) {
- //ok
- return;
- } else {
+ if (!inferenceContext.inferencevars.contains(pt)) {
//must be a functional descriptor
+ Type descriptorType = null;
try {
- Type desc = types.findDescriptorType(pt);
- if (desc.getParameterTypes().length() != tree.params.length()) {
- checkContext.report(tree, diags.fragment("incompatible.arg.types.in.lambda"));
- }
+ descriptorType = types.findDescriptorType(pt);
} catch (Types.FunctionDescriptorLookupError ex) {
checkContext.report(null, ex.getDiagnostic());
}
+
+ if (descriptorType.getParameterTypes().length() != tree.params.length()) {
+ checkContext.report(tree,
+ diags.fragment("incompatible.arg.types.in.lambda"));
+ }
+
+ Type currentReturnType = descriptorType.getReturnType();
+ boolean returnTypeIsVoid = currentReturnType.hasTag(VOID);
+ if (tree.getBodyKind() == BodyKind.EXPRESSION) {
+ boolean isExpressionCompatible = !returnTypeIsVoid ||
+ TreeInfo.isExpressionStatement((JCExpression)tree.getBody());
+ if (!isExpressionCompatible) {
+ resultInfo.checkContext.report(tree.pos(),
+ diags.fragment("incompatible.ret.type.in.lambda",
+ diags.fragment("missing.ret.val", currentReturnType)));
+ }
+ } else {
+ LambdaBodyStructChecker lambdaBodyChecker =
+ new LambdaBodyStructChecker();
+
+ tree.body.accept(lambdaBodyChecker);
+ boolean isVoidCompatible = lambdaBodyChecker.isVoidCompatible;
+
+ if (returnTypeIsVoid) {
+ if (!isVoidCompatible) {
+ resultInfo.checkContext.report(tree.pos(),
+ diags.fragment("unexpected.ret.val"));
+ }
+ } else {
+ boolean isValueCompatible = lambdaBodyChecker.isPotentiallyValueCompatible
+ && !canLambdaBodyCompleteNormally(tree);
+ if (!isValueCompatible && !isVoidCompatible) {
+ log.error(tree.body.pos(),
+ "lambda.body.neither.value.nor.void.compatible");
+ }
+
+ if (!isValueCompatible) {
+ resultInfo.checkContext.report(tree.pos(),
+ diags.fragment("incompatible.ret.type.in.lambda",
+ diags.fragment("missing.ret.val", currentReturnType)));
+ }
+ }
+ }
+ }
+ }
+
+ boolean canLambdaBodyCompleteNormally(JCLambda tree) {
+ JCLambda newTree = new TreeCopier<>(make).copy(tree);
+ /* attr.lambdaEnv will create a meaningful env for the
+ * lambda expression. This is specially useful when the
+ * lambda is used as the init of a field. But we need to
+ * remove any added symbol.
+ */
+ Env localEnv = attr.lambdaEnv(newTree, env);
+ try {
+ List tmpParams = newTree.params;
+ while (tmpParams.nonEmpty()) {
+ tmpParams.head.vartype = make.at(tmpParams.head).Type(syms.errType);
+ tmpParams = tmpParams.tail;
+ }
+
+ attr.attribStats(newTree.params, localEnv);
+
+ /* set pt to Type.noType to avoid generating any bound
+ * which may happen if lambda's return type is an
+ * inference variable
+ */
+ Attr.ResultInfo bodyResultInfo = attr.new ResultInfo(VAL, Type.noType);
+ localEnv.info.returnResult = bodyResultInfo;
+
+ // discard any log output
+ Log.DiagnosticHandler diagHandler = new Log.DiscardDiagnosticHandler(log);
+ try {
+ JCBlock body = (JCBlock)newTree.body;
+ /* we need to attribute the lambda body before
+ * doing the aliveness analysis. This is because
+ * constant folding occurs during attribution
+ * and the reachability of some statements depends
+ * on constant values, for example:
+ *
+ * while (true) {...}
+ */
+ attr.attribStats(body.stats, localEnv);
+
+ attr.preFlow(newTree);
+ /* make an aliveness / reachability analysis of the lambda
+ * to determine if it can complete normally
+ */
+ flow.analyzeLambda(localEnv, newTree, make, true);
+ } finally {
+ log.popDiagnosticHandler(diagHandler);
+ }
+ return newTree.canCompleteNormally;
+ } finally {
+ JCBlock body = (JCBlock)newTree.body;
+ unenterScanner.scan(body.stats);
+ localEnv.info.scope.leave();
}
}
@@ -623,10 +724,7 @@ public class DeferredAttr extends JCTree.Visitor {
public void visitReference(JCMemberReference tree) {
Check.CheckContext checkContext = resultInfo.checkContext;
Type pt = resultInfo.pt;
- if (inferenceContext.inferencevars.contains(pt)) {
- //ok
- return;
- } else {
+ if (!inferenceContext.inferencevars.contains(pt)) {
try {
types.findDescriptorType(pt);
} catch (Types.FunctionDescriptorLookupError ex) {
@@ -656,6 +754,40 @@ public class DeferredAttr extends JCTree.Visitor {
}
}
}
+
+ /* This visitor looks for return statements, its analysis will determine if
+ * a lambda body is void or value compatible. We must analyze return
+ * statements contained in the lambda body only, thus any return statement
+ * contained in an inner class or inner lambda body, should be ignored.
+ */
+ class LambdaBodyStructChecker extends TreeScanner {
+ boolean isVoidCompatible = true;
+ boolean isPotentiallyValueCompatible = true;
+
+ @Override
+ public void visitClassDef(JCClassDecl tree) {
+ // do nothing
+ }
+
+ @Override
+ public void visitLambda(JCLambda tree) {
+ // do nothing
+ }
+
+ @Override
+ public void visitNewClass(JCNewClass tree) {
+ // do nothing
+ }
+
+ @Override
+ public void visitReturn(JCReturn tree) {
+ if (tree.expr != null) {
+ isVoidCompatible = false;
+ } else {
+ isPotentiallyValueCompatible = false;
+ }
+ }
+ }
}
/** an empty deferred attribution context - all methods throw exceptions */
@@ -767,7 +899,7 @@ public class DeferredAttr extends JCTree.Visitor {
/**
* handler that is executed when a node has been discarded
*/
- abstract void skip(JCTree tree);
+ void skip(JCTree tree) {}
}
/**
@@ -779,11 +911,6 @@ public class DeferredAttr extends JCTree.Visitor {
PolyScanner() {
super(EnumSet.of(CONDEXPR, PARENS, LAMBDA, REFERENCE));
}
-
- @Override
- void skip(JCTree tree) {
- //do nothing
- }
}
/**
@@ -796,11 +923,6 @@ public class DeferredAttr extends JCTree.Visitor {
super(EnumSet.of(BLOCK, CASE, CATCH, DOLOOP, FOREACHLOOP,
FORLOOP, RETURN, SYNCHRONIZED, SWITCH, TRY, WHILELOOP));
}
-
- @Override
- void skip(JCTree tree) {
- //do nothing
- }
}
/**
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Enter.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Enter.java
index c9985f7c997..bd189b3b696 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Enter.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Enter.java
@@ -288,15 +288,16 @@ public class Enter extends JCTree.Visitor {
boolean addEnv = false;
boolean isPkgInfo = tree.sourcefile.isNameCompatible("package-info",
JavaFileObject.Kind.SOURCE);
- if (tree.pid != null) {
- tree.packge = syms.enterPackage(TreeInfo.fullName(tree.pid));
- if (tree.packageAnnotations.nonEmpty()
- || pkginfoOpt == PkgInfo.ALWAYS
- || tree.docComments != null) {
+ JCPackageDecl pd = tree.getPackage();
+ if (pd != null) {
+ tree.packge = pd.packge = syms.enterPackage(TreeInfo.fullName(pd.pid));
+ if ( pd.annotations.nonEmpty()
+ || pkginfoOpt == PkgInfo.ALWAYS
+ || tree.docComments != null) {
if (isPkgInfo) {
addEnv = true;
- } else if (tree.packageAnnotations.nonEmpty()){
- log.error(tree.packageAnnotations.head.pos(),
+ } else if (pd.annotations.nonEmpty()) {
+ log.error(pd.annotations.head.pos(),
"pkg.annotations.sb.in.package-info.java");
}
}
@@ -305,26 +306,20 @@ public class Enter extends JCTree.Visitor {
}
tree.packge.complete(); // Find all classes in package.
Env topEnv = topLevelEnv(tree);
+ Env packageEnv = isPkgInfo ? topEnv.dup(pd) : null;
// Save environment of package-info.java file.
if (isPkgInfo) {
Env env0 = typeEnvs.get(tree.packge);
- if (env0 == null) {
- typeEnvs.put(tree.packge, topEnv);
- } else {
+ if (env0 != null) {
JCCompilationUnit tree0 = env0.toplevel;
if (!fileManager.isSameFile(tree.sourcefile, tree0.sourcefile)) {
- log.warning(tree.pid != null ? tree.pid.pos()
- : null,
+ log.warning(pd != null ? pd.pid.pos() : null,
"pkg-info.already.seen",
tree.packge);
- if (addEnv || (tree0.packageAnnotations.isEmpty() &&
- tree.docComments != null &&
- tree.docComments.hasComment(tree))) {
- typeEnvs.put(tree.packge, topEnv);
- }
}
}
+ typeEnvs.put(tree.packge, packageEnv);
for (Symbol q = tree.packge; q != null && q.kind == PCK; q = q.owner)
q.flags_field |= EXISTS;
@@ -339,7 +334,7 @@ public class Enter extends JCTree.Visitor {
}
classEnter(tree.defs, topEnv);
if (addEnv) {
- todo.append(topEnv);
+ todo.append(packageEnv);
}
log.useSource(prev);
result = null;
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java
index d18988c7515..a269fcec866 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Flow.java
@@ -1,5 +1,5 @@
/*
- * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2014, Oracle and/or its affiliates. All rights reserved.
* 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,7 +45,7 @@ import static com.sun.tools.javac.code.TypeTag.VOID;
import static com.sun.tools.javac.tree.JCTree.Tag.*;
/** This pass implements dataflow analysis for Java programs though
- * different AST visitor steps. Liveness analysis (see AliveAlanyzer) checks that
+ * different AST visitor steps. Liveness analysis (see AliveAnalyzer) checks that
* every statement is reachable. Exception analysis (see FlowAnalyzer) ensures that
* every checked exception that is thrown is declared or caught. Definite assignment analysis
* (see AssignAnalyzer) ensures that each variable is assigned when used. Definite
@@ -388,6 +388,10 @@ public class Flow {
super.scan(tree);
}
}
+
+ public void visitPackageDef(JCPackageDecl tree) {
+ // Do nothing for PackageDecl
+ }
}
/**
@@ -723,10 +727,6 @@ public class Flow {
}
}
- public void visitTopLevel(JCCompilationUnit tree) {
- // Do nothing for TopLevel since each class is visited individually
- }
-
/**************************************************************************
* main method
*************************************************************************/
@@ -1289,10 +1289,6 @@ public class Flow {
}
}
- public void visitTopLevel(JCCompilationUnit tree) {
- // Do nothing for TopLevel since each class is visited individually
- }
-
/**************************************************************************
* main method
*************************************************************************/
@@ -2357,10 +2353,6 @@ public class Flow {
tree.underlyingType.accept(this);
}
- public void visitTopLevel(JCCompilationUnit tree) {
- // Do nothing for TopLevel since each class is visited individually
- }
-
/**************************************************************************
* main method
*************************************************************************/
@@ -2677,10 +2669,6 @@ public class Flow {
}
}
- public void visitTopLevel(JCCompilationUnit tree) {
- // Do nothing for TopLevel since each class is visited individually
- }
-
/**************************************************************************
* main method
*************************************************************************/
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java
index 1fe49587172..b34f36fefa9 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Infer.java
@@ -515,6 +515,32 @@ public class Infer {
/** max number of incorporation rounds */
static final int MAX_INCORPORATION_STEPS = 100;
+ /* If for two types t and s there is a least upper bound that is a
+ * parameterized type G, then there exists a supertype of 't' of the form
+ * G and a supertype of 's' of the form G
+ * which will be returned by this method. If no such supertypes exists then
+ * null is returned.
+ *
+ * As an example for the following input:
+ *
+ * t = java.util.ArrayList
+ * s = java.util.List
+ *
+ * we get this ouput:
+ *
+ * Pair[java.util.List,java.util.List]
+ */
+ private Pair getParameterizedSupers(Type t, Type s) {
+ Type lubResult = types.lub(t, s);
+ if (lubResult == syms.errType || lubResult == syms.botType ||
+ !lubResult.isParameterized()) {
+ return null;
+ }
+ Type asSuperOfT = types.asSuper(t, lubResult.tsym);
+ Type asSuperOfS = types.asSuper(s, lubResult.tsym);
+ return new Pair<>(asSuperOfT, asSuperOfS);
+ }
+
/**
* This enumeration defines an entry point for doing inference variable
* bound incorporation - it can be used to inject custom incorporation
@@ -681,6 +707,53 @@ public class Infer {
uv.getBounds(InferenceBound.LOWER).nonEmpty();
}
},
+ /**
+ * Given a bound set containing {@code alpha <: P} and
+ * {@code alpha <: P} where P is a parameterized type,
+ * perform {@code T = S} (which could lead to new bounds).
+ */
+ CROSS_UPPER_UPPER() {
+ @Override
+ public void apply(UndetVar uv, InferenceContext inferenceContext, Warner warn) {
+ Infer infer = inferenceContext.infer();
+ List boundList = uv.getBounds(InferenceBound.UPPER);
+ List boundListTail = boundList.tail;
+ while (boundList.nonEmpty()) {
+ List tmpTail = boundListTail;
+ while (tmpTail.nonEmpty()) {
+ Type b1 = boundList.head;
+ Type b2 = tmpTail.head;
+ if (b1 != b2) {
+ Pair commonSupers = infer.getParameterizedSupers(b1, b2);
+ if (commonSupers != null) {
+ List allParamsSuperBound1 = commonSupers.fst.allparams();
+ List allParamsSuperBound2 = commonSupers.snd.allparams();
+ while (allParamsSuperBound1.nonEmpty() && allParamsSuperBound2.nonEmpty()) {
+ //traverse the list of all params comparing them
+ if (!allParamsSuperBound1.head.hasTag(WILDCARD) &&
+ !allParamsSuperBound2.head.hasTag(WILDCARD)) {
+ isSameType(inferenceContext.asUndetVar(allParamsSuperBound1.head),
+ inferenceContext.asUndetVar(allParamsSuperBound2.head), infer);
+ }
+ allParamsSuperBound1 = allParamsSuperBound1.tail;
+ allParamsSuperBound2 = allParamsSuperBound2.tail;
+ }
+ Assert.check(allParamsSuperBound1.isEmpty() && allParamsSuperBound2.isEmpty());
+ }
+ }
+ tmpTail = tmpTail.tail;
+ }
+ boundList = boundList.tail;
+ boundListTail = boundList.tail;
+ }
+ }
+
+ @Override
+ boolean accepts(UndetVar uv, InferenceContext inferenceContext) {
+ return !uv.isCaptured() &&
+ uv.getBounds(InferenceBound.UPPER).nonEmpty();
+ }
+ },
/**
* Given a bound set containing {@code alpha == S} and {@code alpha == T}
* perform {@code S == T} (which could lead to new bounds).
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java b/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
index 5714524afeb..5f686ac5190 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
@@ -1893,11 +1893,11 @@ public class LambdaToMethod extends TreeTranslator {
};
break;
case LOCAL_VAR:
- ret = new VarSymbol(FINAL, name, types.erasure(sym.type), translatedSym);
+ ret = new VarSymbol(sym.flags() & FINAL, name, types.erasure(sym.type), translatedSym);
((VarSymbol) ret).pos = ((VarSymbol) sym).pos;
break;
case PARAM:
- ret = new VarSymbol(FINAL | PARAMETER, name, types.erasure(sym.type), translatedSym);
+ ret = new VarSymbol((sym.flags() & FINAL) | PARAMETER, name, types.erasure(sym.type), translatedSym);
((VarSymbol) ret).pos = ((VarSymbol) sym).pos;
break;
default:
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java b/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java
index 31f5095e93b..269fd1938ef 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/Lower.java
@@ -2359,6 +2359,7 @@ public class Lower extends TreeTranslator {
/** Visitor method: Translate a single node.
* Attach the source position from the old tree to its replacement tree.
*/
+ @Override
public T translate(T tree) {
if (tree == null) {
return null;
@@ -2407,39 +2408,39 @@ public class Lower extends TreeTranslator {
return trees;
}
- public void visitTopLevel(JCCompilationUnit tree) {
- if (needPackageInfoClass(tree)) {
- Name name = names.package_info;
- long flags = Flags.ABSTRACT | Flags.INTERFACE;
- if (target.isPackageInfoSynthetic())
- // package-info is marked SYNTHETIC in JDK 1.6 and later releases
- flags = flags | Flags.SYNTHETIC;
- JCClassDecl packageAnnotationsClass
- = make.ClassDef(make.Modifiers(flags,
- tree.packageAnnotations),
- name, List.nil(),
- null, List.nil(), List.nil());
- ClassSymbol c = tree.packge.package_info;
- c.flags_field |= flags;
- c.setAttributes(tree.packge);
- ClassType ctype = (ClassType) c.type;
- ctype.supertype_field = syms.objectType;
- ctype.interfaces_field = List.nil();
- packageAnnotationsClass.sym = c;
+ public void visitPackageDef(JCPackageDecl tree) {
+ if (!needPackageInfoClass(tree))
+ return;
- translated.append(packageAnnotationsClass);
- }
+ Name name = names.package_info;
+ long flags = Flags.ABSTRACT | Flags.INTERFACE;
+ if (target.isPackageInfoSynthetic())
+ // package-info is marked SYNTHETIC in JDK 1.6 and later releases
+ flags = flags | Flags.SYNTHETIC;
+ JCClassDecl packageAnnotationsClass
+ = make.ClassDef(make.Modifiers(flags, tree.getAnnotations()),
+ name, List.nil(),
+ null, List.nil(), List.nil());
+ ClassSymbol c = tree.packge.package_info;
+ c.flags_field |= flags;
+ c.setAttributes(tree.packge);
+ ClassType ctype = (ClassType) c.type;
+ ctype.supertype_field = syms.objectType;
+ ctype.interfaces_field = List.nil();
+ packageAnnotationsClass.sym = c;
+
+ translated.append(packageAnnotationsClass);
}
// where
- private boolean needPackageInfoClass(JCCompilationUnit tree) {
+ private boolean needPackageInfoClass(JCPackageDecl pd) {
switch (pkginfoOpt) {
case ALWAYS:
return true;
case LEGACY:
- return tree.packageAnnotations.nonEmpty();
+ return pd.getAnnotations().nonEmpty();
case NONEMPTY:
for (Attribute.Compound a :
- tree.packge.getDeclarationAttributes()) {
+ pd.packge.getDeclarationAttributes()) {
Attribute.RetentionPolicy p = types.getRetention(a);
if (p != Attribute.RetentionPolicy.SOURCE)
return true;
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java b/langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java
index 3e002c7d501..ffecda19573 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/MemberEnter.java
@@ -493,10 +493,26 @@ public class MemberEnter extends JCTree.Visitor implements Completer {
return;
}
+ DiagnosticPosition prevLintPos = deferredLintHandler.immediate();
+ Lint prevLint = chk.setLint(lint);
+
+ try {
+ // Import-on-demand java.lang.
+ importAll(tree.pos, syms.enterPackage(names.java_lang), env);
+
+ // Process the package def and all import clauses.
+ memberEnter(tree.defs, env);
+ } finally {
+ chk.setLint(prevLint);
+ deferredLintHandler.setPos(prevLintPos);
+ }
+ }
+
+ public void visitPackageDef(JCPackageDecl tree) {
// check that no class exists with same fully qualified name as
// toplevel package
if (checkClash && tree.pid != null) {
- Symbol p = tree.packge;
+ Symbol p = env.toplevel.packge;
while (p.owner != syms.rootPackage) {
p.owner.complete(); // enter all class members of p
if (syms.classes.get(p.getQualifiedName()) != null) {
@@ -507,23 +523,8 @@ public class MemberEnter extends JCTree.Visitor implements Completer {
p = p.owner;
}
}
-
// process package annotations
- annotate.annotateLater(tree.packageAnnotations, env, tree.packge, null);
-
- DiagnosticPosition prevLintPos = deferredLintHandler.immediate();
- Lint prevLint = chk.setLint(lint);
-
- try {
- // Import-on-demand java.lang.
- importAll(tree.pos, syms.enterPackage(names.java_lang), env);
-
- // Process all import clauses.
- memberEnter(tree.defs, env);
- } finally {
- chk.setLint(prevLint);
- deferredLintHandler.setPos(prevLintPos);
- }
+ annotate.annotateLater(tree.annotations, env, env.toplevel.packge, null);
}
// process the non-static imports and the static imports of types.
diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java
index c1fdd998dec..87bddd8b2e2 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassReader.java
@@ -475,14 +475,14 @@ public class ClassReader {
break;
case CONSTANT_Fieldref: {
ClassSymbol owner = readClassSymbol(getChar(index + 1));
- NameAndType nt = (NameAndType)readPool(getChar(index + 3));
+ NameAndType nt = readNameAndType(getChar(index + 3));
poolObj[i] = new VarSymbol(0, nt.name, nt.uniqueType.type, owner);
break;
}
case CONSTANT_Methodref:
case CONSTANT_InterfaceMethodref: {
ClassSymbol owner = readClassSymbol(getChar(index + 1));
- NameAndType nt = (NameAndType)readPool(getChar(index + 3));
+ NameAndType nt = readNameAndType(getChar(index + 3));
poolObj[i] = new MethodSymbol(0, nt.name, nt.uniqueType.type, owner);
break;
}
@@ -551,13 +551,34 @@ public class ClassReader {
/** Read class entry.
*/
ClassSymbol readClassSymbol(int i) {
- return (ClassSymbol) (readPool(i));
+ Object obj = readPool(i);
+ if (obj != null && !(obj instanceof ClassSymbol))
+ throw badClassFile("bad.const.pool.entry",
+ currentClassFile.toString(),
+ "CONSTANT_Class_info", i);
+ return (ClassSymbol)obj;
}
/** Read name.
*/
Name readName(int i) {
- return (Name) (readPool(i));
+ Object obj = readPool(i);
+ if (obj != null && !(obj instanceof Name))
+ throw badClassFile("bad.const.pool.entry",
+ currentClassFile.toString(),
+ "CONSTANT_Utf8_info or CONSTANT_String_info", i);
+ return (Name)obj;
+ }
+
+ /** Read name and type.
+ */
+ NameAndType readNameAndType(int i) {
+ Object obj = readPool(i);
+ if (obj != null && !(obj instanceof NameAndType))
+ throw badClassFile("bad.const.pool.entry",
+ currentClassFile.toString(),
+ "CONSTANT_NameAndType_info", i);
+ return (NameAndType)obj;
}
/************************************************************************
@@ -1209,7 +1230,7 @@ public class ClassReader {
sym.owner.members().remove(sym);
ClassSymbol self = (ClassSymbol)sym;
ClassSymbol c = readClassSymbol(nextChar());
- NameAndType nt = (NameAndType)readPool(nextChar());
+ NameAndType nt = readNameAndType(nextChar());
if (c.members_field == null)
throw badClassFile("bad.enclosing.class", self, c);
@@ -1542,7 +1563,7 @@ public class ClassReader {
final int exception_index = nextChar();
final TypeAnnotationPosition position =
TypeAnnotationPosition.exceptionParameter(readTypePath());
- position.exception_index = exception_index;
+ position.setExceptionIndex(exception_index);
return position;
}
// method receiver
diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java
index 13e910ce559..9df21523c10 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/ClassWriter.java
@@ -925,7 +925,7 @@ public class ClassWriter extends ClassFile {
break;
// exception parameter
case EXCEPTION_PARAMETER:
- databuf.appendChar(p.exception_index);
+ databuf.appendChar(p.getExceptionIndex());
break;
// method receiver
case METHOD_RECEIVER:
diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java
index dacf206426f..081146cc2c5 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Code.java
@@ -2148,27 +2148,18 @@ public class Code {
for (Attribute.TypeCompound ta : lv.sym.getRawTypeAttributes()) {
TypeAnnotationPosition p = ta.position;
- // At this point p.type_index contains the catch type index.
- // Use that index to determine the exception table index.
- // We can afterwards discard the type_index.
- // A TA position is shared for all type annotations in the
- // same location; updating one is enough.
- // Use -666 as a marker that the exception_index was already updated.
- if (p.type_index != -666) {
- p.exception_index = findExceptionIndex(p.type_index);
- p.type_index = -666;
+ if (p.hasCatchType()) {
+ final int idx = findExceptionIndex(p.getCatchType());
+ if (idx == -1)
+ Assert.error("Could not find exception index for type annotation " +
+ ta + " on exception parameter");
+ p.setExceptionIndex(idx);
}
}
}
}
private int findExceptionIndex(int catchType) {
- if (catchType == Integer.MIN_VALUE) {
- // We didn't set the catch type index correctly.
- // This shouldn't happen.
- // TODO: issue error?
- return -1;
- }
List iter = catchInfo.toList();
int len = catchInfo.length();
for (int i = 0; i < len; ++i) {
diff --git a/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java b/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java
index e1bda1c736d..38976c97e15 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/jvm/Gen.java
@@ -1647,7 +1647,7 @@ public class Gen extends JCTree.Visitor {
if (subCatch.type.isAnnotated()) {
for (Attribute.TypeCompound tc :
subCatch.type.getAnnotationMirrors()) {
- tc.position.type_index = catchType;
+ tc.position.setCatchType(catchType);
}
}
}
@@ -1664,7 +1664,7 @@ public class Gen extends JCTree.Visitor {
if (subCatch.type.isAnnotated()) {
for (Attribute.TypeCompound tc :
subCatch.type.getAnnotationMirrors()) {
- tc.position.type_index = catchType;
+ tc.position.setCatchType(catchType);
}
}
}
diff --git a/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java b/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java
index 18db5cf5554..90883092e3a 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/main/JavaCompiler.java
@@ -601,8 +601,7 @@ public class JavaCompiler {
*/
protected JCCompilationUnit parse(JavaFileObject filename, CharSequence content) {
long msec = now();
- JCCompilationUnit tree = make.TopLevel(List.nil(),
- null, List.nil());
+ JCCompilationUnit tree = make.TopLevel(List.nil());
if (content != null) {
if (verbose) {
log.printVerbose("parsing.started", filename);
@@ -689,7 +688,7 @@ public class JavaCompiler {
: make.Select(tree, names.fromString(s));
}
JCCompilationUnit toplevel =
- make.TopLevel(List.nil(), null, List.nil());
+ make.TopLevel(List.nil());
toplevel.packge = syms.unnamedPackage;
return attr.attribIdent(tree, toplevel);
} finally {
@@ -768,7 +767,7 @@ public class JavaCompiler {
tree = parse(filename, filename.getCharContent(false));
} catch (IOException e) {
log.error("error.reading.file", filename, JavacFileManager.getMessage(e));
- tree = make.TopLevel(List.nil(), null, List.nil());
+ tree = make.TopLevel(List.nil());
} finally {
log.useSource(prev);
}
@@ -1440,7 +1439,7 @@ public class JavaCompiler {
make.at(Position.FIRSTPOS);
TreeMaker localMake = make.forToplevel(env.toplevel);
- if (env.tree instanceof JCCompilationUnit) {
+ if (env.tree.hasTag(JCTree.Tag.PACKAGEDEF)) {
if (!(stubOutput || sourceOutput || printFlat)) {
if (shouldStop(CompileState.LOWER))
return;
diff --git a/langtools/src/share/classes/com/sun/tools/javac/model/JavacElements.java b/langtools/src/share/classes/com/sun/tools/javac/model/JavacElements.java
index dbe7bb59d7c..f04fb38c83d 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/model/JavacElements.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/model/JavacElements.java
@@ -170,8 +170,8 @@ public class JavacElements implements Elements {
Symbol sym = cast(Symbol.class, e);
class Vis extends JCTree.Visitor {
List result = null;
- public void visitTopLevel(JCCompilationUnit tree) {
- result = tree.packageAnnotations;
+ public void visitPackageDef(JCPackageDecl tree) {
+ result = tree.annotations;
}
public void visitClassDef(JCClassDecl tree) {
result = tree.mods.annotations;
diff --git a/langtools/src/share/classes/com/sun/tools/javac/parser/JavacParser.java b/langtools/src/share/classes/com/sun/tools/javac/parser/JavacParser.java
index c8a26f35f61..52c18418e55 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/parser/JavacParser.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/parser/JavacParser.java
@@ -3081,27 +3081,33 @@ public class JavacParser implements Parser {
*/
public JCTree.JCCompilationUnit parseCompilationUnit() {
Token firstToken = token;
- JCExpression pid = null;
JCModifiers mods = null;
boolean consumedToplevelDoc = false;
boolean seenImport = false;
boolean seenPackage = false;
- List packageAnnotations = List.nil();
+ ListBuffer defs = new ListBuffer<>();
if (token.kind == MONKEYS_AT)
mods = modifiersOpt();
if (token.kind == PACKAGE) {
+ int packagePos = token.pos;
+ List annotations = List.nil();
seenPackage = true;
if (mods != null) {
checkNoMods(mods.flags);
- packageAnnotations = mods.annotations;
+ annotations = mods.annotations;
mods = null;
}
nextToken();
- pid = qualident(false);
+ JCExpression pid = qualident(false);
accept(SEMI);
+ JCPackageDecl pd = F.at(packagePos).PackageDecl(annotations, pid);
+ attach(pd, firstToken.comment(CommentStyle.JAVADOC));
+ consumedToplevelDoc = true;
+ storeEnd(pd, token.pos);
+ defs.append(pd);
}
- ListBuffer defs = new ListBuffer<>();
+
boolean checkForImports = true;
boolean firstTypeDecl = true;
while (token.kind != EOF) {
@@ -3130,7 +3136,7 @@ public class JavacParser implements Parser {
firstTypeDecl = false;
}
}
- JCTree.JCCompilationUnit toplevel = F.at(firstToken.pos).TopLevel(packageAnnotations, pid, defs.toList());
+ JCTree.JCCompilationUnit toplevel = F.at(firstToken.pos).TopLevel(defs.toList());
if (!consumedToplevelDoc)
attach(toplevel, firstToken.comment(CommentStyle.JAVADOC));
if (defs.isEmpty())
@@ -3417,16 +3423,28 @@ public class JavacParser implements Parser {
* | ModifiersOpt
* ( Type Ident
* ( VariableDeclaratorsRest ";" | MethodDeclaratorRest )
- * | VOID Ident MethodDeclaratorRest
- * | TypeParameters (Type | VOID) Ident MethodDeclaratorRest
+ * | VOID Ident VoidMethodDeclaratorRest
+ * | TypeParameters [Annotations]
+ * ( Type Ident MethodDeclaratorRest
+ * | VOID Ident VoidMethodDeclaratorRest
+ * )
* | Ident ConstructorDeclaratorRest
* | TypeParameters Ident ConstructorDeclaratorRest
* | ClassOrInterfaceOrEnumDeclaration
* )
* InterfaceBodyDeclaration =
* ";"
- * | ModifiersOpt Type Ident
- * ( ConstantDeclaratorsRest | InterfaceMethodDeclaratorRest ";" )
+ * | ModifiersOpt
+ * ( Type Ident
+ * ( ConstantDeclaratorsRest ";" | MethodDeclaratorRest )
+ * | VOID Ident MethodDeclaratorRest
+ * | TypeParameters [Annotations]
+ * ( Type Ident MethodDeclaratorRest
+ * | VOID Ident VoidMethodDeclaratorRest
+ * )
+ * | ClassOrInterfaceOrEnumDeclaration
+ * )
+ *
*/
protected List classOrInterfaceBodyDeclaration(Name className, boolean isInterface) {
if (token.kind == SEMI) {
@@ -3458,28 +3476,29 @@ public class JavacParser implements Parser {
}
List annosAfterParams = annotationsOpt(Tag.ANNOTATION);
+ if (annosAfterParams.nonEmpty()) {
+ checkAnnotationsAfterTypeParams(annosAfterParams.head.pos);
+ mods.annotations = mods.annotations.appendList(annosAfterParams);
+ if (mods.pos == Position.NOPOS)
+ mods.pos = mods.annotations.head.pos;
+ }
+
Token tk = token;
pos = token.pos;
JCExpression type;
boolean isVoid = token.kind == VOID;
if (isVoid) {
- if (annosAfterParams.nonEmpty())
- illegal(annosAfterParams.head.pos);
type = to(F.at(pos).TypeIdent(TypeTag.VOID));
nextToken();
} else {
- if (annosAfterParams.nonEmpty()) {
- checkAnnotationsAfterTypeParams(annosAfterParams.head.pos);
- mods.annotations = mods.annotations.appendList(annosAfterParams);
- if (mods.pos == Position.NOPOS)
- mods.pos = mods.annotations.head.pos;
- }
// method returns types are un-annotated types
type = unannotatedType();
}
if (token.kind == LPAREN && !isInterface && type.hasTag(IDENT)) {
if (isInterface || tk.name() != className)
error(pos, "invalid.meth.decl.ret.type.req");
+ else if (annosAfterParams.nonEmpty())
+ illegal(annosAfterParams.head.pos);
return List.of(methodDeclaratorRest(
pos, mods, null, names.init, typarams,
isInterface, true, dc));
@@ -3511,13 +3530,9 @@ public class JavacParser implements Parser {
}
/** MethodDeclaratorRest =
- * FormalParameters BracketsOpt [Throws TypeList] ( MethodBody | [DEFAULT AnnotationValue] ";")
+ * FormalParameters BracketsOpt [THROWS TypeList] ( MethodBody | [DEFAULT AnnotationValue] ";")
* VoidMethodDeclaratorRest =
- * FormalParameters [Throws TypeList] ( MethodBody | ";")
- * InterfaceMethodDeclaratorRest =
- * FormalParameters BracketsOpt [THROWS TypeList] ";"
- * VoidInterfaceMethodDeclaratorRest =
- * FormalParameters [THROWS TypeList] ";"
+ * FormalParameters [THROWS TypeList] ( MethodBody | ";")
* ConstructorDeclaratorRest =
* "(" FormalParameterListOpt ")" [THROWS TypeList] MethodBody
*/
diff --git a/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties b/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties
index 8f792bd15e8..e8417df496a 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties
+++ b/langtools/src/share/classes/com/sun/tools/javac/resources/compiler.properties
@@ -738,6 +738,9 @@ compiler.misc.incompatible.ret.type.in.mref=\
bad return type in method reference\n\
{0}
+compiler.err.lambda.body.neither.value.nor.void.compatible=\
+ lambda body is neither value nor void compatible
+
# 0: list of type
compiler.err.incompatible.thrown.types.in.mref=\
incompatible thrown types {0} in method reference
@@ -1716,6 +1719,11 @@ compiler.err.cant.access=\
compiler.misc.bad.class.file=\
class file is invalid for class {0}
+# 0: file name, 1: expected CP entry type, 2: constant pool index
+compiler.misc.bad.const.pool.entry=\
+ bad constant pool entry in {0}\n\
+ expected {1} at index {2}
+
# 0: file name, 1: message segment
compiler.misc.bad.class.file.header=\
bad class file: {0}\n\
diff --git a/langtools/src/share/classes/com/sun/tools/javac/tree/JCTree.java b/langtools/src/share/classes/com/sun/tools/javac/tree/JCTree.java
index 10eae9fcf87..441264bccef 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/JCTree.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/JCTree.java
@@ -89,6 +89,10 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
*/
TOPLEVEL,
+ /** Package level definitions.
+ */
+ PACKAGEDEF,
+
/** Import clauses, of type Import.
*/
IMPORT,
@@ -478,9 +482,6 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
* Everything in one source file is kept in a {@linkplain JCCompilationUnit} structure.
*/
public static class JCCompilationUnit extends JCTree implements CompilationUnitTree {
- public List packageAnnotations;
- /** The tree representing the package clause. */
- public JCExpression pid;
/** All definitions in this file (ClassDef, Import, and Skip) */
public List defs;
/* The source file name. */
@@ -499,39 +500,39 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
/* An object encapsulating ending positions of source ranges indexed by
* the tree nodes they belong to. Defined only if option -Xjcov is set. */
public EndPosTable endPositions = null;
- protected JCCompilationUnit(List packageAnnotations,
- JCExpression pid,
- List defs,
- JavaFileObject sourcefile,
- PackageSymbol packge,
- ImportScope namedImportScope,
- StarImportScope starImportScope) {
- this.packageAnnotations = packageAnnotations;
- this.pid = pid;
+ protected JCCompilationUnit(List defs) {
this.defs = defs;
- this.sourcefile = sourcefile;
- this.packge = packge;
- this.namedImportScope = namedImportScope;
- this.starImportScope = starImportScope;
}
@Override
public void accept(Visitor v) { v.visitTopLevel(this); }
public Kind getKind() { return Kind.COMPILATION_UNIT; }
- public List getPackageAnnotations() {
- return packageAnnotations;
+
+ public JCPackageDecl getPackage() {
+ // PackageDecl must be the first entry if it exists
+ if (!defs.isEmpty() && defs.head.hasTag(PACKAGEDEF))
+ return (JCPackageDecl)defs.head;
+ return null;
}
+ public List getPackageAnnotations() {
+ JCPackageDecl pd = getPackage();
+ return pd != null ? pd.getAnnotations() : List.nil();
+ }
+ public ExpressionTree getPackageName() {
+ JCPackageDecl pd = getPackage();
+ return pd != null ? pd.getPackageName() : null;
+ }
+
public List getImports() {
ListBuffer imports = new ListBuffer<>();
for (JCTree tree : defs) {
if (tree.hasTag(IMPORT))
imports.append((JCImport)tree);
- else if (!tree.hasTag(SKIP))
+ else if (!tree.hasTag(PACKAGEDEF) && !tree.hasTag(SKIP))
break;
}
return imports.toList();
}
- public JCExpression getPackageName() { return pid; }
public JavaFileObject getSourceFile() {
return sourcefile;
}
@@ -541,7 +542,7 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
public List getTypeDecls() {
List typeDefs;
for (typeDefs = defs; !typeDefs.isEmpty(); typeDefs = typeDefs.tail)
- if (!typeDefs.head.hasTag(IMPORT))
+ if (!typeDefs.head.hasTag(PACKAGEDEF) && !typeDefs.head.hasTag(IMPORT))
break;
return typeDefs;
}
@@ -556,6 +557,39 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
}
}
+ /**
+ * Package definition.
+ */
+ public static class JCPackageDecl extends JCTree implements PackageTree {
+ public List annotations;
+ /** The tree representing the package clause. */
+ public JCExpression pid;
+ public PackageSymbol packge;
+ public JCPackageDecl(List annotations, JCExpression pid) {
+ this.annotations = annotations;
+ this.pid = pid;
+ }
+ @Override
+ public void accept(Visitor v) { v.visitPackageDef(this); }
+ public Kind getKind() {
+ return Kind.PACKAGE;
+ }
+ public List getAnnotations() {
+ return annotations;
+ }
+ public JCExpression getPackageName() {
+ return pid;
+ }
+ @Override
+ public R accept(TreeVisitor v, D d) {
+ return v.visitPackage(this, d);
+ }
+ @Override
+ public Tag getTag() {
+ return PACKAGEDEF;
+ }
+ }
+
/**
* An import clause.
*/
@@ -2438,9 +2472,9 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
/** An interface for tree factories
*/
public interface Factory {
- JCCompilationUnit TopLevel(List packageAnnotations,
- JCExpression pid,
- List defs);
+ JCCompilationUnit TopLevel(List defs);
+ JCPackageDecl PackageDecl(List annotations,
+ JCExpression pid);
JCImport Import(JCTree qualid, boolean staticImport);
JCClassDecl ClassDef(JCModifiers mods,
Name name,
@@ -2528,6 +2562,7 @@ public abstract class JCTree implements Tree, Cloneable, DiagnosticPosition {
*/
public static abstract class Visitor {
public void visitTopLevel(JCCompilationUnit that) { visitTree(that); }
+ public void visitPackageDef(JCPackageDecl that) { visitTree(that); }
public void visitImport(JCImport that) { visitTree(that); }
public void visitClassDef(JCClassDecl that) { visitTree(that); }
public void visitMethodDef(JCMethodDecl that) { visitTree(that); }
diff --git a/langtools/src/share/classes/com/sun/tools/javac/tree/Pretty.java b/langtools/src/share/classes/com/sun/tools/javac/tree/Pretty.java
index 9076ce47532..15d9ca586be 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/Pretty.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/Pretty.java
@@ -367,16 +367,13 @@ public class Pretty extends JCTree.Visitor {
public void printUnit(JCCompilationUnit tree, JCClassDecl cdef) throws IOException {
docComments = tree.docComments;
printDocComment(tree);
- if (tree.pid != null) {
- print("package ");
- printExpr(tree.pid);
- print(";");
- println();
- }
+
boolean firstImport = true;
for (List l = tree.defs;
- l.nonEmpty() && (cdef == null || l.head.hasTag(IMPORT));
- l = l.tail) {
+ l.nonEmpty() &&
+ (cdef == null ||
+ l.head.hasTag(IMPORT) || l.head.hasTag(PACKAGEDEF));
+ l = l.tail) {
if (l.head.hasTag(IMPORT)) {
JCImport imp = (JCImport)l.head;
Name name = TreeInfo.name(imp.qualid);
@@ -426,6 +423,21 @@ public class Pretty extends JCTree.Visitor {
}
}
+ public void visitPackageDef(JCPackageDecl tree) {
+ try {
+ printDocComment(tree);
+ printAnnotations(tree.annotations);
+ if (tree.pid != null) {
+ print("package ");
+ printExpr(tree.pid);
+ print(";");
+ println();
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ }
+
public void visitImport(JCImport tree) {
try {
print("import ");
diff --git a/langtools/src/share/classes/com/sun/tools/javac/tree/TreeCopier.java b/langtools/src/share/classes/com/sun/tools/javac/tree/TreeCopier.java
index c2e2e004a10..b9bd7b0f317 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/TreeCopier.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/TreeCopier.java
@@ -346,10 +346,15 @@ public class TreeCopier
implements TreeVisitor {
public JCTree visitCompilationUnit(CompilationUnitTree node, P p) {
JCCompilationUnit t = (JCCompilationUnit) node;
- List packageAnnotations = copy(t.packageAnnotations, p);
- JCExpression pid = copy(t.pid, p);
List